List of usage examples for java.io StringWriter write
public void write(String str)
From source file:de.tu_dortmund.ub.hb_ng.SolRDF.java
@Override public String getResource(String graph, String uri, String format, boolean isAuthorized) throws LinkedDataStorageException { this.logger.info("getResource: " + graph); this.logger.info("getResource: " + uri); this.logger.info("getResource: " + format); this.logger.info("getResource: " + isAuthorized); String resource = null;//from w w w . j a v a 2s . co m String queryResult = this.doResourceRequest(graph, uri, format, isAuthorized); if (queryResult != null && !queryResult.equals("")) { try { switch (format) { case "html": { Document document = new SAXBuilder().build(new StringReader(queryResult)); StringWriter stringWriter = new StringWriter(); stringWriter.write(htmlOutputter(document, this.config.getProperty("xslt.resource"), null)); resource = stringWriter.toString(); break; } case "rdf.xml": { Document document = new SAXBuilder().build(new StringReader(queryResult)); StringWriter stringWriter = new StringWriter(); XMLOutputter xmlOutputter = new XMLOutputter(); xmlOutputter.output(document, stringWriter); resource = stringWriter.toString(); break; } case "rdf.ttl": { resource = queryResult; break; } case "json": { resource = queryResult; break; } case "nquads": { resource = queryResult; break; } } } catch (JDOMException | IOException e) { throw new LinkedDataStorageException(e.getMessage(), e.getCause()); } } return resource; }
From source file:se.mithlond.services.shared.test.entity.PlainJaxbContextRule.java
/** * Marshals the supplied objects into an XML String, or throws an IllegalArgumentException * containing a wrapped JAXBException indicating why the marshalling was unsuccessful. * * @param loader The ClassLoader to use in order to load all classes previously added * by calls to the {@code add} method. * @param emitJSON if {@code true}, the method will attempt to output JSON instead of XML. * This requires the EclipseLink MOXy implementation as the JAXBContextFactory. * @param objects The objects to Marshal into XML. * @return An XML-formatted String containing * @throws IllegalArgumentException if the marshalling operation failed. * The {@code cause} field in the IllegalArgumentException contains * the JAXBException thrown by the JAXB framework. * @see #add(Class[])/*w w w .j a v a 2 s . com*/ */ @SuppressWarnings("all") public String marshal(final ClassLoader loader, final boolean emitJSON, final Object... objects) throws IllegalArgumentException { // Create an EntityTransporter, to extract the types as required by the plain JAXBContext. final EntityTransporter<Object> transporter = new EntityTransporter<>(); for (Object current : objects) { transporter.addItem(current); } // Use EclipseLink? if (emitJSON) { setUseEclipseLinkMOXyIfAvailable(true); } if (useEclipseLinkMOXyIfAvailable) { System.setProperty(JAXB_CONTEXTFACTORY_PROPERTY, ECLIPSELINK_JAXB_CONTEXT_FACTORY); } else { System.clearProperty(JAXB_CONTEXTFACTORY_PROPERTY); } // Extract class info as required by the JAXBContext. final SortedSet<String> clsInfo = transporter.getClassInformation(); try { jaxbContext = JAXBContext.newInstance(getClasses(loader, clsInfo), marshallerProperties); log.info("Got JAXBContext of type " + jaxbContext.getClass().getName() + ", with classes"); } catch (JAXBException e) { throw new IllegalArgumentException("Could not create JAXB context.", e); } // Handle the namespace mapper handleNamespacePrefixMapper(); Marshaller marshaller = null; try { marshaller = jaxbContext.createMarshaller(); // Should we validate what we write? if (performXsdValidation) { if ("org.eclipse.persistence.jaxb.JAXBContext".equals(jaxbContext.getClass().getName())) { // Cast to the appropriate JAXBContext org.eclipse.persistence.jaxb.JAXBContext eclipseLinkJaxbContext = ((org.eclipse.persistence.jaxb.JAXBContext) jaxbContext); if (emitJSON) { final SimpleSchemaOutputResolver simpleResolver = new SimpleSchemaOutputResolver(); Arrays.stream(objects).filter(c -> c != null).forEach(c -> { final Class<?> currentClass = c.getClass(); if (log.isDebugEnabled()) { log.debug("Generating JSON schema for " + currentClass.getName()); } try { eclipseLinkJaxbContext.generateJsonSchema(simpleResolver, currentClass); } catch (Exception e) { log.error("Could not generate JSON schema", e); } }); } else { final Tuple<Schema, LSResourceResolver> schema2LSResolver = generateTransientXSD( jaxbContext); marshaller.setSchema(schema2LSResolver.getKey()); } } } } catch (Exception e) { try { marshaller = jaxbContext.createMarshaller(); } catch (JAXBException e1) { throw new IllegalStateException("Could not create non-validating JAXB Marshaller", e); } } // Should we emit JSON instead of XML? if (emitJSON) { try { marshaller.setProperty(ECLIPSELINK_MEDIA_TYPE, JSON_CONTENT_TYPE); marshaller.setProperty(ECLIPSELINK_JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE); } catch (PropertyException e) { // This is likely not the EclipseLink Marshaller. log.error( "Could not assign EclipseLink properties to Marshaller of type " + marshaller.getClass().getName() + "]. Proceeding, but results may be unexpected.", e); } } // Assign all other Marshaller properties. try { for (Map.Entry<String, Object> current : marshallerProperties.entrySet()) { marshaller.setProperty(current.getKey(), current.getValue()); } } catch (PropertyException e) { final StringBuilder builder = new StringBuilder("Could not assign Marshaller properties."); marshallerProperties.entrySet().stream() .forEach(c -> builder.append("\n [" + c.getKey() + "]: " + c.getValue())); throw new IllegalStateException(builder.toString(), e); } // Marshal the objects final StringWriter result = new StringWriter(); for (int i = 0; i < objects.length; i++) { final StringWriter tmp = new StringWriter(); try { marshaller.marshal(objects[i], tmp); result.write(tmp.toString()); } catch (JAXBException e) { final String currentTypeName = objects[i] == null ? "<null>" : objects[i].getClass().getName(); throw new IllegalArgumentException( "Could not marshalToXML object [" + i + "] of type [" + currentTypeName + "].", e); } catch (Exception e) { throw new IllegalArgumentException("Could not marshalToXML object [" + i + "]: " + objects[i], e); } } // All done. return result.toString(); }
From source file:com.omertron.themoviedbapi.tools.WebBrowser.java
public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException { StringWriter content = null; try {// w ww. ja va2s. co m content = new StringWriter(); BufferedReader in = null; HttpURLConnection cnx = null; OutputStreamWriter wr = null; try { cnx = (HttpURLConnection) openProxiedConnection(url); // If we get a null connection, then throw an exception if (cnx == null) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, "No HTTP connection could be made.", url); } if (isDeleteRequest) { cnx.setDoOutput(true); cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); cnx.setRequestMethod("DELETE"); } sendHeader(cnx); if (StringUtils.isNotBlank(jsonBody)) { cnx.setDoOutput(true); wr = new OutputStreamWriter(cnx.getOutputStream()); wr.write(jsonBody); } readHeader(cnx); // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error if (cnx.getResponseCode() >= 400) { in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx))); } else { in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx))); } String line; while ((line = in.readLine()) != null) { content.write(line); } } finally { if (wr != null) { wr.flush(); wr.close(); } if (in != null) { in.close(); } if (cnx instanceof HttpURLConnection) { ((HttpURLConnection) cnx).disconnect(); } } return content.toString(); } catch (IOException ex) { throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex); } finally { if (content != null) { try { content.close(); } catch (IOException ex) { LOG.debug("Failed to close connection: " + ex.getMessage()); } } } }
From source file:org.trianacode.taskgraph.service.RunnableTask.java
private void notifyError(Throwable e) { StringWriter s = new StringWriter(); s.write("Error in:" + getQualifiedTaskName() + "\n"); PrintWriter p = new PrintWriter(s); e.printStackTrace(p);/* w ww. ja v a2s . c o m*/ p.flush(); notifyError(s.toString()); }
From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java
protected String resolveLinks(String _content) { tagFilterReader reader = new tagFilterReader(new StringReader(_content)); reader.registerTagFilter(new urlResolver(url, port)); java.io.StringWriter writer = new java.io.StringWriter(); try {//w w w. j a v a 2 s. com int ch = reader.readChar(); while (ch != -1) { writer.write(ch); ch = reader.readChar(); } return writer.toString(); } catch (IOException ignored) { } // won't happen since the source is a String return _content; }
From source file:uk.ac.ebi.embl.api.validation.EnaValidator.java
/** * Validate files./*from ww w. ja v a 2 s . co m*/ * @throws ValidationEngineException */ private void validateFiles() { List<ValidationPlanResult> planResults = new ArrayList<ValidationPlanResult>(); int parseErrorCount = 0; try { long timeIn = System.currentTimeMillis(); if (filterMode && filterPrefix != null) { goodFilesWriter = new FileWriter(filterPrefix + "_good.txt"); badFilesWriter = new FileWriter(filterPrefix + "_bad.txt"); } for (File file : entryFiles) { List<ValidationPlanResult> results = validateFile(file, errorWriter); planResults.addAll(results); } infoWriter.flush(); errorWriter.flush(); reportWriter.flush(); fixWriter.flush(); infoWriter.close(); errorWriter.close(); reportWriter.close(); fixWriter.close(); if (filterMode && filterPrefix != null) { badFilesWriter.flush(); badFilesWriter.close(); goodFilesWriter.flush(); goodFilesWriter.close(); } List<ValidationMessage<Origin>> messages = new ArrayList<ValidationMessage<Origin>>(); for (ValidationPlanResult planResult : planResults) { messages.addAll(planResult.getMessages()); } for (ValidationResult parseResult : parseResults) { messages.addAll(parseResult.getMessages()); for (ValidationMessage message : parseResult.getMessages()) { parseErrorCount++; } } /** * will be built up to form the summary for the whole run */ String summaryLine = ""; if (!planResults.isEmpty()) { FlattenedMessageResult results = Utils.flattenMessages(messages, MESSAGE_FLATTEN_THRESHOLD); List<ValidationMessage> flattenedMessages = results.getFlattenedMessages(); List<ValidationMessage> unFlattenedMessages = results.getUnFlattenedMessages(); Collections.sort(flattenedMessages, new ValidationMessageComparator()); Collections.sort(unFlattenedMessages, new ValidationMessageComparator()); if (!flattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\n***MESSAGES SUMMARY***"); summaryLine = summaryLine.concat( "\nCompressed messages (occurring more than " + MESSAGE_FLATTEN_THRESHOLD + " times)"); for (ValidationMessage message : flattenedMessages) { summaryLine = summaryLine.concat("\n" + message.getSeverity()); summaryLine = summaryLine.concat(": "); summaryLine = summaryLine.concat(message.getMessage()); summaryLine = summaryLine.concat(" (" + message.getMessageKey() + ") "); } } if (!unFlattenedMessages.isEmpty()) { summaryLine = summaryLine.concat("\n\nMessages"); for (ValidationMessage message : unFlattenedMessages) { summaryLine = summaryLine.concat("\n" + message.getSeverity()); summaryLine = summaryLine.concat(": "); summaryLine = summaryLine.concat(message.getMessage()); summaryLine = summaryLine.concat(" (" + message.getMessageKey() + ") "); for (Object origin : message.getOrigins()) { StringWriter writer = new StringWriter(); String text = ((Origin) origin).getOriginText(); writer.write(text); summaryLine = summaryLine.concat(writer.toString()); writer.close(); } } } summaryLine = summaryLine.concat("\n\n***FILE SUMMARY***\n"); List<FlattenedValidationPlanResult> flattenedPlanResults = Utils .flattenValidationPlans(planResults); for (FlattenedValidationPlanResult flattenedResult : flattenedPlanResults) { summaryLine = summaryLine.concat(flattenedResult.getFileName() + " - "); summaryLine = summaryLine.concat(flattenedResult.getEntryCount() + " entries, "); summaryLine = summaryLine.concat(flattenedResult.getFailedEntryCount() + " failed entries, "); summaryLine = summaryLine .concat((flattenedResult.getErrorCount() + parseErrorCount) + " errors, "); summaryLine = summaryLine.concat(flattenedResult.getFixCount() + " fixes, "); summaryLine = summaryLine.concat(flattenedResult.getWarningInfoCount() + " warnings & info"); summaryLine = summaryLine.concat("\n"); } } summaryLine = summaryLine.concat("\n*** SUMMARY***\n"); summaryLine = summaryLine.concat("Fixed Entries:" + fixCount + "\n"); summaryLine = summaryLine.concat("Failed Entries:" + failCount + "\n"); summaryLine = summaryLine.concat("Checked Entries:" + totalEntryCount + "\n"); summaryLine = summaryLine.concat("Unchanged Entries:" + unchangedCount + "\n"); long timeOut = System.currentTimeMillis(); long timeToRun = (timeOut - timeIn) / 1000; summaryLine = summaryLine .concat("\n\nProcessed " + totalEntryCount + " entries in " + timeToRun + " seconds.\n\n"); printMessage(summaryLine, LOG_LEVEL_SUMMARY); summaryWriter.write(summaryLine); summaryWriter.flush(); summaryWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.codelibs.fess.api.json.JsonApiManager.java
protected String escapeJsonString(final String str) { final StringWriter out = new StringWriter(str.length() * 2); int sz;// www. ja v a 2 s. c om sz = str.length(); for (int i = 0; i < sz; i++) { final char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u"); out.write(hex(ch)); } else if (ch > 0xff) { out.write("\\u0"); out.write(hex(ch)); } else if (ch > 0x7f) { out.write("\\u00"); out.write(hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default: if (ch > 0xf) { out.write("\\u00"); out.write(hex(ch)); } else { out.write("\\u000"); out.write(hex(ch)); } break; } } else { switch (ch) { case '"': out.write("\\u0022"); break; case '\\': out.write("\\u005C"); break; case '/': out.write("\\u002F"); break; default: out.write(ch); break; } } } return out.toString(); }
From source file:org.apache.maven.archetype.mojos.IntegrationTestMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {// w ww .ja v a2 s . co m return; } if (!testProjectsDirectory.exists()) { getLog().warn("No Archetype IT projects: root 'projects' directory not found."); return; } File archetypeFile = project.getArtifact().getFile(); if (archetypeFile == null) { throw new MojoFailureException( "Unable to get the archetypes' artifact which should have just been built:" + " you probably launched 'mvn archetype:integration-test' instead of" + " 'mvn integration-test'."); } try { List<File> projectsGoalFiles = FileUtils.getFiles(testProjectsDirectory, "**/goal.txt", ""); if (projectsGoalFiles.size() == 0) { getLog().warn("No Archetype IT projects: no directory with goal.txt found."); return; } StringWriter errorWriter = new StringWriter(); for (File goalFile : projectsGoalFiles) { try { processIntegrationTest(goalFile, archetypeFile); } catch (IntegrationTestFailure ex) { errorWriter.write("\nArchetype IT '" + goalFile.getParentFile().getName() + "' failed: "); errorWriter.write(ex.getMessage()); } } String errors = errorWriter.toString(); if (!StringUtils.isEmpty(errors)) { throw new MojoExecutionException(errors); } } catch (IOException ex) { throw new MojoFailureException(ex, ex.getMessage(), ex.getMessage()); } }