Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

In this page you can find the example usage for java.io StringWriter write.

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:au.edu.usq.fascinator.harvester.feed.FeedHarvester.java

public String getConfig() {
    StringWriter writer = new StringWriter();
    try {//from   w  ww  .  j  a  v a  2 s  .c  o  m
        IOUtils.copy(getClass().getResourceAsStream("/" + getId() + "-config.html"), writer);
    } catch (IOException ioe) {
        writer.write("<span class=\"error\">" + ioe.getMessage() + "</span>");
    }
    return writer.toString();
}

From source file:org.jactr.eclipse.ui.commands.ConvertTo.java

@Override
protected IContributionItem[] getContributionItems() {
    Collection<IContributionItem> rtn = new ArrayList<IContributionItem>();
    IWorkbenchWindow ww = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    ISelection selection = ww.getSelectionService().getSelection();
    ICompilationUnit compilationUnit = null;
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection sSelection = (IStructuredSelection) selection;
        if (sSelection.getFirstElement() instanceof IResource) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Found resource " + sSelection.getFirstElement());
            compilationUnit = CompilationUnitManager.acquire((IResource) sSelection.getFirstElement());
        }/*w w w.  j a  v a  2s  .  c  o  m*/
    }

    if (compilationUnit == null || !(compilationUnit instanceof IProjectCompilationUnit))
        return new IContributionItem[0];

    IResource resource = ((IProjectCompilationUnit) compilationUnit).getResource();

    final String currentExtension = resource.getFileExtension();
    /*
     * find all the code generators..
     */
    for (String extension : CodeGeneratorFactory.getExtensions())
        if (!extension.equals(currentExtension)) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Creating convert to " + extension);
            final ICodeGenerator codeGenerator = CodeGeneratorFactory.getCodeGenerator(extension);
            final IFile file = (IFile) resource;
            final CommonTree modelDescriptor = compilationUnit.getModelDescriptor();
            IAction action = new Action(extension) {
                @Override
                public void run() {
                    IFolder folder = (IFolder) file.getParent();
                    String sansExtension = file.getName();
                    sansExtension = sansExtension.substring(0, sansExtension.lastIndexOf(currentExtension));
                    IFile toCreate = folder.getFile(sansExtension + getText());
                    if (!toCreate.exists()) {
                        StringWriter sw = new StringWriter();
                        for (StringBuilder line : codeGenerator.generate(modelDescriptor, true)) {
                            sw.write(line.toString());
                            sw.write("\n");
                            line.delete(0, line.length());
                        }

                        InputStream input = new ByteArrayInputStream(sw.toString().getBytes());

                        try {
                            toCreate.create(input, true, null);
                        } catch (CoreException e) {
                            LOGGER.error("Could not create " + toCreate, e);
                        }
                    } else
                        LOGGER.error("File " + toCreate + " already exists");
                }
            };

            rtn.add(new ActionContributionItem(action));
        }

    CompilationUnitManager.release(compilationUnit);

    return rtn.toArray(new IContributionItem[0]);
}

From source file:org.opennms.upgrade.implementations.ServiceConfigMigratorOffline.java

