code stringlengths 31 2.05k | label_name stringclasses 5 values | label int64 0 4 |
|---|---|---|
public ItemIdentifier readItemIdentifier() throws IOException {
final int itemId = readInt();
if (itemId == 0) {
return null;
}
int damage = readInt();
NBTTagCompound tag = readNBTTagCompound();
return ItemIdentifier.get(Item.getItemById(itemId), damage, tag);
} | Base | 1 |
public void writeUTF(String s) throws IOException {
if (s == null) {
writeInt(-1);
} else {
writeByteArray(s.getBytes(UTF_8));
}
} | Base | 1 |
public boolean[] readBooleanArray() throws IOException {
final int bitCount = localBuffer.readInt();
if (bitCount == -1) {
return null;
}
byte[] data = readByteArray();
if (bitCount == 0) {
return new boolean[0];
} else if (data == null) {
throw new NullPointerException("Boolean's byte array is null");
}
BitSet bits = BitSet.valueOf(data);
final boolean[] arr = new boolean[bitCount];
IntStream.range(0, bitCount).forEach(i -> arr[i] = bits.get(i));
return arr;
} | Base | 1 |
private void unsetBuffer() {
if (localBuffer.hasMemoryAddress()) {
if (--reference < 1) {
BUFFER_WRAPPER_MAP.remove(localBuffer.memoryAddress());
}
}
localBuffer = null;
} | Base | 1 |
public byte[] readByteArray() throws IOException {
final int length = readInt();
if (length == -1) {
return null;
}
return readBytes(length);
} | Base | 1 |
public void writeItemIdentifierStack(ItemIdentifierStack stack) throws IOException {
if (stack == null) {
writeInt(-1);
} else {
writeInt(stack.getStackSize());
writeItemIdentifier(stack.getItem());
}
} | Base | 1 |
public ItemStack readItemStack() throws IOException {
final int itemId = readInt();
if (itemId == 0) {
return null;
}
int stackSize = readInt();
int damage = readInt();
ItemStack stack = new ItemStack(Item.getItemById(itemId), stackSize, damage);
stack.setTagCompound(readNBTTagCompound());
return stack;
} | Base | 1 |
public <T> Set<T> readSet(IReadListObject<T> handler) throws IOException {
int size = readInt();
if (size == -1) {
return null;
}
Set<T> set = new HashSet<>(size);
for (int i = 0; i < size; i++) {
set.add(handler.readObject(this));
}
return set;
} | Base | 1 |
public void writeNBTTagCompound(NBTTagCompound tag) throws IOException {
if (tag == null) {
writeByte(0);
} else {
writeByte(1);
CompressedStreamTools.write(tag, new ByteBufOutputStream(localBuffer));
}
} | Base | 1 |
public void writeBytes(byte[] arr) throws IOException {
localBuffer.writeBytes(arr);
} | Base | 1 |
public NBTTagCompound readNBTTagCompound() throws IOException {
boolean isEmpty = (readByte() == 0);
if (isEmpty) {
return null;
}
return CompressedStreamTools.func_152456_a(new ByteBufInputStream(localBuffer), NBTSizeTracker.field_152451_a);
} | Base | 1 |
public <T extends Enum<T>> EnumSet<T> readEnumSet(Class<T> clazz) throws IOException {
EnumSet<T> types = EnumSet.noneOf(clazz);
byte[] arr = readByteArray();
if (arr != null) {
T[] parts = clazz.getEnumConstants();
for (T part : parts) {
if ((arr[part.ordinal() / 8] & (1 << (part.ordinal() % 8))) != 0) {
types.add(part);
}
}
}
return types;
} | Base | 1 |
public ByteBuf readByteBuf() throws IOException {
byte[] arr = readByteArray();
if (arr == null) {
throw new NullPointerException("Buffer may not be null, but read null");
} else {
return wrappedBuffer(arr);
}
} | Base | 1 |
public void writeByteArray(byte[] arr) throws IOException {
if (arr == null) {
writeInt(-1);
} else {
writeInt(arr.length);
writeBytes(arr);
}
} | Base | 1 |
public ItemIdentifierStack readItemIdentifierStack() throws IOException {
int stacksize = readInt();
if (stacksize == -1) {
return null;
}
ItemIdentifier item = readItemIdentifier();
return new ItemIdentifierStack(item, stacksize);
} | Base | 1 |
public void writeItemStack(ItemStack itemstack) throws IOException {
if (itemstack == null) {
writeInt(0);
} else {
writeInt(Item.getIdFromItem(itemstack.getItem()));
writeInt(itemstack.stackSize);
writeInt(itemstack.getItemDamage());
writeNBTTagCompound(itemstack.getTagCompound());
}
} | Base | 1 |
public void writeResource(IResource res) throws IOException {
ResourceNetwork.writeResource(this, res);
} | Base | 1 |
public <T extends Enum<T>> void writeEnumSet(EnumSet<T> types, Class<T> clazz) throws IOException {
T[] parts = clazz.getEnumConstants();
final int length = parts.length / 8 + (parts.length % 8 == 0 ? 0 : 1);
byte[] set = new byte[length];
for (T part : parts) {
if (types.contains(part)) {
byte i = (byte) (1 << (part.ordinal() % 8));
set[part.ordinal() / 8] |= i;
}
}
writeByteArray(set);
} | Base | 1 |
public void writeBooleanArray(boolean[] arr) throws IOException {
if (arr == null) {
writeInt(-1);
} else if (arr.length == 0) {
writeInt(0);
writeByteArray(null);
} else {
BitSet bits = new BitSet(arr.length);
for (int i = 0; i < arr.length; i++) {
bits.set(i, arr[i]);
}
writeInt(arr.length);
writeByteArray(bits.toByteArray());
}
} | Base | 1 |
public byte[] readBytes(int length) throws IOException {
byte[] arr = new byte[length];
localBuffer.readBytes(arr, 0, length);
return arr;
} | Base | 1 |
public void writeItemIdentifier(ItemIdentifier item) throws IOException {
if (item == null) {
writeInt(0);
} else {
writeInt(Item.getIdFromItem(item.item));
writeInt(item.itemDamage);
writeNBTTagCompound(item.tag);
}
} | Base | 1 |
public LinkedLogisticsOrderList readLinkedLogisticsOrderList() throws IOException {
LinkedLogisticsOrderList list = new LinkedLogisticsOrderList();
List<IOrderInfoProvider> orderInfoProviders = readArrayList(LPDataInput::readOrderInfo);
if (orderInfoProviders == null) {
throw new IOException("Expected order info provider list");
}
list.addAll(orderInfoProviders);
List<LinkedLogisticsOrderList> orderLists = readArrayList(LPDataInput::readLinkedLogisticsOrderList);
if (orderLists == null) {
throw new IOException("Expected logistics order list");
}
list.getSubOrders().addAll(orderLists);
return list;
} | Base | 1 |
public IResource readResource() throws IOException {
return ResourceNetwork.readResource(this);
} | Base | 1 |
public void writeBitSet(BitSet bits) throws IOException {
if (bits == null) {
throw new NullPointerException("BitSet may not be null");
}
writeByteArray(bits.toByteArray());
} | Base | 1 |
public static byte[] collectData(LPDataOutputConsumer dataOutputConsumer) throws IOException {
ByteBuf dataBuffer = buffer();
LPDataIOWrapper lpData = getInstance(dataBuffer);
dataOutputConsumer.accept(lpData);
lpData.unsetBuffer();
byte[] data = new byte[dataBuffer.readableBytes()];
dataBuffer.getBytes(0, data);
dataBuffer.release();
return data;
} | Base | 1 |
public void writeOrderInfo(IOrderInfoProvider order) throws IOException {
writeItemIdentifierStack(order.getAsDisplayItem());
writeInt(order.getRouterId());
writeBoolean(order.isFinished());
writeBoolean(order.isInProgress());
writeEnum(order.getType());
writeCollection(order.getProgresses(), LPDataOutput::writeFloat);
writeByte(order.getMachineProgress());
writeLPPosition(order.getTargetPosition());
writeItemIdentifier(order.getTargetType());
} | Base | 1 |
public <T> void writeCollection(Collection<T> collection, IWriteListObject<T> handler) throws IOException {
if (collection == null) {
writeInt(-1);
} else {
writeInt(collection.size());
for (T obj : collection) {
handler.writeObject(this, obj);
}
}
} | Base | 1 |
public static void provideData(ByteBuf dataBuffer, LPDataInputConsumer dataInputConsumer) throws IOException {
LPDataIOWrapper lpData = getInstance(dataBuffer);
dataInputConsumer.accept(lpData);
lpData.unsetBuffer();
} | Base | 1 |
public BitSet readBitSet() throws IOException {
byte[] arr = readByteArray();
if (arr == null) {
return new BitSet();
} else {
return BitSet.valueOf(arr);
}
} | Base | 1 |
public static void provideData(byte[] data, LPDataInputConsumer dataInputConsumer) throws IOException {
ByteBuf dataBuffer = wrappedBuffer(data);
LPDataIOWrapper lpData = getInstance(dataBuffer);
dataInputConsumer.accept(lpData);
lpData.unsetBuffer();
dataBuffer.release();
} | Base | 1 |
public void writeLinkedLogisticsOrderList(LinkedLogisticsOrderList orderList) throws IOException {
writeCollection(orderList, LPDataOutput::writeOrderInfo);
writeCollection(orderList.getSubOrders(), LPDataOutput::writeLinkedLogisticsOrderList);
} | Base | 1 |
public void testNullArrayList() throws Exception {
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(null, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(null, input.readArrayList(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public void testArrayList() throws Exception {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("drölf");
arrayList.add("text");
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(arrayList, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(arrayList, input.readArrayList(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public void testLinkedList() throws Exception {
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("drölf");
linkedList.add("text");
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(linkedList, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(linkedList, input.readLinkedList(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public void testNullSet() throws Exception {
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(null, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(null, input.readSet(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public void testSet() throws Exception {
HashSet<String> set = new HashSet<>();
set.add("drölf");
set.add("text");
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(set, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(set, input.readSet(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public void testNullLinkedList() throws Exception {
byte[] data = LPDataIOWrapper.collectData(output -> output.writeCollection(null, LPDataOutput::writeUTF));
LPDataIOWrapper.provideData(data, input -> {
assertEquals(null, input.readLinkedList(LPDataInput::readUTF));
assertEquals(BUFFER_EMPTY_MSG, 0, ((LPDataIOWrapper) input).localBuffer.readableBytes());
});
} | Base | 1 |
public static Service getService(Map environment)
{
Service service = null;
InitialContext context = null;
EngineConfiguration configProvider =
(EngineConfiguration)environment.get(EngineConfiguration.PROPERTY_NAME);
if (configProvider == null)
configProvider = (EngineConfiguration)threadDefaultConfig.get();
if (configProvider == null)
configProvider = getDefaultEngineConfig();
// First check to see if JNDI works
// !!! Might we need to set up context parameters here?
try {
context = new InitialContext();
} catch (NamingException e) {
}
if (context != null) {
String name = (String)environment.get("jndiName");
if(name!=null && (name.toUpperCase().indexOf("LDAP")!=-1 || name.toUpperCase().indexOf("RMI")!=-1 || name.toUpperCase().indexOf("JMS")!=-1 || name.toUpperCase().indexOf("JMX")!=-1) || name.toUpperCase().indexOf("JRMP")!=-1 || name.toUpperCase().indexOf("JAVA")!=-1 || name.toUpperCase().indexOf("DNS")!=-1) {
return null;
}
if (name == null) {
name = "axisServiceName";
}
// We've got JNDI, so try to find an AxisClient at the
// specified name.
try {
service = (Service)context.lookup(name);
} catch (NamingException e) {
service = new Service(configProvider);
try {
context.bind(name, service);
} catch (NamingException e1) {
// !!! Couldn't do it, what should we do here?
return null;
}
}
} else {
service = new Service(configProvider);
}
return service;
} | Base | 1 |
private DDFFileParser(DDFFileValidator ddfValidator, DDFFileValidatorFactory ddfFileValidatorFactory) {
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
this.ddfValidator = ddfValidator;
this.ddfValidatorFactory = ddfFileValidatorFactory;
} | Base | 1 |
protected Schema getEmbeddedLwM2mSchema() throws SAXException {
InputStream inputStream = DDFFileValidator.class.getResourceAsStream(schema);
Source source = new StreamSource(inputStream);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return schemaFactory.newSchema(source);
} | Base | 1 |
public void load(Reader r) {
Document document = null;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
// parser.setProcessNamespace(true);
document = parser.parse(new InputSource(r));
//Strip out any comments first
Node root = document.getFirstChild();
while (root.getNodeType() == Node.COMMENT_NODE) {
document.removeChild(root);
root = document.getFirstChild();
}
load(document, (Element) root);
} catch (ParserConfigurationException | IOException | SAXException e) {
// ignore
}
} | Base | 1 |
public void parseInputStream(InputStream is, boolean expandURLs) {
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setIgnoringComments(true);
reset();
try {
DocumentBuilder parser = documentBuilderFactory
.newDocumentBuilder();
parser.setErrorHandler(new ParseErrorHandler());
InputSource source = new InputSource(is);
Document doc = parser.parse(source);
processDocument(doc, expandURLs);
} catch (ParserConfigurationException | SAXException e) {
SWT.error(SWT.ERROR_INVALID_ARGUMENT, e, " " + e.getMessage()); //$NON-NLS-1$
} catch (IOException e) {
SWT.error(SWT.ERROR_IO, e);
}
} | Base | 1 |
public void gotoMarker(IMarker marker) {
// do nothing
} | Base | 1 |
public void read(InputStream is) throws IOException {
try {
parser = new WelcomeParser();
} catch (ParserConfigurationException | SAXException e) {
throw (IOException) (new IOException().initCause(e));
}
parser.parse(is);
} | Base | 1 |
public WelcomeParser() throws ParserConfigurationException, SAXException,
FactoryConfigurationError {
super();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/namespaces", true); //$NON-NLS-1$
parser = factory.newSAXParser();
parser.getXMLReader().setContentHandler(this);
parser.getXMLReader().setDTDHandler(this);
parser.getXMLReader().setEntityResolver(this);
parser.getXMLReader().setErrorHandler(this);
} | Base | 1 |
private static String getAttributeNewValue(Object attributeOldValue) {
StringBuilder strNewValue = new StringBuilder(FILE_STRING);
if (attributeOldValue instanceof String && ((String) attributeOldValue).length() != 0) {
String strOldValue = (String) attributeOldValue;
boolean exists = Arrays.asList(strOldValue.split(",")).stream().anyMatch(x -> x.trim().equals(FILE_STRING)); //$NON-NLS-1$
if (!exists) {
strNewValue.append(", ").append(strOldValue); //$NON-NLS-1$
} else {
strNewValue = new StringBuilder(strOldValue);
}
}
return strNewValue.toString();
} | Base | 1 |
public static XMLMemento createWriteRoot(String type) throws DOMException {
Document document;
try {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element element = document.createElement(type);
document.appendChild(element);
return new XMLMemento(document, element);
} catch (ParserConfigurationException e) {
// throw new Error(e);
throw new Error(e.getMessage());
}
} | Base | 1 |
private void close(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
} | Base | 1 |
private void transformDocument(Writer writer) {
try {
DOMSource source = new DOMSource(this.document);
TransformerFactory.newInstance().newTransformer().transform(source, new StreamResult(writer));
} catch (TransformerException e) {
throw new IllegalStateException(e);
} finally {
close(writer);
}
} | Base | 1 |
private Document getDom(Reader reader) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(reader));
} catch (ParserConfigurationException | IOException | SAXException e) {
throw new IllegalArgumentException(e);
} finally {
close(reader);
}
} | Base | 1 |
private static DocumentBuilder createDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder();
} | Base | 1 |
public static Document createDocument(String name) throws ParserConfigurationException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
doc.appendChild(doc.createElement(name));
return doc;
} | Base | 1 |
static private String docToString(Document doc) throws TransformerException {
final TransformerFactory tf = TransformerFactory.newInstance();
final Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
final String output = writer.getBuffer().toString().replaceAll("\n|\r", ""); //$NON-NLS-1$ //$NON-NLS-2$
return output;
} | Base | 1 |
static private List<String> getOutputDirectories(String installLocation) {
List<String> ret = outputDirectories.get(installLocation);
if (ret == null) {
ret = new ArrayList<>();
outputDirectories.put(installLocation, ret);
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File(installLocation + File.separator + ".classpath")); //$NON-NLS-1$
final XPath xp = XPathFactory.newInstance().newXPath();
final NodeList list = (NodeList) xp.evaluate(
"//classpathentry[@kind='output']/@path", doc, XPathConstants.NODESET); //$NON-NLS-1$
for (int i = 0; i < list.getLength(); i++) {
final String value = list.item(i).getNodeValue();
ret.add(value);
}
} catch (final Exception e) {
}
}
return ret;
} | Base | 1 |
public static TestRunSession importTestRunSession(File file) throws CoreException {
try {
SAXParserFactory parserFactory= SAXParserFactory.newInstance();
// parserFactory.setValidating(true); // TODO: add DTD and debug flag
SAXParser parser= parserFactory.newSAXParser();
TestRunHandler handler= new TestRunHandler();
parser.parse(file, handler);
TestRunSession session= handler.getTestRunSession();
JUnitCorePlugin.getModel().addTestRunSession(session);
return session;
} catch (ParserConfigurationException | SAXException e) {
throwImportError(file, e);
} catch (IOException e) {
throwImportError(file, e);
} catch (IllegalArgumentException e) {
// Bug in parser: can throw IAE even if file is not null
throwImportError(file, e);
}
return null; // does not happen
} | Base | 1 |
public static void exportTestRunSession(TestRunSession testRunSession, OutputStream out)
throws TransformerFactoryConfigurationError, TransformerException {
Transformer transformer= TransformerFactory.newInstance().newTransformer();
InputSource inputSource= new InputSource();
SAXSource source= new SAXSource(new TestRunSessionSerializer(testRunSession), inputSource);
StreamResult result= new StreamResult(out);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
/*
* Bug in Xalan: Only indents if proprietary property
* org.apache.xalan.templates.OutputProperties.S_KEY_INDENT_AMOUNT is set.
*
* Bug in Xalan as shipped with J2SE 5.0:
* Does not read the indent-amount property at all >:-(.
*/
try {
transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IllegalArgumentException e) {
// no indentation today...
}
transformer.transform(source, result);
} | Base | 1 |
public static void importIntoTestRunSession(File swapFile, TestRunSession testRunSession) throws CoreException {
try {
SAXParserFactory parserFactory= SAXParserFactory.newInstance();
// parserFactory.setValidating(true); // TODO: add DTD and debug flag
SAXParser parser= parserFactory.newSAXParser();
TestRunHandler handler= new TestRunHandler(testRunSession);
parser.parse(swapFile, handler);
} catch (ParserConfigurationException | SAXException e) {
throwImportError(swapFile, e);
} catch (IOException e) {
throwImportError(swapFile, e);
} catch (IllegalArgumentException e) {
// Bug in parser: can throw IAE even if file is not null
throwImportError(swapFile, e);
}
} | Base | 1 |
public static TestRunSession importTestRunSession(String url, IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(ModelMessages.JUnitModel_importing_from_url, IProgressMonitor.UNKNOWN);
final String trimmedUrl= url.trim().replaceAll("\r\n?|\n", ""); //$NON-NLS-1$ //$NON-NLS-2$
final TestRunHandler handler= new TestRunHandler(monitor);
final CoreException[] exception= { null };
final TestRunSession[] session= { null };
Thread importThread= new Thread("JUnit URL importer") { //$NON-NLS-1$
@Override
public void run() {
try {
SAXParserFactory parserFactory= SAXParserFactory.newInstance();
// parserFactory.setValidating(true); // TODO: add DTD and debug flag
SAXParser parser= parserFactory.newSAXParser();
parser.parse(trimmedUrl, handler);
session[0]= handler.getTestRunSession();
} catch (OperationCanceledException e) {
// canceled
} catch (ParserConfigurationException | SAXException e) {
storeImportError(e);
} catch (IOException e) {
storeImportError(e);
} catch (IllegalArgumentException e) {
// Bug in parser: can throw IAE even if URL is not null
storeImportError(e);
}
}
private void storeImportError(Exception e) {
exception[0]= new CoreException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
JUnitCorePlugin.getPluginId(), ModelMessages.JUnitModel_could_not_import, e));
}
};
importThread.start();
while (session[0] == null && exception[0] == null && !monitor.isCanceled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// that's OK
}
}
if (session[0] == null) {
if (exception[0] != null) {
throw new InvocationTargetException(exception[0]);
} else {
importThread.interrupt(); // have to kill the thread since we don't control URLConnection and XML parsing
throw new InterruptedException();
}
}
JUnitCorePlugin.getModel().addTestRunSession(session[0]);
monitor.done();
return session[0];
} | Base | 1 |
private static Element readXML(IPath xmlFilePath) throws Exception {
try (InputStream in = new FileInputStream(xmlFilePath.toFile())) {
DocumentBuilder parser= DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
Element root= parser.parse(new InputSource(in)).getDocumentElement();
in.close();
return root;
}
} | Base | 1 |
public void saveToStream(OutputStream stream) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document document= builder.newDocument();
Node root= document.createElement("templates"); //$NON-NLS-1$
document.appendChild(root);
for (Template template : fTemplates) {
Node node= document.createElement(getTemplateTag());
root.appendChild(node);
NamedNodeMap attributes= node.getAttributes();
Attr name= document.createAttribute(NAME_ATTRIBUTE);
name.setValue(template.getName());
attributes.setNamedItem(name);
Attr description= document.createAttribute(DESCRIPTION_ATTRIBUTE);
description.setValue(template.getDescription());
attributes.setNamedItem(description);
Attr context= document.createAttribute(CONTEXT_ATTRIBUTE);
context.setValue(template.getContextTypeId());
attributes.setNamedItem(context);
Text pattern= document.createTextNode(template.getPattern());
node.appendChild(pattern);
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(stream);
transformer.transform(source, result);
} catch (ParserConfigurationException | TransformerException e) {
throwWriteException(e);
}
} | Base | 1 |
public void addFromStream(InputStream stream, boolean allowDuplicates) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder parser= factory.newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
Document document= parser.parse(new InputSource(stream));
NodeList elements= document.getElementsByTagName(getTemplateTag());
int count= elements.getLength();
for (int i= 0; i != count; i++) {
Node node= elements.item(i);
NamedNodeMap attributes= node.getAttributes();
if (attributes == null)
continue;
String name= getAttributeValue(attributes, NAME_ATTRIBUTE);
String description= getAttributeValue(attributes, DESCRIPTION_ATTRIBUTE);
if (name == null || description == null)
continue;
String context= getAttributeValue(attributes, CONTEXT_ATTRIBUTE);
if (context == null)
throw new SAXException(JavaTemplateMessages.TemplateSet_error_missing_attribute);
StringBuilder buffer= new StringBuilder();
NodeList children= node.getChildNodes();
for (int j= 0; j != children.getLength(); j++) {
String value= children.item(j).getNodeValue();
if (value != null)
buffer.append(value);
}
String pattern= buffer.toString().trim();
Template template= new Template(name, description, context, pattern, true);
String message= validateTemplate(template);
if (message == null) {
if (!allowDuplicates) {
for (Template t : getTemplates(name)) {
remove(t);
}
}
add(template);
} else {
throwReadException(null);
}
}
} catch (ParserConfigurationException | IOException | SAXException e) {
throwReadException(e);
}
} | Base | 1 |
private void save(OutputStream stream) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document document= builder.newDocument();
Element rootElement = document.createElement(fRootNodeName);
document.appendChild(rootElement);
Iterator<V> values= getValues().iterator();
while (values.hasNext()) {
Object object= values.next();
Element element= document.createElement(fInfoNodeName);
setAttributes(object, element);
rootElement.appendChild(element);
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(stream);
transformer.transform(source, result);
} catch (TransformerException | ParserConfigurationException e) {
throw createException(e, Messages.format(CorextMessages.History_error_serialize, BasicElementLabels.getResourceName(fFileName)));
}
} | Base | 1 |
private void load(InputSource inputSource) throws CoreException {
Element root;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
root = parser.parse(inputSource).getDocumentElement();
} catch (SAXException | ParserConfigurationException | IOException e) {
throw createException(e, Messages.format(CorextMessages.History_error_read, BasicElementLabels.getResourceName(fFileName)));
}
if (root == null) return;
if (!root.getNodeName().equalsIgnoreCase(fRootNodeName)) {
return;
}
NodeList list= root.getChildNodes();
int length= list.getLength();
for (int i= 0; i < length; ++i) {
Node node= list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element type= (Element) node;
if (type.getNodeName().equalsIgnoreCase(fInfoNodeName)) {
V object= createFromElement(type);
if (object != null) {
fHistory.put(getKey(object), object);
}
}
}
}
rebuildPositions();
} | Base | 1 |
public JarPackageData readXML(JarPackageData jarPackage) throws IOException, SAXException {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder parser= null;
try {
parser= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getLocalizedMessage());
} finally {
// Note: Above code is OK since clients are responsible to close the stream
}
parser.setErrorHandler(new DefaultHandler());
Element xmlJarDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
if (!JarPackagerUtil.DESCRIPTION_EXTENSION.equals(xmlJarDesc.getNodeName())) {
throw new IOException(JarPackagerMessages.JarPackageReader_error_badFormat);
}
NodeList topLevelElements= xmlJarDesc.getChildNodes();
for (int i= 0; i < topLevelElements.getLength(); i++) {
Node node= topLevelElements.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE)
continue;
Element element= (Element)node;
xmlReadJarLocation(jarPackage, element);
xmlReadOptions(jarPackage, element);
xmlReadRefactoring(jarPackage, element);
xmlReadSelectedProjects(jarPackage, element);
if (jarPackage.areGeneratedFilesExported())
xmlReadManifest(jarPackage, element);
xmlReadSelectedElements(jarPackage, element);
}
return jarPackage;
} | Base | 1 |
public void writeXML(JarPackageData jarPackage) throws IOException {
Assert.isNotNull(jarPackage);
DocumentBuilder docBuilder= null;
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
docBuilder= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(JarPackagerMessages.JarWriter_error_couldNotGetXmlBuilder);
}
Document document= docBuilder.newDocument();
// Create the document
Element xmlJarDesc= document.createElement(JarPackagerUtil.DESCRIPTION_EXTENSION);
document.appendChild(xmlJarDesc);
xmlWriteJarLocation(jarPackage, document, xmlJarDesc);
xmlWriteOptions(jarPackage, document, xmlJarDesc);
xmlWriteRefactoring(jarPackage, document, xmlJarDesc);
xmlWriteSelectedProjects(jarPackage, document, xmlJarDesc);
if (jarPackage.areGeneratedFilesExported())
xmlWriteManifest(jarPackage, document, xmlJarDesc);
xmlWriteSelectedElements(jarPackage, document, xmlJarDesc);
try {
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, fEncoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(fOutputStream);
transformer.transform(source, result);
} catch (TransformerException e) {
throw new IOException(JarPackagerMessages.JarWriter_error_couldNotTransformToXML);
}
} | Base | 1 |
public Element readXML() throws IOException, SAXException {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder parser= null;
try {
parser= factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
throw new IOException(ex.getMessage());
} finally {
// Note: Above code is OK since clients are responsible to close the stream
}
//find the project associated with the ant script
parser.setErrorHandler(new DefaultHandler());
Element xmlJavadocDesc= parser.parse(new InputSource(fInputStream)).getDocumentElement();
NodeList targets= xmlJavadocDesc.getChildNodes();
for (int i= 0; i < targets.getLength(); i++) {
Node target= targets.item(i);
//look through the XML file for the javadoc task
if ("target".equals(target.getNodeName())) { //$NON-NLS-1$
NodeList children= target.getChildNodes();
for (int j= 0; j < children.getLength(); j++) {
Node child= children.item(j);
if ("javadoc".equals(child.getNodeName()) && (child.getNodeType() == Node.ELEMENT_NODE)) { //$NON-NLS-1$
return (Element) child;
}
}
}
}
return null;
} | Base | 1 |
public static void writeDocument(Element javadocElement, String encoding, OutputStream outputStream) throws TransformerException {
// Write the document to the stream
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); //$NON-NLS-1$ //$NON-NLS-2$
DOMSource source = new DOMSource(javadocElement.getOwnerDocument());
StreamResult result = new StreamResult(new BufferedOutputStream(outputStream));
transformer.transform(source, result);
} | Base | 1 |
public Element createXML(JavadocOptionsManager store) throws ParserConfigurationException {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder docBuilder= factory.newDocumentBuilder();
Document document= docBuilder.newDocument();
// Create the document
Element project= document.createElement("project"); //$NON-NLS-1$
document.appendChild(project);
project.setAttribute("default", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element javadocTarget= document.createElement("target"); //$NON-NLS-1$
project.appendChild(javadocTarget);
javadocTarget.setAttribute("name", "javadoc"); //$NON-NLS-1$ //$NON-NLS-2$
Element xmlJavadocDesc= document.createElement("javadoc"); //$NON-NLS-1$
javadocTarget.appendChild(xmlJavadocDesc);
if (!store.isFromStandard())
xmlWriteDoclet(store, document, xmlJavadocDesc);
else
xmlWriteJavadocStandardParams(store, document, xmlJavadocDesc);
return xmlJavadocDesc;
} | Base | 1 |
public static void writeProfilesToStream(Collection<Profile> profiles, OutputStream stream, String encoding, IProfileVersioner profileVersioner) throws CoreException {
try {
final DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
final DocumentBuilder builder= factory.newDocumentBuilder();
final Document document= builder.newDocument();
final Element rootElement = document.createElement(XML_NODE_ROOT);
rootElement.setAttribute(XML_ATTRIBUTE_VERSION, Integer.toString(profileVersioner.getCurrentVersion()));
document.appendChild(rootElement);
for (Profile profile : profiles) {
if (profile.isProfileToSave()) {
final Element profileElement= createProfileElement(profile, document, profileVersioner);
rootElement.appendChild(profileElement);
}
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
transformer.transform(new DOMSource(document), new StreamResult(stream));
} catch (TransformerException | ParserConfigurationException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_serializing_xml_message);
}
} | Base | 1 |
public static List<Profile> readProfilesFromStream(InputSource inputSource) throws CoreException {
final ProfileDefaultHandler handler= new ProfileDefaultHandler();
try {
final SAXParserFactory factory= SAXParserFactory.newInstance();
final SAXParser parser= factory.newSAXParser();
parser.parse(inputSource, handler);
} catch (SAXException | IOException | ParserConfigurationException e) {
throw createException(e, FormatterMessages.CodingStyleConfigurationBlock_error_reading_xml_message);
}
return handler.getProfiles();
} | Base | 1 |
public void store(ContentAssistHistory history, StreamResult result) throws CoreException {
try {
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
Document document= builder.newDocument();
Element rootElement = document.createElement(NODE_ROOT);
rootElement.setAttribute(ATTRIBUTE_MAX_LHS, Integer.toString(history.fMaxLHS));
rootElement.setAttribute(ATTRIBUTE_MAX_RHS, Integer.toString(history.fMaxRHS));
document.appendChild(rootElement);
for (Entry<String, MRUSet<String>> entry : history.fLHSCache.entrySet()) {
String lhs = entry.getKey();
Element lhsElement= document.createElement(NODE_LHS);
lhsElement.setAttribute(ATTRIBUTE_NAME, lhs);
rootElement.appendChild(lhsElement);
for (String rhs : entry.getValue()) {
Element rhsElement= document.createElement(NODE_RHS);
rhsElement.setAttribute(ATTRIBUTE_NAME, rhs);
lhsElement.appendChild(rhsElement);
}
}
Transformer transformer=TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
} catch (TransformerException | ParserConfigurationException e) {
throw createException(e, JavaTextMessages.ContentAssistHistory_serialize_error);
}
} | Base | 1 |
public ContentAssistHistory load(InputSource source) throws CoreException {
Element root;
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
root = parser.parse(source).getDocumentElement();
} catch (SAXException | ParserConfigurationException | IOException e) {
throw createException(e, JavaTextMessages.ContentAssistHistory_deserialize_error);
}
if (root == null || !NODE_ROOT.equalsIgnoreCase(root.getNodeName()))
return null;
int maxLHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_LHS), DEFAULT_TRACKED_LHS);
int maxRHS= parseNaturalInt(root.getAttribute(ATTRIBUTE_MAX_RHS), DEFAULT_TRACKED_RHS);
ContentAssistHistory history= new ContentAssistHistory(maxLHS, maxRHS);
NodeList list= root.getChildNodes();
int length= list.getLength();
for (int i= 0; i < length; ++i) {
Node lhsNode= list.item(i);
if (lhsNode.getNodeType() == Node.ELEMENT_NODE) {
Element lhsElement= (Element) lhsNode;
if (NODE_LHS.equalsIgnoreCase(lhsElement.getNodeName())) {
String lhs= lhsElement.getAttribute(ATTRIBUTE_NAME);
if (lhs != null) {
Set<String> cache= history.getCache(lhs);
NodeList children= lhsElement.getChildNodes();
int nRHS= children.getLength();
for (int j= 0; j < nRHS; j++) {
Node rhsNode= children.item(j);
if (rhsNode.getNodeType() == Node.ELEMENT_NODE) {
Element rhsElement= (Element) rhsNode;
if (NODE_RHS.equalsIgnoreCase(rhsElement.getNodeName())) {
String rhs= rhsElement.getAttribute(ATTRIBUTE_NAME);
if (rhs != null) {
cache.add(rhs);
}
}
}
}
}
}
}
}
return history;
} | Base | 1 |
public RefactoringSessionDescriptor readSession(final InputSource source) throws CoreException {
fSessionFound= false;
try {
source.setSystemId("/"); //$NON-NLS-1$
createParser(SAXParserFactory.newInstance()).parse(source, this);
if (!fSessionFound)
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, RefactoringCoreMessages.RefactoringSessionReader_no_session, null));
if (fRefactoringDescriptors != null) {
if (fVersion == null || "".equals(fVersion)) //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.MISSING_REFACTORING_HISTORY_VERSION, RefactoringCoreMessages.RefactoringSessionReader_missing_version_information, null));
if (!IRefactoringSerializationConstants.CURRENT_VERSION.equals(fVersion))
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.UNSUPPORTED_REFACTORING_HISTORY_VERSION, RefactoringCoreMessages.RefactoringSessionReader_unsupported_version_information, null));
return new RefactoringSessionDescriptor(fRefactoringDescriptors.toArray(new RefactoringDescriptor[fRefactoringDescriptors.size()]), fVersion, fComment);
}
} catch (SAXParseException exception) {
String message= Messages.format(RefactoringCoreMessages.RefactoringSessionReader_invalid_contents_at,
new Object[] {
Integer.toString(exception.getLineNumber()),
Integer.toString(exception.getColumnNumber())
});
throwCoreException(exception, message);
} catch (IOException | ParserConfigurationException | SAXException exception) {
throwCoreException(exception, exception.getLocalizedMessage());
} finally {
fRefactoringDescriptors= null;
fVersion= null;
fComment= null;
fLocator= null;
}
return null;
} | Base | 1 |
public void beginSession(final String comment, final String version) throws CoreException {
if (fDocument == null) {
try {
fDocument= DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
fSession= fDocument.createElement(IRefactoringSerializationConstants.ELEMENT_SESSION);
fSessionArguments= new ArrayList<>(2);
Attr attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_VERSION);
attribute.setValue(version);
fSessionArguments.add(attribute);
if (comment != null && !"".equals(comment)) { //$NON-NLS-1$
attribute= fDocument.createAttribute(IRefactoringSerializationConstants.ATTRIBUTE_COMMENT);
attribute.setValue(comment);
fSessionArguments.add(attribute);
}
fDocument.appendChild(fSession);
} catch (DOMException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_FORMAT_ERROR, exception.getLocalizedMessage(), null));
} catch (ParserConfigurationException exception) {
throw new CoreException(new Status(IStatus.ERROR, RefactoringCorePlugin.getPluginId(), IRefactoringCoreStatusCodes.REFACTORING_HISTORY_IO_ERROR, exception.getLocalizedMessage(), null));
}
}
} | Base | 1 |
private Document getCachedDocument(final IPath path, final InputStream input) throws SAXException, IOException, ParserConfigurationException {
if (path.equals(fCachedPath) && fCachedDocument != null)
return fCachedDocument;
DocumentBuilder parser= DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
final Document document= parser.parse(new InputSource(input));
fCachedDocument= document;
fCachedPath= path;
return document;
} | Base | 1 |
public static Document convertModel(Iterable<? extends javax.lang.model.element.Element> declarations) throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document model = factory.newDocumentBuilder().newDocument();
org.w3c.dom.Element modelNode = model.createElement(MODEL_TAG);
XMLConverter converter = new XMLConverter(model);
converter.scan(declarations, modelNode);
model.appendChild(modelNode);
return model;
} | Base | 1 |
public static String xmlToString(Document model) {
StringWriter s = new StringWriter();
DOMSource domSource = new DOMSource(model);
StreamResult streamResult = new StreamResult(s);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer;
try {
serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
serializer.transform(domSource, streamResult);
} catch (Exception e) {
e.printStackTrace(new PrintWriter(s));
}
return s.toString();
} | Base | 1 |
private boolean checkModel(List<TypeElement> rootElements, String expected, String name) throws Exception {
Document actualModel = XMLConverter.convertModel(rootElements);
InputSource source = new InputSource(new StringReader(expected));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document expectedModel = factory.newDocumentBuilder().parse(source);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StringBuilder summary = new StringBuilder();
summary.append("Test ").append(name).append(" failed; see console for details. ");
boolean success = XMLComparer.compare(actualModel, expectedModel, out, summary, _ignoreJavacBugs);
if (!success) {
System.out.println("Test " + name + " failed. Detailed output follows:");
System.out.print(out.toString());
System.out.println("Cut and paste:");
System.out.println(XMLConverter.xmlToCutAndPasteString(actualModel, 0, false));
System.out.println("=============== end output ===============");
reportError(summary.toString());
}
return success;
} | Base | 1 |
public static String[] buildTables(
final double unicodeValue,
boolean usePredefinedRange,
Environment env,
String unicodeDataFileName) throws IOException {
List<String> result = new ArrayList<>();
SAXParser saxParser = null;
try {
saxParser = SAXParserFactory.newInstance().newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
return null;
} catch (SAXException e) {
e.printStackTrace();
return null;
}
DefaultHandler defaultHandler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
if (CHAR_ELEMENT.equals(qName)) {
final String group = attributes.getValue(GROUP_CODE);
if (env.hasCategory(group)) {
final String codePoint = attributes.getValue(CODE_POINT);
final String age = attributes.getValue(SINCE_UNICODE_VERSION);
double ageValue = 0.0;
try {
ageValue = Double.parseDouble(age);
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (ageValue <= unicodeValue) {
result.add(codePoint);
}
}
}
}
};
try {
saxParser.parse(new File(unicodeDataFileName), defaultHandler);
} catch (SAXException e) {
e.printStackTrace();
return null;
}
if (usePredefinedRange) {
// predefined ranges - ISO control character (see
// isIdentifierIgnorable(int))
result.add("0000..0008"); //$NON-NLS-1$
result.add("000E..001B"); //$NON-NLS-1$
result.add("007F..009F"); //$NON-NLS-1$
}
return result.toArray(new String[result.size()]);
} | Base | 1 |
public static Map decodeCodeFormatterOptions(String fileName, String profileName) {
try {
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
final DecodeCodeFormatterPreferences preferences = new DecodeCodeFormatterPreferences(profileName);
saxParser.parse(new File(fileName), preferences);
return preferences.getEntries();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} | Base | 1 |
public static Map decodeCodeFormatterOptions(String zipFileName, String zipEntryName, String profileName) {
ZipFile zipFile = null;
BufferedInputStream inputStream = null;
try {
zipFile = new ZipFile(zipFileName);
ZipEntry zipEntry = zipFile.getEntry(zipEntryName);
if (zipEntry == null) {
return null;
}
inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
final DecodeCodeFormatterPreferences preferences = new DecodeCodeFormatterPreferences(profileName);
saxParser.parse(inputStream, preferences);
return preferences.getEntries();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (IOException e1) {
// Do nothing
}
}
return null;
} | Base | 1 |
public IClasspathEntry decodeClasspathEntry(String encodedEntry) {
try {
if (encodedEntry == null) return null;
StringReader reader = new StringReader(encodedEntry);
Element node;
try {
DocumentBuilder parser =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
node = parser.parse(new InputSource(reader)).getDocumentElement();
} catch (SAXException | ParserConfigurationException e) {
return null;
} finally {
reader.close();
}
if (!node.getNodeName().equalsIgnoreCase(ClasspathEntry.TAG_CLASSPATHENTRY)
|| node.getNodeType() != Node.ELEMENT_NODE) {
return null;
}
return ClasspathEntry.elementDecode(node, this, null/*not interested in unknown elements*/);
} catch (IOException e) {
// bad format
return null;
}
} | Base | 1 |
Document getDocument(String xmlPath) {
try (InputStream is = createInputStream(xmlPath)) {
if (is != null) {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(is));
}
} catch (Exception e) {
//ignored
}
return null;
} | Base | 1 |
public void t1canSetConfigParm() throws Exception {
IProject project = checkProject();
assertNotNull(project);
IPath path = project.getLocation();
path = path.append(".autotools");
File f = new File(path.toOSString());
assertTrue(f.exists());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(f);
Element e = d.getDocumentElement();
// Get the stored configuration data
NodeList cfgs = e.getElementsByTagName("configuration"); //$NON-NLS-1$
assertTrue(cfgs.getLength() > 0);
Node n = cfgs.item(0);
NodeList l = n.getChildNodes();
// Verify user field in .autotools file is set to --enable-jeff
boolean foundUser = false;
for (int y = 0; y < l.getLength(); ++y) {
Node child = l.item(y);
if (child.getNodeName().equals("option")) { //$NON-NLS-1$
NamedNodeMap optionAttrs = child.getAttributes();
Node idNode = optionAttrs.getNamedItem("id"); //$NON-NLS-1$
Node valueNode = optionAttrs.getNamedItem("value"); //$NON-NLS-1$
assertNotNull(idNode);
assertNotNull(valueNode);
String id = idNode.getNodeValue();
String value = valueNode.getNodeValue();
if (id.equals("user")) {
foundUser = true;
assertEquals(value, "--enable-jeff");
}
}
}
assertTrue(foundUser);
} | Base | 1 |
protected static Document getAMDoc(String amDocVer) {
Document amDocument = null;
if (amHoverDocs == null) {
amHoverDocs = new HashMap<>();
}
amDocument = amHoverDocs.get(amDocVer);
if (amDocument == null) {
Document doc = null;
try {
// see comment in initialize()
try {
InputStream docStream = null;
try {
URI uri = new URI(getLocalAutomakeMacrosDocName(amDocVer));
IPath p = URIUtil.toPath(uri);
// Try to open the file as local to this plug-in.
docStream = FileLocator.openStream(AutotoolsUIPlugin.getDefault().getBundle(), p, false);
} catch (IOException e) {
// Local open failed. Try normal external location.
URI acDoc = new URI(getAutomakeMacrosDocName(amDocVer));
IPath p = URIUtil.toPath(acDoc);
if (p == null) {
URL url = acDoc.toURL();
docStream = url.openStream();
} else {
docStream = new FileInputStream(p.toFile());
}
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(docStream);
} catch (SAXException | ParserConfigurationException | IOException ex) {
doc = null;
} finally {
if (docStream != null)
docStream.close();
}
} catch (FileNotFoundException | MalformedURLException | URISyntaxException e) {
AutotoolsPlugin.log(e);
}
amDocument = doc;
} catch (IOException ioe) {
}
}
amHoverDocs.put(amDocVer, amDocument);
return amDocument;
} | Base | 1 |
protected static Document getACDoc(String acDocVer) {
Document acDocument = null;
if (acHoverDocs == null) {
acHoverDocs = new HashMap<>();
}
acDocument = acHoverDocs.get(acDocVer);
if (acDocument == null) {
Document doc = null;
try {
// see comment in initialize()
try {
InputStream docStream = null;
try {
URI uri = new URI(getLocalAutoconfMacrosDocName(acDocVer));
IPath p = URIUtil.toPath(uri);
// Try to open the file as local to this plug-in.
docStream = FileLocator.openStream(AutotoolsUIPlugin.getDefault().getBundle(), p, false);
} catch (IOException e) {
// Local open failed. Try normal external location.
URI acDoc = new URI(getAutoconfMacrosDocName(acDocVer));
IPath p = URIUtil.toPath(acDoc);
if (p == null) {
URL url = acDoc.toURL();
docStream = url.openStream();
} else {
docStream = new FileInputStream(p.toFile());
}
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(docStream);
} catch (SAXException | ParserConfigurationException | IOException saxEx) {
doc = null;
} finally {
if (docStream != null)
docStream.close();
}
} catch (FileNotFoundException | MalformedURLException | URISyntaxException e) {
AutotoolsPlugin.log(e);
}
acDocument = doc;
} catch (IOException ioe) {
}
}
acHoverDocs.put(acDocVer, acDocument);
return acDocument;
} | Base | 1 |
protected ICStorageElement translateInputStreamToDocument(InputStream input) {
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
return XmlStorageUtil.createCStorageTree(document);
} catch (Exception e) {
MakeCorePlugin.log(e);
}
return null;
} | Base | 1 |
public void saveDiscoveredScannerInfoToState(IProject project, InfoContext context,
IDiscoveredScannerInfoSerializable serializable) throws CoreException {
Document document = getDocument(project);
// Create document
try {
saveDiscoveredScannerInfo(context, serializable, document);
// Transform the document to something we can save in a file
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(stream);
transformer.transform(source, result);
// Save the document
try {
IPath path = getDiscoveredScannerConfigStore(project);
FileOutputStream file = new FileOutputStream(path.toFile());
file.write(stream.toByteArray());
file.close();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
}
// Close the streams
stream.close();
} catch (TransformerException e) {
MakeCorePlugin.log(e);
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
} catch (IOException e) {
MakeCorePlugin.log(e);
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
}
} | Base | 1 |
private Document getDocument(IProject project) throws CoreException {
// Get the document
Reference<Document> ref = fDocumentCache.get(project);
Document document = ref != null ? ref.get() : null;
if (document == null) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
IPath path = getDiscoveredScannerConfigStore(project);
if (path.toFile().exists()) {
// read form file
FileInputStream file = new FileInputStream(path.toFile());
document = builder.parse(file);
Node rootElem = document.getFirstChild();
if (rootElem.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE) {
// no version info; upgrade
upgradeDocument(document, project);
}
} else {
// create new document
document = builder.newDocument();
ProcessingInstruction pi = document.createProcessingInstruction(SCD_STORE_VERSION, "version=\"2\""); //$NON-NLS-1$
document.appendChild(pi);
Element rootElement = document.createElement(SI_ELEM);
rootElement.setAttribute(ID_ATTR, CDESCRIPTOR_ID);
document.appendChild(rootElement);
}
fDocumentCache.put(project, new SoftReference<>(document));
} catch (IOException e) {
MakeCorePlugin.log(e);
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
} catch (ParserConfigurationException e) {
MakeCorePlugin.log(e);
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
} catch (SAXException e) {
MakeCorePlugin.log(e);
throw new CoreException(new Status(IStatus.ERROR, MakeCorePlugin.getUniqueIdentifier(), -1,
MakeMessages.getString("DiscoveredPathManager.File_Error_Message"), e)); //$NON-NLS-1$
}
}
return document;
} | Base | 1 |
public static boolean manages(IResource resource) {
ICProjectDescription des = CoreModel.getDefault().getProjectDescription(resource.getProject(), false);
if (des == null) {
return false;
}
ICConfigurationDescription cfgDes = des.getActiveConfiguration();
IConfiguration cfg = ManagedBuildManager.getConfigurationForDescription(cfgDes);
if (cfg != null)
return true;
return false;
// // The managed build manager manages build information for the
// // resource IFF it it is a project and has a build file with the proper
// // root element
// IProject project = null;
// if (resource instanceof IProject){
// project = (IProject)resource;
// } else if (resource instanceof IFile) {
// project = ((IFile)resource).getProject();
// } else {
// return false;
// }
// IFile file = project.getFile(SETTINGS_FILE_NAME);
// if (file.exists()) {
// try {
// InputStream stream = file.getContents();
// DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Document document = parser.parse(stream);
// NodeList nodes = document.getElementsByTagName(ROOT_NODE_NAME);
// return (nodes.getLength() > 0);
// } catch (Exception e) {
// return false;
// }
// }
// return false;
} | Base | 1 |
public static void main(String[] args) {
Test test = new Test();
try {
XMLDumper dumper = new XMLDumper(test);
Document document = dumper.getDocument();
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.out.println("STRXML = " + writer.toString()); //Spit out DOM as a String //$NON-NLS-1$
} catch (TransformerException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
} | Base | 1 |
public XMLDumper(Object obj) throws ParserConfigurationException {
document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
document.appendChild(createObject(obj));
} | Base | 1 |
private Transformer createSerializer() throws CoreException {
try {
return TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException e) {
throw new CoreException(Util.createStatus(e));
} catch (TransformerFactoryConfigurationError e) {
throw new CoreException(Util.createStatus(e));
}
} | Base | 1 |
public void storeMappings(WorkspaceLanguageConfiguration config) throws CoreException {
try {
// Encode mappings as XML and serialize as a String.
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element rootElement = doc.createElement(WORKSPACE_MAPPINGS);
doc.appendChild(rootElement);
addContentTypeMappings(config.getWorkspaceMappings(), rootElement);
Transformer serializer = createSerializer();
DOMSource source = new DOMSource(doc);
StringWriter buffer = new StringWriter();
StreamResult result = new StreamResult(buffer);
serializer.transform(source, result);
String encodedMappings = buffer.getBuffer().toString();
IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
node.put(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, encodedMappings);
node.flush();
} catch (ParserConfigurationException e) {
throw new CoreException(Util.createStatus(e));
} catch (TransformerException e) {
throw new CoreException(Util.createStatus(e));
} catch (BackingStoreException e) {
throw new CoreException(Util.createStatus(e));
}
} | Base | 1 |
public WorkspaceLanguageConfiguration decodeWorkspaceMappings() throws CoreException {
IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
IEclipsePreferences defaultNode = DefaultScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
String encodedMappings = node.get(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, null);
if (encodedMappings == null) {
encodedMappings = defaultNode.get(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, null);
}
WorkspaceLanguageConfiguration config = new WorkspaceLanguageConfiguration();
if (encodedMappings == null || encodedMappings.length() == 0) {
return config;
}
// The mappings are encoded as XML in a String so we need to parse it.
InputSource input = new InputSource(new StringReader(encodedMappings));
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
config.setWorkspaceMappings(decodeContentTypeMappings(document.getDocumentElement()));
return config;
} catch (SAXException e) {
throw new CoreException(Util.createStatus(e));
} catch (IOException e) {
throw new CoreException(Util.createStatus(e));
} catch (ParserConfigurationException e) {
throw new CoreException(Util.createStatus(e));
}
} | Base | 1 |
private synchronized void initExtensionPoints() {
if (storageTypeMap != null)
return;
Map<String, List<CProjectDescriptionStorageTypeProxy>> m = new HashMap<>();
IExtensionPoint extpoint = Platform.getExtensionRegistry().getExtensionPoint(CCorePlugin.PLUGIN_ID,
CPROJ_DESC_STORAGE_EXT_ID);
for (IExtension extension : extpoint.getExtensions()) {
for (IConfigurationElement configEl : extension.getConfigurationElements()) {
if (configEl.getName().equalsIgnoreCase(CPROJ_STORAGE_TYPE)) {
CProjectDescriptionStorageTypeProxy type = initStorageType(configEl);
if (type != null) {
if (!m.containsKey(type.id))
m.put(type.id, new LinkedList<CProjectDescriptionStorageTypeProxy>());
m.get(type.id).add(type);
}
}
}
}
storageTypeMap = m;
} | Base | 1 |
public Element createXmlElementCopy(InternalXmlStorageElement el) throws CoreException {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element newXmlEl = null;
synchronized (doc) {
synchronized (el.fLock) {
if (el.fElement.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
Document baseDoc = el.fElement.getOwnerDocument();
NodeList list = baseDoc.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
node = importAddNode(doc, node);
if (node.getNodeType() == Node.ELEMENT_NODE && newXmlEl == null) {
newXmlEl = (Element) node;
}
}
} else {
newXmlEl = (Element) importAddNode(doc, el.fElement);
}
return newXmlEl;
}
}
} catch (ParserConfigurationException e) {
throw ExceptionFactory.createCoreException(e);
} catch (FactoryConfigurationError e) {
throw ExceptionFactory.createCoreException(e);
}
} | Base | 1 |
private ByteArrayOutputStream write(ICStorageElement element) throws CoreException {
Document doc = ((InternalXmlStorageElement) element).fElement.getOwnerDocument();
XmlUtil.prettyFormat(doc);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
// Indentation is done with XmlUtil.prettyFormat(doc)
transformer.setOutputProperty(OutputKeys.INDENT, "no"); //$NON-NLS-1$
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(stream);
transformer.transform(source, result);
return stream;
} catch (TransformerConfigurationException e) {
throw ExceptionFactory.createCoreException(e);
} catch (TransformerException e) {
throw ExceptionFactory.createCoreException(e);
}
} | Base | 1 |
private ICStorageElement readOldCDTProjectFile(IProject project) throws CoreException {
ICStorageElement storage = null;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = null;
InputStream stream = getSharedProperty(project, OLD_CDTPROJECT_FILE_NAME);
if (stream != null) {
doc = builder.parse(stream);
NodeList nodeList = doc.getElementsByTagName(OLD_PROJECT_DESCRIPTION);
if (nodeList != null && nodeList.getLength() > 0) {
Node node = nodeList.item(0);
storage = new InternalXmlStorageElement((Element) node, false);
}
}
} catch (ParserConfigurationException e) {
throw ExceptionFactory.createCoreException(e);
} catch (SAXException e) {
throw ExceptionFactory.createCoreException(e);
} catch (IOException e) {
throw ExceptionFactory.createCoreException(e);
}
return storage;
} | Base | 1 |
protected Element createXmlElementCopy() throws CoreException {
try {
synchronized (fLock) {
Element newXmlEl = null;
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
synchronized (doc) {
if (fElement.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
Document baseDoc = fElement.getOwnerDocument();
NodeList list = baseDoc.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
node = importAddNode(doc, node);
if (node.getNodeType() == Node.ELEMENT_NODE && newXmlEl == null) {
newXmlEl = (Element) node;
}
}
} else {
newXmlEl = (Element) importAddNode(doc, fElement);
}
}
return newXmlEl;
}
} catch (ParserConfigurationException e) {
throw ExceptionFactory.createCoreException(e);
} catch (FactoryConfigurationError e) {
throw ExceptionFactory.createCoreException(e);
}
} | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.