feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,34 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
/**
*
* @author Martin Grebac
*/
public interface Builder<T> {
T build();
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import javax.activation.DataSource;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
/**
* {@link DataSource} backed by a byte buffer.
*
* @author Kohsuke Kawaguchi
*/
public final class ByteArrayDataSource implements DataSource {
private final String contentType;
private final byte[] buf;
private final int len;
public ByteArrayDataSource(byte[] buf, String contentType) {
this(buf,buf.length,contentType);
}
public ByteArrayDataSource(byte[] buf, int length, String contentType) {
this.buf = buf;
this.len = length;
this.contentType = contentType;
}
public String getContentType() {
if(contentType==null)
return "application/octet-stream";
return contentType;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(buf,0,len);
}
public String getName() {
return null;
}
public OutputStream getOutputStream() {
throw new UnsupportedOperationException();
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import java.util.ArrayList;
import java.util.Collection;
/**
* {@link ArrayList} with the final keyword.
*
* <p>
* This gives HotSpot a better hint that all methods can be inlined.
*
* @author Kohsuke Kawaguchi
*/
public final class FinalArrayList<T> extends ArrayList<T> {
public FinalArrayList(int initialCapacity) {
super(initialCapacity);
}
public FinalArrayList() {
}
public FinalArrayList(Collection<? extends T> ts) {
super(ts);
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ContentHandler;
/**
* {@link XMLFilterImpl} that masks start/end document SAX events.
* @author Kohsuke Kawaguchi
*/
public class FragmentContentHandler extends XMLFilterImpl {
public FragmentContentHandler() {
}
public FragmentContentHandler(XMLReader parent) {
super(parent);
}
public FragmentContentHandler(ContentHandler handler) {
super();
setContentHandler(handler);
}
public void startDocument() throws SAXException {
// noop
}
public void endDocument() throws SAXException {
// noop
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
/**
* Designates that a field, return value, argument, or a variable is supposed
* to be an {@link String#intern() interned} string.
*
* <p>
* In many places in the istack, we assume Strings to be interned for
* the performance reason. Similarly, In many other places, we don't
* make such an assumption for the performance reason (because intern
* isn't free.)
*
* <p>
* Therefore, distinguishing which part is supposed to be interned and
* which part is supposed to be not is important. This annotation
* allows us to capture that in the code.
*
* @author Kohsuke Kawaguchi
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER,ElementType.LOCAL_VARIABLE})
public @interface Interned {
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
/**
* Designates that a field, return value, argument, or a variable is guaranteed to be non-null.
*
* @author Kohsuke Kawaguchi
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER,ElementType.LOCAL_VARIABLE})
public @interface NotNull {
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
/**
* Designates that a field, return value, argument, or a variable may be null.
*
* @author Kohsuke Kawaguchi
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.PARAMETER,ElementType.LOCAL_VARIABLE})
public @interface Nullable {
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.lang.ref.WeakReference;
/**
* Pool of reusable objects that are indistinguishable from each other,
* such as JAXB marshallers.
*
* @author Kohsuke Kawaguchi
*/
public interface Pool<T> {
/**
* Gets a new object from the pool.
*
* <p>
* If no object is available in the pool, this method creates a new one.
*/
@NotNull T take();
/**
* Returns an object back to the pool.
*/
void recycle(@NotNull T t);
/**
* Default implementation that uses {@link ConcurrentLinkedQueue}
* as the data store.
*
* <h2>Note for Implementors</h2>
* <p>
* Don't rely on the fact that this class extends from {@link ConcurrentLinkedQueue}.
*/
public abstract class Impl<T> implements Pool<T> {
private volatile WeakReference<ConcurrentLinkedQueue<T>> queue;
/**
* Gets a new object from the pool.
*
* <p>
* If no object is available in the pool, this method creates a new one.
*
* @return
* always non-null.
*/
public final @NotNull T take() {
T t = getQueue().poll();
if(t==null) {
return create();
}
return t;
}
/**
* Returns an object back to the pool.
*/
public final void recycle(T t) {
getQueue().offer(t);
}
private ConcurrentLinkedQueue<T> getQueue() {
WeakReference<ConcurrentLinkedQueue<T>> q = queue;
if (q != null) {
ConcurrentLinkedQueue<T> d = q.get();
if (d != null) {
return d;
}
}
// overwrite the queue
ConcurrentLinkedQueue<T> d = new ConcurrentLinkedQueue<T>();
queue = new WeakReference<ConcurrentLinkedQueue<T>>(d);
return d;
}
/**
* Creates a new instance of object.
*
* <p>
* This method is used when someone wants to
* {@link #take() take} an object from an empty pool.
*
* <p>
* Also note that multiple threads may call this method
* concurrently.
*/
protected abstract @NotNull T create();
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import org.xml.sax.SAXException;
/**
* {@link SAXException} that handles exception chaining correctly.
*
* @author Kohsuke Kawaguchi
* @since 2.0 FCS
*/
public class SAXException2 extends SAXException {
public SAXException2(String message) {
super(message);
}
public SAXException2(Exception e) {
super(e);
}
public SAXException2(String message, Exception e) {
super(message, e);
}
public Throwable getCause() {
return getException();
}
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import org.xml.sax.SAXParseException;
import org.xml.sax.Locator;
/**
* {@link SAXParseException} that handles exception chaining correctly.
*
* @author Kohsuke Kawaguchi
* @since 2.0 FCS
*/
public class SAXParseException2 extends SAXParseException {
public SAXParseException2(String message, Locator locator) {
super(message, locator);
}
public SAXParseException2(String message, Locator locator, Exception e) {
super(message, locator, e);
}
public SAXParseException2(String message, String publicId, String systemId, int lineNumber, int columnNumber) {
super(message, publicId, systemId, lineNumber, columnNumber);
}
public SAXParseException2(String message, String publicId, String systemId, int lineNumber, int columnNumber, Exception e) {
super(message, publicId, systemId, lineNumber, columnNumber, e);
}
public Throwable getCause() {
return getException();
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.Location;
/**
* {@link XMLStreamException} that properly handles exception chaining.
*
* @author Kohsuke Kawaguchi
*/
public class XMLStreamException2 extends XMLStreamException {
public XMLStreamException2(String msg) {
super(msg);
}
public XMLStreamException2(Throwable th) {
super(th);
}
public XMLStreamException2(String msg, Throwable th) {
super(msg, th);
}
public XMLStreamException2(String msg, Location location) {
super(msg, location);
}
public XMLStreamException2(String msg, Location location, Throwable th) {
super(msg, location, th);
}
/**
* {@link XMLStreamException} doesn't return the correct cause.
*/
public Throwable getCause() {
return getNestedException();
}
}

View File

@@ -0,0 +1,388 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.Locator;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.namespace.QName;
/**
* This is a simple utility class that adapts StAX events from an
* {@link XMLStreamReader} to SAX events on a
* {@link ContentHandler}, bridging between the two
* parser technologies.
*
* @author Ryan.Shoemaker@Sun.COM
* @version 1.0
*/
public class XMLStreamReaderToContentHandler {
// StAX event source
private final XMLStreamReader staxStreamReader;
// SAX event sink
private final ContentHandler saxHandler;
// if true, when the conversion is completed, leave the cursor to the last
// event that was fired (such as end element)
private final boolean eagerQuit;
/**
* If true, not start/endDocument event.
*/
private final boolean fragment;
// array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
private final String[] inscopeNamespaces;
/**
* @see #XMLStreamReaderToContentHandler(XMLStreamReader, ContentHandler, boolean, boolean, String[])
*/
public XMLStreamReaderToContentHandler(XMLStreamReader staxCore, ContentHandler saxCore, boolean eagerQuit, boolean fragment) {
this(staxCore, saxCore, eagerQuit, fragment, new String[0]);
}
/**
* Construct a new StAX to SAX adapter that will convert a StAX event
* stream into a SAX event stream.
*
* @param staxCore
* StAX event source
* @param saxCore
* SAXevent sink
* @param eagerQuit
* @param fragment
* @param inscopeNamespaces
* array of the even length of the form { prefix0, uri0, prefix1, uri1, ... }
*/
public XMLStreamReaderToContentHandler(XMLStreamReader staxCore, ContentHandler saxCore,
boolean eagerQuit, boolean fragment, String[] inscopeNamespaces) {
this.staxStreamReader = staxCore;
this.saxHandler = saxCore;
this.eagerQuit = eagerQuit;
this.fragment = fragment;
this.inscopeNamespaces = inscopeNamespaces;
assert inscopeNamespaces.length%2 == 0;
}
/*
* @see StAXReaderToContentHandler#bridge()
*/
public void bridge() throws XMLStreamException {
try {
// remembers the nest level of elements to know when we are done.
int depth=0;
// if the parser is at the start tag, proceed to the first element
int event = staxStreamReader.getEventType();
if(event == XMLStreamConstants.START_DOCUMENT) {
// nextTag doesn't correctly handle DTDs
while( !staxStreamReader.isStartElement() )
event = staxStreamReader.next();
}
if( event!=XMLStreamConstants.START_ELEMENT)
throw new IllegalStateException("The current event is not START_ELEMENT\n but " + event);
handleStartDocument();
for(int i=0; i < inscopeNamespaces.length; i+=2) {
saxHandler.startPrefixMapping(inscopeNamespaces[i], inscopeNamespaces[i+1]);
}
OUTER:
do {
// These are all of the events listed in the javadoc for
// XMLEvent.
// The spec only really describes 11 of them.
switch (event) {
case XMLStreamConstants.START_ELEMENT :
depth++;
handleStartElement();
break;
case XMLStreamConstants.END_ELEMENT :
handleEndElement();
depth--;
if(depth==0 && eagerQuit)
break OUTER;
break;
case XMLStreamConstants.CHARACTERS :
handleCharacters();
break;
case XMLStreamConstants.ENTITY_REFERENCE :
handleEntityReference();
break;
case XMLStreamConstants.PROCESSING_INSTRUCTION :
handlePI();
break;
case XMLStreamConstants.COMMENT :
handleComment();
break;
case XMLStreamConstants.DTD :
handleDTD();
break;
case XMLStreamConstants.ATTRIBUTE :
handleAttribute();
break;
case XMLStreamConstants.NAMESPACE :
handleNamespace();
break;
case XMLStreamConstants.CDATA :
handleCDATA();
break;
case XMLStreamConstants.ENTITY_DECLARATION :
handleEntityDecl();
break;
case XMLStreamConstants.NOTATION_DECLARATION :
handleNotationDecl();
break;
case XMLStreamConstants.SPACE :
handleSpace();
break;
default :
throw new InternalError("processing event: " + event);
}
event=staxStreamReader.next();
} while (depth!=0);
for(int i=0; i < inscopeNamespaces.length; i+=2) {
saxHandler.endPrefixMapping(inscopeNamespaces[i]);
}
handleEndDocument();
} catch (SAXException e) {
throw new XMLStreamException2(e);
}
}
private void handleEndDocument() throws SAXException {
if(fragment)
return;
saxHandler.endDocument();
}
private void handleStartDocument() throws SAXException {
if(fragment)
return;
saxHandler.setDocumentLocator(new Locator() {
public int getColumnNumber() {
return staxStreamReader.getLocation().getColumnNumber();
}
public int getLineNumber() {
return staxStreamReader.getLocation().getLineNumber();
}
public String getPublicId() {
return staxStreamReader.getLocation().getPublicId();
}
public String getSystemId() {
return staxStreamReader.getLocation().getSystemId();
}
});
saxHandler.startDocument();
}
private void handlePI() throws XMLStreamException {
try {
saxHandler.processingInstruction(
staxStreamReader.getPITarget(),
staxStreamReader.getPIData());
} catch (SAXException e) {
throw new XMLStreamException2(e);
}
}
private void handleCharacters() throws XMLStreamException {
try {
saxHandler.characters(
staxStreamReader.getTextCharacters(),
staxStreamReader.getTextStart(),
staxStreamReader.getTextLength() );
} catch (SAXException e) {
throw new XMLStreamException2(e);
}
}
private void handleEndElement() throws XMLStreamException {
QName qName = staxStreamReader.getName();
try {
String pfix = qName.getPrefix();
String rawname = (pfix == null || pfix.length() == 0)
? qName.getLocalPart()
: pfix + ':' + qName.getLocalPart();
// fire endElement
saxHandler.endElement(
qName.getNamespaceURI(),
qName.getLocalPart(),
rawname);
// end namespace bindings
int nsCount = staxStreamReader.getNamespaceCount();
for (int i = nsCount - 1; i >= 0; i--) {
String prefix = staxStreamReader.getNamespacePrefix(i);
if (prefix == null) { // true for default namespace
prefix = "";
}
saxHandler.endPrefixMapping(prefix);
}
} catch (SAXException e) {
throw new XMLStreamException2(e);
}
}
private void handleStartElement() throws XMLStreamException {
try {
// start namespace bindings
int nsCount = staxStreamReader.getNamespaceCount();
for (int i = 0; i < nsCount; i++) {
saxHandler.startPrefixMapping(
fixNull(staxStreamReader.getNamespacePrefix(i)),
fixNull(staxStreamReader.getNamespaceURI(i)));
}
// fire startElement
QName qName = staxStreamReader.getName();
String prefix = qName.getPrefix();
String rawname;
if(prefix==null || prefix.length()==0)
rawname = qName.getLocalPart();
else
rawname = prefix + ':' + qName.getLocalPart();
Attributes attrs = getAttributes();
saxHandler.startElement(
qName.getNamespaceURI(),
qName.getLocalPart(),
rawname,
attrs);
} catch (SAXException e) {
throw new XMLStreamException2(e);
}
}
private static String fixNull(String s) {
if(s==null) return "";
else return s;
}
/**
* Get the attributes associated with the given START_ELEMENT or ATTRIBUTE
* StAXevent.
*
* @return the StAX attributes converted to an org.xml.sax.Attributes
*/
private Attributes getAttributes() {
AttributesImpl attrs = new AttributesImpl();
int eventType = staxStreamReader.getEventType();
if (eventType != XMLStreamConstants.ATTRIBUTE
&& eventType != XMLStreamConstants.START_ELEMENT) {
throw new InternalError(
"getAttributes() attempting to process: " + eventType);
}
// in SAX, namespace declarations are not part of attributes by default.
// (there's a property to control that, but as far as we are concerned
// we don't use it.) So don't add xmlns:* to attributes.
// gather non-namespace attrs
for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) {
String uri = staxStreamReader.getAttributeNamespace(i);
if(uri==null) uri="";
String localName = staxStreamReader.getAttributeLocalName(i);
String prefix = staxStreamReader.getAttributePrefix(i);
String qName;
if(prefix==null || prefix.length()==0)
qName = localName;
else
qName = prefix + ':' + localName;
String type = staxStreamReader.getAttributeType(i);
String value = staxStreamReader.getAttributeValue(i);
attrs.addAttribute(uri, localName, qName, type, value);
}
return attrs;
}
private void handleNamespace() {
// no-op ???
// namespace events don't normally occur outside of a startElement
// or endElement
}
private void handleAttribute() {
// no-op ???
// attribute events don't normally occur outside of a startElement
// or endElement
}
private void handleDTD() {
// no-op ???
// it seems like we need to pass this info along, but how?
}
private void handleComment() {
// no-op ???
}
private void handleEntityReference() {
// no-op ???
}
private void handleSpace() {
// no-op ???
// this event is listed in the javadoc, but not in the spec.
}
private void handleNotationDecl() {
// no-op ???
// this event is listed in the javadoc, but not in the spec.
}
private void handleEntityDecl() {
// no-op ???
// this event is listed in the javadoc, but not in the spec.
}
private void handleCDATA() {
// no-op ???
// this event is listed in the javadoc, but not in the spec.
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.localization;
/**
* Localizable message.
*
* @author WS Development Team
*/
public interface Localizable {
/**
* Gets the key in the resource bundle.
*
* @return
* if this method returns {@link #NOT_LOCALIZABLE},
* that means the message is not localizable, and
* the first item of {@link #getArguments()} array
* holds a String.
*/
public String getKey();
/**
* Returns the arguments for message formatting.
*
* @return
* can be an array of length 0 but never be null.
*/
public Object[] getArguments();
public String getResourceBundleName();
/**
* Special constant that represents a message that
* is not localizable.
*
* <p>
* Use of "new" is to create an unique instance.
*/
public static final String NOT_LOCALIZABLE = "\u0000";
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.localization;
import java.util.Arrays;
/**
* @author WS Development Team
*/
public final class LocalizableMessage implements Localizable {
private final String _bundlename;
private final String _key;
private final Object[] _args;
public LocalizableMessage(String bundlename, String key, Object... args) {
_bundlename = bundlename;
_key = key;
if(args==null)
args = new Object[0];
_args = args;
}
public String getKey() {
return _key;
}
public Object[] getArguments() {
return Arrays.copyOf(_args, _args.length);
}
public String getResourceBundleName() {
return _bundlename;
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.localization;
/**
* @author WS Development Team
*/
public class LocalizableMessageFactory {
private final String _bundlename;
public LocalizableMessageFactory(String bundlename) {
_bundlename = bundlename;
}
public Localizable getMessage(String key, Object... args) {
return new LocalizableMessage(_bundlename, key, args);
}
}

View File

@@ -0,0 +1,155 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.localization;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* Localizes the {@link Localizable} into a message
* by using a configured {@link Locale}.
*
* @author WS Development Team
*/
public class Localizer {
private final Locale _locale;
private final HashMap _resourceBundles;
public Localizer() {
this(Locale.getDefault());
}
public Localizer(Locale l) {
_locale = l;
_resourceBundles = new HashMap();
}
public Locale getLocale() {
return _locale;
}
public String localize(Localizable l) {
String key = l.getKey();
if (key == Localizable.NOT_LOCALIZABLE) {
// this message is not localizable
return (String) l.getArguments()[0];
}
String bundlename = l.getResourceBundleName();
try {
ResourceBundle bundle =
(ResourceBundle) _resourceBundles.get(bundlename);
if (bundle == null) {
try {
bundle = ResourceBundle.getBundle(bundlename, _locale);
} catch (MissingResourceException e) {
// work around a bug in the com.sun.enterprise.deployment.WebBundleArchivist:
// all files with an extension different from .class (hence all the .properties files)
// get copied to the top level directory instead of being in the package where they
// are defined
// so, since we can't find the bundle under its proper name, we look for it under
// the top-level package
int i = bundlename.lastIndexOf('.');
if (i != -1) {
String alternateBundleName =
bundlename.substring(i + 1);
try {
bundle =
ResourceBundle.getBundle(
alternateBundleName,
_locale);
} catch (MissingResourceException e2) {
//try context classloader
try {
bundle = ResourceBundle.getBundle(bundlename, _locale, Thread.currentThread().getContextClassLoader());
} catch (MissingResourceException e3) {
// give up
return getDefaultMessage(l);
}
}
}
}
_resourceBundles.put(bundlename, bundle);
}
if (bundle == null) {
return getDefaultMessage(l);
}
if (key == null)
key = "undefined";
String msg;
try {
msg = bundle.getString(key);
} catch (MissingResourceException e) {
// notice that this may throw a MissingResourceException of its own (caught below)
msg = bundle.getString("undefined");
}
// localize all arguments to the given localizable object
Object[] args = l.getArguments();
for (int i = 0; i < args.length; ++i) {
if (args[i] instanceof Localizable)
args[i] = localize((Localizable) args[i]);
}
String message = MessageFormat.format(msg, args);
return message;
} catch (MissingResourceException e) {
return getDefaultMessage(l);
}
}
private String getDefaultMessage(Localizable l) {
String key = l.getKey();
Object[] args = l.getArguments();
StringBuilder sb = new StringBuilder();
sb.append("[failed to localize] ");
sb.append(key);
if (args != null) {
sb.append('(');
for (int i = 0; i < args.length; ++i) {
if (i != 0)
sb.append(", ");
sb.append(String.valueOf(args[i]));
}
sb.append(')');
}
return sb.toString();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.localization;
/**
* {@link Localizable} that wraps a non-localizable string.
*
* @author WS Development Team
*/
public final class NullLocalizable implements Localizable {
private final String msg;
public NullLocalizable(String msg) {
if(msg==null)
throw new IllegalArgumentException();
this.msg = msg;
}
public String getKey() {
return Localizable.NOT_LOCALIZABLE;
}
public Object[] getArguments() {
return new Object[]{msg};
}
public String getResourceBundleName() {
return "";
}
}

View File

@@ -0,0 +1,515 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.logging;
import com.sun.istack.internal.NotNull;
import java.util.StringTokenizer;
import java.util.logging.Level;
/**
* This is a helper class that provides some convenience methods wrapped around the
* standard {@link java.util.logging.Logger} interface.
*
* The class also makes sure that logger names of each Metro subsystem are consistent
* with each other.
*
* @author Marek Potociar <marek.potociar at sun.com>
* @author Fabian Ritzmann
*/
public class Logger {
private static final String WS_LOGGING_SUBSYSTEM_NAME_ROOT = "com.sun.metro";
private static final String ROOT_WS_PACKAGE = "com.sun.xml.internal.ws.";
//
private static final Level METHOD_CALL_LEVEL_VALUE = Level.FINEST;
//
private final String componentClassName;
private final java.util.logging.Logger logger;
/**
* Prevents creation of a new instance of this Logger unless used by a subclass.
*/
protected Logger(final String systemLoggerName, final String componentName) {
this.componentClassName = "[" + componentName + "] ";
this.logger = java.util.logging.Logger.getLogger(systemLoggerName);
}
/**
* <p>
* The factory method returns preconfigured Logger wrapper for the class. Method calls
* {@link #getSystemLoggerName(java.lang.Class)} to generate default logger name.
* </p>
* <p>
* Since there is no caching implemented, it is advised that the method is called only once
* per a class in order to initialize a final static logger variable, which is then used
* through the class to perform actual logging tasks.
* </p>
*
* @param componentClass class of the component that will use the logger instance. Must not be {@code null}.
* @return logger instance preconfigured for use with the component
* @throws NullPointerException if the componentClass parameter is {@code null}.
*/
public static @NotNull Logger getLogger(final @NotNull Class<?> componentClass) {
return new Logger(getSystemLoggerName(componentClass), componentClass.getName());
}
/**
* The factory method returns preconfigured Logger wrapper for the class. Since there is no caching implemented,
* it is advised that the method is called only once per a class in order to initialize a final static logger variable,
* which is then used through the class to perform actual logging tasks.
*
* This method should be only used in a special cases when overriding of a default logger name derived from the
* package of the component class is needed. For all common use cases please use {@link #getLogger(java.lang.Class)}
* method.
*
* @param customLoggerName custom name of the logger.
* @param componentClass class of the component that will use the logger instance. Must not be {@code null}.
* @return logger instance preconfigured for use with the component
* @throws NullPointerException if the componentClass parameter is {@code null}.
*
* @see #getLogger(java.lang.Class)
*/
public static @NotNull Logger getLogger(final @NotNull String customLoggerName, final @NotNull Class<?> componentClass) {
return new Logger(customLoggerName, componentClass.getName());
}
/**
* Calculates the subsystem suffix based on the package of the component class
* @param componentClass class of the component that will use the logger instance. Must not be {@code null}.
* @return system logger name for the given {@code componentClass} instance
*/
static final String getSystemLoggerName(@NotNull Class<?> componentClass) {
StringBuilder sb = new StringBuilder(componentClass.getPackage().getName());
final int lastIndexOfWsPackage = sb.lastIndexOf(ROOT_WS_PACKAGE);
if (lastIndexOfWsPackage > -1) {
sb.replace(0, lastIndexOfWsPackage + ROOT_WS_PACKAGE.length(), "");
StringTokenizer st = new StringTokenizer(sb.toString(), ".");
sb = new StringBuilder(WS_LOGGING_SUBSYSTEM_NAME_ROOT).append(".");
if (st.hasMoreTokens()) {
String token = st.nextToken();
if ("api".equals(token)) {
token = st.nextToken();
}
sb.append(token);
}
}
return sb.toString();
}
public void log(final Level level, final String message) {
if (!this.logger.isLoggable(level)) {
return;
}
logger.logp(level, componentClassName, getCallerMethodName(), message);
}
public void log(final Level level, final String message, Object param1) {
if (!this.logger.isLoggable(level)) {
return;
}
logger.logp(level, componentClassName, getCallerMethodName(), message, param1);
}
public void log(final Level level, final String message, Object[] params) {
if (!this.logger.isLoggable(level)) {
return;
}
logger.logp(level, componentClassName, getCallerMethodName(), message, params);
}
public void log(final Level level, final String message, final Throwable thrown) {
if (!this.logger.isLoggable(level)) {
return;
}
logger.logp(level, componentClassName, getCallerMethodName(), message, thrown);
}
public void finest(final String message) {
if (!this.logger.isLoggable(Level.FINEST)) {
return;
}
logger.logp(Level.FINEST, componentClassName, getCallerMethodName(), message);
}
public void finest(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.FINEST)) {
return;
}
logger.logp(Level.FINEST, componentClassName, getCallerMethodName(), message, params);
}
public void finest(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.FINEST)) {
return;
}
logger.logp(Level.FINEST, componentClassName, getCallerMethodName(), message, thrown);
}
public void finer(final String message) {
if (!this.logger.isLoggable(Level.FINER)) {
return;
}
logger.logp(Level.FINER, componentClassName, getCallerMethodName(), message);
}
public void finer(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.FINER)) {
return;
}
logger.logp(Level.FINER, componentClassName, getCallerMethodName(), message, params);
}
public void finer(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.FINER)) {
return;
}
logger.logp(Level.FINER, componentClassName, getCallerMethodName(), message, thrown);
}
public void fine(final String message) {
if (!this.logger.isLoggable(Level.FINE)) {
return;
}
logger.logp(Level.FINE, componentClassName, getCallerMethodName(), message);
}
public void fine(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.FINE)) {
return;
}
logger.logp(Level.FINE, componentClassName, getCallerMethodName(), message, thrown);
}
public void info(final String message) {
if (!this.logger.isLoggable(Level.INFO)) {
return;
}
logger.logp(Level.INFO, componentClassName, getCallerMethodName(), message);
}
public void info(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.INFO)) {
return;
}
logger.logp(Level.INFO, componentClassName, getCallerMethodName(), message, params);
}
public void info(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.INFO)) {
return;
}
logger.logp(Level.INFO, componentClassName, getCallerMethodName(), message, thrown);
}
public void config(final String message) {
if (!this.logger.isLoggable(Level.CONFIG)) {
return;
}
logger.logp(Level.CONFIG, componentClassName, getCallerMethodName(), message);
}
public void config(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.CONFIG)) {
return;
}
logger.logp(Level.CONFIG, componentClassName, getCallerMethodName(), message, params);
}
public void config(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.CONFIG)) {
return;
}
logger.logp(Level.CONFIG, componentClassName, getCallerMethodName(), message, thrown);
}
public void warning(final String message) {
if (!this.logger.isLoggable(Level.WARNING)) {
return;
}
logger.logp(Level.WARNING, componentClassName, getCallerMethodName(), message);
}
public void warning(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.WARNING)) {
return;
}
logger.logp(Level.WARNING, componentClassName, getCallerMethodName(), message, params);
}
public void warning(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.WARNING)) {
return;
}
logger.logp(Level.WARNING, componentClassName, getCallerMethodName(), message, thrown);
}
public void severe(final String message) {
if (!this.logger.isLoggable(Level.SEVERE)) {
return;
}
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), message);
}
public void severe(final String message, Object[] params) {
if (!this.logger.isLoggable(Level.SEVERE)) {
return;
}
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), message, params);
}
public void severe(final String message, final Throwable thrown) {
if (!this.logger.isLoggable(Level.SEVERE)) {
return;
}
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), message, thrown);
}
public boolean isMethodCallLoggable() {
return this.logger.isLoggable(METHOD_CALL_LEVEL_VALUE);
}
public boolean isLoggable(final Level level) {
return this.logger.isLoggable(level);
}
public void setLevel(final Level level) {
this.logger.setLevel(level);
}
public void entering() {
if (!this.logger.isLoggable(METHOD_CALL_LEVEL_VALUE)) {
return;
}
logger.entering(componentClassName, getCallerMethodName());
}
public void entering(final Object... parameters) {
if (!this.logger.isLoggable(METHOD_CALL_LEVEL_VALUE)) {
return;
}
logger.entering(componentClassName, getCallerMethodName(), parameters);
}
public void exiting() {
if (!this.logger.isLoggable(METHOD_CALL_LEVEL_VALUE)) {
return;
}
logger.exiting(componentClassName, getCallerMethodName());
}
public void exiting(final Object result) {
if (!this.logger.isLoggable(METHOD_CALL_LEVEL_VALUE)) {
return;
}
logger.exiting(componentClassName, getCallerMethodName(), result);
}
/**
* Method logs {@code exception}'s message as a {@code SEVERE} logging level
* message.
* <p/>
* If {@code cause} parameter is not {@code null}, it is logged as well and
* {@code exception} original cause is initialized with instance referenced
* by {@code cause} parameter.
*
* @param exception exception whose message should be logged. Must not be
* {@code null}.
* @param cause initial cause of the exception that should be logged as well
* and set as {@code exception}'s original cause. May be {@code null}.
* @return the same exception instance that was passed in as the {@code exception}
* parameter.
*/
public <T extends Throwable> T logSevereException(final T exception, final Throwable cause) {
if (this.logger.isLoggable(Level.SEVERE)) {
if (cause == null) {
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage());
} else {
exception.initCause(cause);
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage(), cause);
}
}
return exception;
}
/**
* Method logs {@code exception}'s message as a {@code SEVERE} logging level
* message.
* <p/>
* If {@code logCause} parameter is {@code true}, {@code exception}'s original
* cause is logged as well (if exists). This may be used in cases when
* {@code exception}'s class provides constructor to initialize the original
* cause. In such case you do not need to use
* {@link #logSevereException(Throwable, Throwable)}
* method version but you might still want to log the original cause as well.
*
* @param exception exception whose message should be logged. Must not be
* {@code null}.
* @param logCause deterimnes whether initial cause of the exception should
* be logged as well
* @return the same exception instance that was passed in as the {@code exception}
* parameter.
*/
public <T extends Throwable> T logSevereException(final T exception, final boolean logCause) {
if (this.logger.isLoggable(Level.SEVERE)) {
if (logCause && exception.getCause() != null) {
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage(), exception.getCause());
} else {
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage());
}
}
return exception;
}
/**
* Same as {@link #logSevereException(Throwable, boolean) logSevereException(exception, true)}.
*/
public <T extends Throwable> T logSevereException(final T exception) {
if (this.logger.isLoggable(Level.SEVERE)) {
if (exception.getCause() == null) {
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage());
} else {
logger.logp(Level.SEVERE, componentClassName, getCallerMethodName(), exception.getMessage(), exception.getCause());
}
}
return exception;
}
/**
* Method logs {@code exception}'s message at the logging level specified by the
* {@code level} argument.
* <p/>
* If {@code cause} parameter is not {@code null}, it is logged as well and
* {@code exception} original cause is initialized with instance referenced
* by {@code cause} parameter.
*
* @param exception exception whose message should be logged. Must not be
* {@code null}.
* @param cause initial cause of the exception that should be logged as well
* and set as {@code exception}'s original cause. May be {@code null}.
* @param level loging level which should be used for logging
* @return the same exception instance that was passed in as the {@code exception}
* parameter.
*/
public <T extends Throwable> T logException(final T exception, final Throwable cause, final Level level) {
if (this.logger.isLoggable(level)) {
if (cause == null) {
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage());
} else {
exception.initCause(cause);
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage(), cause);
}
}
return exception;
}
/**
* Method logs {@code exception}'s message at the logging level specified by the
* {@code level} argument.
* <p/>
* If {@code logCause} parameter is {@code true}, {@code exception}'s original
* cause is logged as well (if exists). This may be used in cases when
* {@code exception}'s class provides constructor to initialize the original
* cause. In such case you do not need to use
* {@link #logException(Throwable, Throwable, Level) logException(exception, cause, level)}
* method version but you might still want to log the original cause as well.
*
* @param exception exception whose message should be logged. Must not be
* {@code null}.
* @param logCause deterimnes whether initial cause of the exception should
* be logged as well
* @param level loging level which should be used for logging
* @return the same exception instance that was passed in as the {@code exception}
* parameter.
*/
public <T extends Throwable> T logException(final T exception, final boolean logCause, final Level level) {
if (this.logger.isLoggable(level)) {
if (logCause && exception.getCause() != null) {
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage(), exception.getCause());
} else {
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage());
}
}
return exception;
}
/**
* Same as {@link #logException(Throwable, Throwable, Level)
* logException(exception, true, level)}.
*/
public <T extends Throwable> T logException(final T exception, final Level level) {
if (this.logger.isLoggable(level)) {
if (exception.getCause() == null) {
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage());
} else {
logger.logp(level, componentClassName, getCallerMethodName(), exception.getMessage(), exception.getCause());
}
}
return exception;
}
/**
* Function returns the name of the caller method for the method executing this
* function.
*
* @return caller method name from the call stack of the current {@link Thread}.
*/
private static String getCallerMethodName() {
return getStackMethodName(5);
}
/**
* Method returns the name of the method that is on the {@code methodIndexInStack}
* position in the call stack of the current {@link Thread}.
*
* @param methodIndexInStack index to the call stack to get the method name for.
* @return the name of the method that is on the {@code methodIndexInStack}
* position in the call stack of the current {@link Thread}.
*/
private static String getStackMethodName(final int methodIndexInStack) {
final String methodName;
final StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length > methodIndexInStack + 1) {
methodName = stack[methodIndexInStack].getMethodName();
} else {
methodName = "UNKNOWN METHOD";
}
return methodName;
}
}