@Override
public void execute() throws OnmsUpgradeException {
    if (skipMe)/*from   w  ww  .j  a  va  2s.c  o  m*/
        return;
    try {
        ServiceConfiguration currentCfg = JaxbUtils.unmarshal(ServiceConfiguration.class, configFile);
        int index = 0;
        for (Service baseSvc : baseConfig.getServiceCollection()) {
            Service localSvc = getService(currentCfg, baseSvc.getName());
            if (localSvc == null) {
                if (baseSvc.isEnabled()) {
                    log("Adding new service %s\n", baseSvc.getName());
                } else {
                    log("Marking service %s as disabled\n", baseSvc.getName());
                }
                currentCfg.getServiceCollection().add(index, baseSvc);
                continue;
            }
            if (!baseSvc.isEnabled()) {
                log("Disabling service %s because it is not on the default list of enabled services\n",
                        localSvc.getName());
                localSvc.setEnabled(false);
            }
            if (localSvc.getClassName().equals("org.opennms.netmgt.poller.jmx.RemotePollerBackEnd")) {
                log("Fixing the class path for RemotePollerBackEnd.\n");
                localSvc.setClassName("org.opennms.netmgt.poller.remote.jmx.RemotePollerBackEnd");
            }
            if (localSvc.getName().equals("OpenNMS:Name=Linkd")) {
                log("Disabling Linkd (to promote EnhancedLinkd)\n");
                localSvc.setEnabled(false);
            }
            Attribute a = getLoggingPrefix(localSvc);
            if (a != null) {
                String prefix = a.getValue().getContent().toLowerCase();
                // If the logging prefix isn't already lower case...
                if (!a.getValue().getContent().equals(prefix)) {
                    // then set it to the lower case value
                    log("Fixing logging prefix for service %s\n", localSvc.getName());
                    a.getValue().setContent(prefix);
                }
            }
            index++;
        }
        StringWriter sw = new StringWriter();
        sw.write("<?xml version=\"1.0\"?>\n");
        sw.write("<!-- NOTE!!!!!!!!!!!!!!!!!!!\n");
        sw.write("The order in which these services are specified is important - for example, Eventd\n");
        sw.write("will need to come up last so that none of the event topic subcribers loose any event.\n");
        sw.write("\nWhen splitting services to run on mutiple VMs, the order of the services should be\n");
        sw.write("maintained\n");
        sw.write("-->\n");
        JaxbUtils.marshal(currentCfg, sw);
        FileWriter fw = new FileWriter(configFile);
        fw.write(sw.toString());
        fw.close();
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix services configuration because " + e.getMessage(), e);
    }
}

From source file:org.eobjects.datacleaner.monitor.server.job.ExecutionLoggerImpl.java

@Override
public void setStatusFailed(Object component, Object data, Throwable throwable) {
    boolean erronuousBefore = _erronuous.getAndSet(true);
    if (erronuousBefore) {
        // don't report another error
        if (throwable != null) {
            logger.error(/*from w  w  w  .j  av  a 2  s. com*/
                    "More than one error was reported, but only the first will be put into the user-log. This error was also reported: "
                            + throwable.getMessage(),
                    throwable);
        }
    } else {
        _execution.setJobEndDate(new Date());
        _execution.setExecutionStatus(ExecutionStatus.FAILURE);

        final StringWriter stringWriter = new StringWriter();
        stringWriter.write("Job execution FAILURE");

        if (throwable != null && !StringUtils.isNullOrEmpty(throwable.getMessage())) {
            stringWriter.write("\n - ");
            stringWriter.write(throwable.getMessage());
            stringWriter.write(" (");
            stringWriter.write(throwable.getClass().getSimpleName());
            stringWriter.write(")");
        }

        if (component != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Failure component: " + component);
        }

        if (data != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Failure input data: " + data);
        }

        if (throwable != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Exception stacktrace of failure condition:");
            stringWriter.write('\n');
            final PrintWriter printWriter = new PrintWriter(stringWriter);
            throwable.printStackTrace(printWriter);
            printWriter.flush();
        }

        stringWriter.write("\nCheck the server logs for more details, warnings and debug information.");

        log(stringWriter.toString());
        flushLog();

        if (_eventPublisher != null) {
            _eventPublisher.publishEvent(new JobFailedEvent(this, _execution, component, data, throwable));
        }
    }
}

From source file:org.datacleaner.monitor.server.job.ExecutionLoggerImpl.java

@Override
public void setStatusFailed(Object component, Object data, Throwable throwable) {
    final boolean erronuousBefore = _erronuous.getAndSet(true);
    if (erronuousBefore) {
        if (throwable instanceof PreviousErrorsExistException) {
            // don't report PreviousErrorsExistExceptions
            logger.error(/* w w w. j a va  2 s .co m*/
                    "More than one error was reported, but only the first will be put into the user-log. This error was also reported: "
                            + throwable.getMessage(),
                    throwable);
        } else {
            log("\n - Additional exception stacktrace:", throwable);
            flushLog();
        }
    } else {
        _execution.setJobEndDate(new Date());
        _execution.setExecutionStatus(ExecutionStatus.FAILURE);

        final StringWriter stringWriter = new StringWriter();
        stringWriter.write("Job execution FAILURE");

        if (throwable != null && !StringUtils.isNullOrEmpty(throwable.getMessage())) {
            stringWriter.write("\n - ");
            stringWriter.write(throwable.getMessage());
            stringWriter.write(" (");
            stringWriter.write(throwable.getClass().getSimpleName());
            stringWriter.write(")");
        }

        if (component != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Failure component: " + component);
        }

        if (data != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Failure input data: " + data);
        }

        if (throwable != null) {
            stringWriter.write('\n');
            stringWriter.write(" - Exception stacktrace of failure condition:");
            stringWriter.write('\n');
            final PrintWriter printWriter = new PrintWriter(stringWriter);
            throwable.printStackTrace(printWriter);
            printWriter.flush();
        }

        stringWriter.write("\nCheck the server logs for more details, warnings and debug information.");

        log(stringWriter.toString());
        flushLog();

        if (_eventPublisher != null) {
            _eventPublisher.publishEvent(new JobFailedEvent(this, _execution, component, data, throwable));
        }
    }
}

From source file:com.amalto.core.server.MDMTransaction.java

@Override
public String getCreationStackTrace() {
    String eol = System.getProperty("line.separator"); //$NON-NLS-1$
    StringWriter writer = new StringWriter();
    if (this.creationStackTrace != null) {
        writer.write(
                "==================================================================================" + eol); //$NON-NLS-1$
        writer.write("MDM Transaction creation stacktrace:" + eol); //$NON-NLS-1$
        for (StackTraceElement s : this.creationStackTrace) {
            writer.append(s.toString());
            writer.append(eol);//from  ww w. j  a v  a2  s.com
        }
        writer.write(
                "==================================================================================" + eol); //$NON-NLS-1$
    } else {
        writer.append("No creationStackTrace captured at transaction creation. Activate DEBUG on " //$NON-NLS-1$
                + MDMTransaction.class.getCanonicalName() + " to capture future transactions."); //$NON-NLS-1$
    }
    return writer.toString();
}

From source file:samson.AndroidNotifications.java

/**
 * Sets the storage value with the given list of identifiers.
 *///from   w ww.jav a  2s. com
protected synchronized void setNotifications(Set<Integer> ids) {
    // build the json list of identifiers
    Json.Array jsonids = PlayN.json().createArray();
    for (int id : ids) {
        jsonids.add(id);
    }

    // build the json object
    Json.Object json = PlayN.platform().json().createObject();
    json.put(JSON_KEY_IDS, jsonids);

    // write the json object to the json writer
    Json.Writer jsonwriter = PlayN.json().newWriter().useVerboseFormat(false).object();
    json.write(jsonwriter);
    jsonwriter.end();

    // convert json writer to string
    StringWriter stringwriter = new StringWriter();
    stringwriter.write(jsonwriter.write());

    // store the string
    PlayN.storage().setItem(STORAGE_KEY, stringwriter.toString());
}