View File

@@ -0,0 +1,29 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* istack-commons runtime utilities.
*/
package com.sun.istack.internal;

View File

@@ -0,0 +1,324 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.Authenticator;
import java.net.Authenticator.RequestorType;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.xml.sax.Locator;
import org.xml.sax.helpers.LocatorImpl;
/**
* @author Vivek Pandey
* @author Lukas Jungmann
*/
public class DefaultAuthenticator extends Authenticator {
private static DefaultAuthenticator instance;
private static Authenticator systemAuthenticator = getCurrentAuthenticator();
private String proxyUser;
private String proxyPasswd;
private final List<AuthInfo> authInfo = new ArrayList<AuthInfo>();
private static int counter = 0;
DefaultAuthenticator() {
//try undocumented but often used properties
if (System.getProperty("http.proxyUser") != null) {
proxyUser = System.getProperty("http.proxyUser");
} else {
proxyUser = System.getProperty("proxyUser");
}
if (System.getProperty("http.proxyPassword") != null) {
proxyPasswd = System.getProperty("http.proxyPassword");
} else {
proxyPasswd = System.getProperty("proxyPassword");
}
}
public static synchronized DefaultAuthenticator getAuthenticator() {
if (instance == null) {
instance = new DefaultAuthenticator();
Authenticator.setDefault(instance);
}
counter++;
return instance;
}
public static synchronized void reset() {
--counter;
if (instance != null && counter == 0) {
Authenticator.setDefault(systemAuthenticator);
}
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//If user sets proxy user and passwd and the RequestType is from proxy server then create
// PasswordAuthentication using proxyUser and proxyPasswd;
if ((getRequestorType() == RequestorType.PROXY) && proxyUser != null && proxyPasswd != null) {
return new PasswordAuthentication(proxyUser, proxyPasswd.toCharArray());
}
for (AuthInfo auth : authInfo) {
if (auth.matchingHost(getRequestingURL())) {
return new PasswordAuthentication(auth.getUser(), auth.getPassword().toCharArray());
}
}
return null;
}
/**
* Proxy authorization string in form of username:password.
*
* @param proxyAuth
*/
public void setProxyAuth(String proxyAuth) {
if (proxyAuth == null) {
this.proxyUser = null;
this.proxyPasswd = null;
} else {
int i = proxyAuth.indexOf(':');
if (i < 0) {
this.proxyUser = proxyAuth;
this.proxyPasswd = "";
} else if (i == 0) {
this.proxyUser = "";
this.proxyPasswd = proxyAuth.substring(1);
} else {
this.proxyUser = proxyAuth.substring(0, i);
this.proxyPasswd = proxyAuth.substring(i + 1);
}
}
}
public void setAuth(File f, Receiver l) {
Receiver listener = l == null ? new DefaultRImpl() : l;
BufferedReader in = null;
FileInputStream fi = null;
InputStreamReader is = null;
try {
String text;
LocatorImpl locator = new LocatorImpl();
locator.setSystemId(f.getAbsolutePath());
try {
fi = new FileInputStream(f);
is = new InputStreamReader(fi, "UTF-8");
in = new BufferedReader(is);
} catch (UnsupportedEncodingException e) {
listener.onError(e, locator);
return;
} catch (FileNotFoundException e) {
listener.onError(e, locator);
return;
}
try {
int lineno = 1;
locator.setSystemId(f.getCanonicalPath());
while ((text = in.readLine()) != null) {
locator.setLineNumber(lineno++);
//ignore empty lines and treat those starting with '#' as comments
if ("".equals(text.trim()) || text.startsWith("#")) {
continue;
}
try {
AuthInfo ai = parseLine(text);
authInfo.add(ai);
} catch (Exception e) {
listener.onParsingError(text, locator);
}
}
} catch (IOException e) {
listener.onError(e, locator);
Logger.getLogger(DefaultAuthenticator.class.getName()).log(Level.SEVERE, e.getMessage(), e);
}
} finally {
try {
if (in != null) {
in.close();
}
if (is != null) {
is.close();
}
if (fi != null) {
fi.close();
}
} catch (IOException ex) {
Logger.getLogger(DefaultAuthenticator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private AuthInfo parseLine(String text) throws Exception {
URL url;
try {
url = new URL(text);
} catch (MalformedURLException mue) {
//possible cause of this can be that password contains
//character which has to be encoded in URL,
//such as '@', ')', '#' and few others
//so try to recreate the URL with encoded string
//between 2nd ':' and last '@'
int i = text.indexOf(':', text.indexOf(':') + 1) + 1;
int j = text.lastIndexOf('@');
String encodedUrl =
text.substring(0, i)
+ URLEncoder.encode(text.substring(i, j), "UTF-8")
+ text.substring(j);
url = new URL(encodedUrl);
}
String authinfo = url.getUserInfo();
if (authinfo != null) {
int i = authinfo.indexOf(':');
if (i >= 0) {
String user = authinfo.substring(0, i);
String password = authinfo.substring(i + 1);
return new AuthInfo(
new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()),
user, URLDecoder.decode(password, "UTF-8"));
}
}
throw new Exception();
}
static Authenticator getCurrentAuthenticator() {
final Field f = getTheAuthenticator();
if (f == null) {
return null;
}
try {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
f.setAccessible(true);
return null;
}
});
return (Authenticator) f.get(null);
} catch (Exception ex) {
return null;
} finally {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
f.setAccessible(false);
return null;
}
});
}
}
private static Field getTheAuthenticator() {
try {
return Authenticator.class.getDeclaredField("theAuthenticator");
} catch (Exception ex) {
return null;
}
}
public static interface Receiver {
void onParsingError(String line, Locator loc);
void onError(Exception e, Locator loc);
}
private static class DefaultRImpl implements Receiver {
@Override
public void onParsingError(String line, Locator loc) {
System.err.println(getLocationString(loc) + ": " + line);
}
@Override
public void onError(Exception e, Locator loc) {
System.err.println(getLocationString(loc) + ": " + e.getMessage());
Logger.getLogger(DefaultAuthenticator.class.getName()).log(Level.SEVERE, e.getMessage(), e);
}
private String getLocationString(Locator l) {
return "[" + l.getSystemId() + "#" + l.getLineNumber() + "]";
}
}
/**
* Represents authorization information needed by
* {@link DefaultAuthenticator} to authenticate access to remote resources.
*
* @author Vivek Pandey
* @author Lukas Jungmann
*/
final static class AuthInfo {
private final String user;
private final String password;
private final Pattern urlPattern;
public AuthInfo(URL url, String user, String password) {
String u = url.toExternalForm().replaceFirst("\\?", "\\\\?");
this.urlPattern = Pattern.compile(u.replace("*", ".*"), Pattern.CASE_INSENSITIVE);
this.user = user;
this.password = password;
}
public String getUser() {
return user;
}
public String getPassword() {
return password;
}
/**
* Returns if the requesting host and port are associated with this
* {@link AuthInfo}
*/
public boolean matchingHost(URL requestingURL) {
return urlPattern.matcher(requestingURL.toExternalForm()).matches();
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.tools;
import java.util.Collection;
/**
* {@link ClassLoader} that masks a specified set of classes
* from its parent class loader.
*
* <p>
* This code is used to create an isolated environment.
*
* @author Kohsuke Kawaguchi
*/
public class MaskingClassLoader extends ClassLoader {
private final String[] masks;
public MaskingClassLoader(String... masks) {
this.masks = masks;
}
public MaskingClassLoader(Collection<String> masks) {
this(masks.toArray(new String[masks.size()]));
}
public MaskingClassLoader(ClassLoader parent, String... masks) {
super(parent);
this.masks = masks;
}
public MaskingClassLoader(ClassLoader parent, Collection<String> masks) {
this(parent, masks.toArray(new String[masks.size()]));
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
for (String mask : masks) {
if(name.startsWith(mask))
throw new ClassNotFoundException();
}
return super.loadClass(name, resolve);
}
}

View File

@@ -0,0 +1,217 @@
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.tools;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Load classes/resources from a side folder, so that
* classes of the same package can live in a single jar file.
*
* <p>
* For example, with the following jar file:
* <pre>
* /
* +- foo
* +- X.class
* +- bar
* +- X.class
* </pre>
* <p>
* {@link ParallelWorldClassLoader}("foo/") would load <tt>X.class<tt> from
* <tt>/foo/X.class</tt> (note that X is defined in the root package, not
* <tt>foo.X</tt>.
*
* <p>
* This can be combined with {@link MaskingClassLoader} to mask classes which are loaded by the parent
* class loader so that the child class loader
* classes living in different folders are loaded
* before the parent class loader loads classes living the jar file publicly
* visible
* For example, with the following jar file:
* <pre>
* /
* +- foo
* +- X.class
* +- bar
* +-foo
* +- X.class
* </pre>
* <p>
* {@link ParallelWorldClassLoader}(MaskingClassLoader.class.getClassLoader()) would load <tt>foo.X.class<tt> from
* <tt>/bar/foo.X.class</tt> not the <tt>foo.X.class<tt> in the publicly visible place in the jar file, thus
* masking the parent classLoader from loading the class from <tt>foo.X.class<tt>
* (note that X is defined in the package foo, not
* <tt>bar.foo.X</tt>.
*
* @author Kohsuke Kawaguchi
*/
public class ParallelWorldClassLoader extends ClassLoader implements Closeable {
/**
* Strings like "prefix/", "abc/", or "" to indicate
* classes should be loaded normally.
*/
private final String prefix;
private final Set<JarFile> jars;
public ParallelWorldClassLoader(ClassLoader parent,String prefix) {
super(parent);
this.prefix = prefix;
jars = Collections.synchronizedSet(new HashSet<JarFile>());
}
protected Class findClass(String name) throws ClassNotFoundException {
StringBuffer sb = new StringBuffer(name.length()+prefix.length()+6);
sb.append(prefix).append(name.replace('.','/')).append(".class");
URL u = getParent().getResource(sb.toString());
if (u == null) {
throw new ClassNotFoundException(name);
}
InputStream is = null;
URLConnection con = null;
try {
con = u.openConnection();
is = con.getInputStream();
} catch (IOException ioe) {
throw new ClassNotFoundException(name);
}
if (is==null)
throw new ClassNotFoundException(name);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while((len=is.read(buf))>=0)
baos.write(buf,0,len);
buf = baos.toByteArray();
int packIndex = name.lastIndexOf('.');
if (packIndex != -1) {
String pkgname = name.substring(0, packIndex);
// Check if package already loaded.
Package pkg = getPackage(pkgname);
if (pkg == null) {
definePackage(pkgname, null, null, null, null, null, null, null);
}
}
return defineClass(name,buf,0,buf.length);
} catch (IOException e) {
throw new ClassNotFoundException(name,e);
} finally {
try {
if (con != null && con instanceof JarURLConnection) {
jars.add(((JarURLConnection) con).getJarFile());
}
} catch (IOException ioe) {
//ignore
}
if (is != null) {
try {
is.close();
} catch (IOException ioe) {
//ignore
}
}
}
}
@Override
protected URL findResource(String name) {
URL u = getParent().getResource(prefix + name);
if (u != null) {
try {
jars.add(new JarFile(new File(toJarUrl(u).toURI())));
} catch (URISyntaxException ex) {
Logger.getLogger(ParallelWorldClassLoader.class.getName()).log(Level.WARNING, null, ex);
} catch (IOException ex) {
Logger.getLogger(ParallelWorldClassLoader.class.getName()).log(Level.WARNING, null, ex);
} catch (ClassNotFoundException ex) {
//ignore - not a jar
}
}
return u;
}
@Override
protected Enumeration<URL> findResources(String name) throws IOException {
Enumeration<URL> en = getParent().getResources(prefix + name);
while (en.hasMoreElements()) {
try {
jars.add(new JarFile(new File(toJarUrl(en.nextElement()).toURI())));
} catch (URISyntaxException ex) {
//should not happen
Logger.getLogger(ParallelWorldClassLoader.class.getName()).log(Level.WARNING, null, ex);
} catch (IOException ex) {
Logger.getLogger(ParallelWorldClassLoader.class.getName()).log(Level.WARNING, null, ex);
} catch (ClassNotFoundException ex) {
//ignore - not a jar
}
}
return en;
}
public synchronized void close() throws IOException {
for (JarFile jar : jars) {
jar.close();
}
}
/**
* Given the URL inside jar, returns the URL to the jar itself.
*/
public static URL toJarUrl(URL res) throws ClassNotFoundException, MalformedURLException {
String url = res.toExternalForm();
if(!url.startsWith("jar:"))
throw new ClassNotFoundException("Loaded outside a jar "+url);
url = url.substring(4); // cut off jar:
url = url.substring(0,url.lastIndexOf('!')); // cut off everything after '!'
url = url.replaceAll(" ", "%20"); // support white spaces in path
return new URL(url);
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.istack.internal.tools;
/**
* Class defined for safe calls of getClassLoader methods of any kind (context/system/class
* classloader. This MUST be package private and defined in every package which
* uses such invocations.
* @author snajper
*/
class SecureLoader {
static ClassLoader getContextClassLoader() {
if (System.getSecurityManager() == null) {
return Thread.currentThread().getContextClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return Thread.currentThread().getContextClassLoader();
}
});
}
}
static ClassLoader getClassClassLoader(final Class c) {
if (System.getSecurityManager() == null) {
return c.getClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return c.getClassLoader();
}
});
}
}
static ClassLoader getSystemClassLoader() {
if (System.getSecurityManager() == null) {
return ClassLoader.getSystemClassLoader();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return ClassLoader.getSystemClassLoader();
}
});
}
}
static ClassLoader getParentClassLoader(final ClassLoader cl) {
if (System.getSecurityManager() == null) {
return cl.getParent();
} else {
return (ClassLoader) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
return cl.getParent();
}
});
}
}
static void setContextClassLoader(final ClassLoader cl) {
if (System.getSecurityManager() == null) {
Thread.currentThread().setContextClassLoader(cl);
} else {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public java.lang.Object run() {
Thread.currentThread().setContextClassLoader(cl);
return null;
}
});
}
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* istack-commons tool time utilities.
*
* <p>
* This includes code that relies on APT, javac, etc.
*/
package com.sun.istack.internal.tools;