From source file:org.n52.wps.server.feed.FeedServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /*// w  ww .jav a2 s .  c  o  m
     * how can the new remote repository be posted?!
     * 1. complete xml snippet
     * 2. what else?!
     */

    RemoteRepository newRemoteRepo = null;

    OutputStream out = res.getOutputStream();
    try {
        InputStream is = req.getInputStream();
        if (req.getParameterMap().containsKey("request")) {
            is = new ByteArrayInputStream(req.getParameter("request").getBytes("UTF-8"));
        }

        // WORKAROUND cut the parameter name "request" of the stream
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringWriter sw = new StringWriter();
        int k;
        while ((k = br.read()) != -1) {
            sw.write(k);
        }
        LOGGER.debug(sw.toString());
        String s;
        String reqContentType = req.getContentType();
        if (sw.toString().startsWith("request=")) {
            if (reqContentType.equalsIgnoreCase("text/plain")) {
                s = sw.toString().substring(8);
            } else {
                s = URLDecoder.decode(sw.toString().substring(8), "UTF-8");
            }
            LOGGER.debug(s);
        } else {
            s = sw.toString();
        }

        newRemoteRepo = RemoteRepositoryDocument.Factory.parse(s).getRemoteRepository();

        addNewRemoteRepository(newRemoteRepo);

        res.setStatus(HttpServletResponse.SC_OK);

    } catch (Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error occured");
    }
    out.flush();
    out.close();

}

From source file:org.dawnsci.dde.templates.AbstractTemplateTestBase.java

/**
 * Tests the contents of <i>plugin.xml</i>. The test is a simple string
 * compare. It may be rewritten to test using internal PDE API.
 * //from  w  w w.  j a va 2 s  .  com
 * @throws CoreException 
 * @throws IOException 
 */
@Test
public void testPlugin() throws CoreException, IOException {
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getProjectName());
    IFile file = project.getFile(new Path("plugin.xml"));
    InputStream contents = file.getContents(false);
    InputStream expected = new ByteArrayInputStream(getPluginContents().getBytes());
    if (!isEqual(expected, contents)) {
        contents = file.getContents();
        expected = new ByteArrayInputStream(getPluginContents().getBytes());
        StringWriter sw = new StringWriter();
        sw.write("Expected: \n");
        IOUtils.copy(expected, sw);
        sw.write("Found: \n");
        IOUtils.copy(contents, sw);
        fail(sw.toString());
    }
}

From source file:org.opcfoundation.ua.stacktest.io.BetwixtTestLog.java

private void write() {
    try {/*ww  w  .  j ava2s  . c o m*/
        // Start by preparing the writer
        // We'll write to a string 
        StringWriter outputWriter = new StringWriter();

        // Betwixt just writes out the bean as a fragment
        // So if we want well-formed xml, we need to add the prolog
        outputWriter.write("<?xml version='1.0' ?>\n");

        // create write and set basic properties
        BeanWriter beanWriter = new BeanWriter(outputWriter);
        //writer.getXMLIntrospector().setAttributesForPrimitives(true);
        beanWriter.enablePrettyPrint();
        beanWriter.setInitialIndentLevel(0);
        beanWriter.getBindingConfiguration().setMapIDs(false);

        beanWriter.getBindingConfiguration().setObjectStringConverter(new DateConverter());
        /*                 new ObjectStringConverter() {
            public String objectToString(Object object, Class type, Context context) {
               if (object == null)
                  return "";
               else if (GregorianCalendar.class.equals(context.getBean().getClass()))
                  return ((GregorianCalendar) context.getBean()).getTime().toString();
               else if (GregorianCalendar.class.equals(type))
                  return ((GregorianCalendar) object).getTime().toString();
               else
                  return object.toString();
            }
         }
         );
        */
        // set a custom name mapper for attributes
        beanWriter.getXMLIntrospector().getConfiguration().setAttributeNameMapper(new CapitalizeNameMapper());
        // set a custom name mapper for elements
        beanWriter.getXMLIntrospector().getConfiguration().setElementNameMapper(new CapitalizeNameMapper());

        /*          beanWriter.getXMLIntrospector().getConfiguration().setPropertySuppressionStrategy(
           new PropertySuppressionStrategy() {
                public boolean suppressProperty(Class clazz, Class type, String name) {
                    return "class".equals(name) || GregorianCalendar.class.equals(type);
                }
           });
        */ // write out the bean
        beanWriter.write(testLog);
        System.out.println(outputWriter.toString());

        outputWriter.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}