Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:cop.raml.processor.RestProcessorTest.java

@Test
public void testAssemble() throws Exception {
    RestApi api = new RestApi();
    api.setTitle("title");
    api.setBaseUri("www.com");
    api.setMediaType(Utils.APPLICATION_JSON);
    api.setDocumentation("docTitle", "docContent");
    api.setVersion("v1");

    Writer out = new StringWriter();

    assemble(api, "raml_08_simple.ftl", out);
    TestUtils.assertThatEquals(out.toString(), SIMPLE_RAML);
}

From source file:com.ibm.jaggr.core.impl.layer.LayerTest.java

/**
 * Test method for {@link com.ibm.jaggr.core.impl.layer.LayerImpl#getInputStream(HttpServletRequest, HttpServletResponse)}.
 * @throws Exception/*from   w ww  .ja  va 2 s .  co  m*/
 */
@SuppressWarnings("unchecked")
@Test
public void testGetInputStream() throws Exception {

    final AggregatorLayerListener layerListener = new AggregatorLayerListener(mockAggregator);
    mockPlatformServices = createMock(IPlatformServices.class);
    IServiceReference mockServiceReference = createMock(IServiceReference.class);
    final IServiceReference[] serviceReferences = new IServiceReference[] { mockServiceReference };
    expect(mockPlatformServices.getServiceReferences(IConfigScopeModifier.class.getName(), "(name=test)"))
            .andReturn(new IServiceReference[] {}).anyTimes();
    expect(mockPlatformServices.getServiceReferences(ILayerListener.class.getName(), "(name=test)"))
            .andAnswer(new IAnswer<IServiceReference[]>() {
                @Override
                public IServiceReference[] answer() throws Throwable {
                    return serviceReferences;
                }
            }).anyTimes();
    expect(mockPlatformServices.getServiceReferences(IOptionsListener.class.getName(), "(name=test)"))
            .andAnswer(new IAnswer<IServiceReference[]>() {
                @Override
                public IServiceReference[] answer() throws Throwable {
                    return null;
                }
            }).anyTimes();
    expect(mockPlatformServices.getService(mockServiceReference)).andReturn(layerListener).anyTimes();
    expect(mockPlatformServices.ungetService(mockServiceReference)).andReturn(true).anyTimes();
    expect(mockPlatformServices.getHeaders()).andReturn(null).anyTimes();
    expect(mockAggregator.getPlatformServices()).andReturn(mockPlatformServices).anyTimes();

    replay(mockAggregator, mockRequest, mockResponse, mockDependencies, mockPlatformServices,
            mockServiceReference);
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    String configJson = "{paths:{p1:'p1',p2:'p2'}, packages:[{name:'foo', location:'foo'}]}";
    configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), configJson, true));

    // Request a single module
    File cacheDir = mockAggregator.getCacheManager().getCacheDir();
    ConcurrentLinkedHashMap<String, CacheEntry> cacheMap = (ConcurrentLinkedHashMap<String, CacheEntry>) ((LayerCacheImpl) mockAggregator
            .getCacheManager().getCache().getLayers()).getLayerBuildMap();
    long totalSize = 0;
    MockRequestedModuleNames modules = new MockRequestedModuleNames();
    modules.setModules(Arrays.asList(new String[] { "p1/a" }));
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    LayerImpl layer = newLayerImpl(modules.toString(), mockAggregator);
    List<String> layerCacheInfo = new LinkedList<String>();
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    InputStream in = layer.getInputStream(mockRequest, mockResponse);
    Writer writer = new StringWriter();
    CopyUtil.copy(in, writer);
    String result = writer.toString();
    System.out.println(result);
    totalSize += result.length();
    assertEquals("[update_lastmod1, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));
    Map<String, String> moduleCacheInfo = (Map<String, String>) requestAttributes
            .get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertTrue(result.contains("\"hello from a.js\""));

    // Request two modules
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    modules.setModules(Arrays.asList(new String[] { "p1/b", "p1/a" }));
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    layer = newLayerImpl(modules.toString(), mockAggregator);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[update_lastmod1, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("hit", moduleCacheInfo.get("p1/a"));
    assertEquals("add", moduleCacheInfo.get("p1/b"));
    assertTrue(result.contains("\"hello from a.js\""));
    assertTrue(result.contains("\"hello from b.js\""));
    totalSize += result.length();
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    // Add a text resource
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    modules.setModules(Arrays.asList(new String[] { "p1/b", "p1/a", "p1/hello.txt" }));
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    layer = newLayerImpl(modules.toString(), mockAggregator);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[update_lastmod1, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("hit", moduleCacheInfo.get("p1/a"));
    assertEquals("hit", moduleCacheInfo.get("p1/b"));
    assertEquals("add", moduleCacheInfo.get("p1/hello.txt"));
    assertTrue(result.contains("\"hello from a.js\""));
    assertTrue(result.contains("\"hello from b.js\""));
    assertTrue(result.contains("Hello world text"));
    totalSize += result.length();
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    // Test filename prologue option
    mockAggregator.getOptions().setOption(IOptions.DEVELOPMENT_MODE, "true");
    layer = newLayerImpl(modules.toString(), mockAggregator);
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(IHttpTransport.SHOWFILENAMES_REQATTRNAME, Boolean.TRUE);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[update_lastmod1, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("hit", moduleCacheInfo.get("p1/a"));
    assertEquals("hit", moduleCacheInfo.get("p1/b"));
    assertEquals("hit", moduleCacheInfo.get("p1/hello.txt"));
    assertTrue(result
            .contains(String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/a.js").toURI())));
    assertTrue(result
            .contains(String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/b.js").toURI())));
    assertTrue(result.contains(
            String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/hello.txt").toURI())));
    totalSize += result.length();
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));
    String saveResult = result;

    // Requst the same layer again and make sure it comes from the layer cache
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(IHttpTransport.SHOWFILENAMES_REQATTRNAME, Boolean.TRUE);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertNull(requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME));
    assertEquals(saveResult, result);
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));

    // rename one of the source files and make sure it busts the cache
    new File(tmpdir, "p1/a.js").renameTo(new File(tmpdir, "p1/a.js.save"));
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.SHOWFILENAMES_REQATTRNAME, Boolean.TRUE);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[update_lastmod2, error_noaction]", layerCacheInfo.toString());
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("remove", moduleCacheInfo.get("p1/a"));
    assertEquals("hit", moduleCacheInfo.get("p1/b"));
    assertEquals("hit", moduleCacheInfo.get("p1/hello.txt"));
    assertTrue(result
            .contains(String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/a.js").toURI())));
    assertTrue(result
            .contains(String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/b.js").toURI())));
    assertTrue(result.contains(
            String.format(AggregatorLayerListener.PREAMBLEFMT, new File(tmpdir, "p1/hello.txt").toURI())));
    URI uri = new File(tmpdir, "p1/a.js").toURI();
    NotFoundModule nfm = new NotFoundModule("p1/a.js", uri);
    Reader rdr = nfm.getBuild(mockRequest).get();
    writer = new StringWriter();
    CopyUtil.copy(rdr, writer);
    assertTrue(result.contains(writer.toString()));
    assertTrue(result.contains("\"hello from b.js\""));
    assertTrue(result.contains("Hello world text"));

    // now rename it back
    new File(tmpdir, "p1/a.js.save").renameTo(new File(tmpdir, "p1/a.js"));
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(IHttpTransport.SHOWFILENAMES_REQATTRNAME, Boolean.TRUE);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("[update_keygen, update_key, update_hit]", layerCacheInfo.toString());
    assertEquals("add", moduleCacheInfo.get("p1/a"));
    assertEquals("hit", moduleCacheInfo.get("p1/b"));
    assertEquals("hit", moduleCacheInfo.get("p1/hello.txt"));
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));
    assertEquals(saveResult, result);

    Thread.sleep(1500L); // Wait long enough for systems with coarse grain last-mod
    // times to recognize that the file has changed.
    // Touch a file and make sure the layer is rebuilt
    new File(tmpdir, "p1/b.js").setLastModified(new Date().getTime());
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(IHttpTransport.SHOWFILENAMES_REQATTRNAME, Boolean.TRUE);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[update_lastmod2, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    moduleCacheInfo = (Map<String, String>) requestAttributes.get(IModuleCache.MODULECACHEINFO_PROPNAME);
    assertEquals("hit", moduleCacheInfo.get("p1/a"));
    assertEquals("hit", moduleCacheInfo.get("p1/b"));
    assertEquals("hit", moduleCacheInfo.get("p1/hello.txt"));
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));
    assertEquals(saveResult, result);

    // Delete a layer cache entry from disk and make sure it's rebuilt
    String key = "" + layer.getId() + "-"
            + (String) requestAttributes.get(LayerImpl.LAYERBUILDCACHEKEY_PROPNAME);
    CacheEntry cacheEntry = ((LayerCacheImpl) mockAggregator.getCacheManager().getCache().getLayers())
            .getLayerBuildMap().get(key);
    File file = new File(mockAggregator.getCacheManager().getCacheDir(), cacheEntry.getFilename());
    assertTrue("Error deleting file", file.delete());
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    assertEquals("[hit_1, update_weights_2]", layerCacheInfo.toString());
    assertEquals("weighted size error", totalSize, cacheMap.weightedSize());
    assertEquals("cache file size error", totalSize, TestUtils.getDirListSize(cacheDir, layerFilter));
    assertEquals(saveResult, result);
    // make sure a new file was written out
    file = new File(mockAggregator.getCacheManager().getCacheDir(), cacheEntry.getFilename());
    assertTrue("missing cache file", file.exists());

    // Test required request parameter
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    modules.setModules(Collections.<String>emptyList());
    modules.setDeps(Arrays.asList(new String[] { "p1/a" }));
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    Pattern p = Pattern.compile(new StringBuffer().append("require\\(\\{cache:\\{")
            .append("\\\"p1/a\\\":function\\(\\)\\{.*?\\},").append("\\\"p1/b\\\":function\\(\\)\\{.*?\\},")
            .append("\\\"p1/c\\\":function\\(\\)\\{.*?\\},")
            .append("\\\"p1/noexist\\\":function\\(\\)\\{.*?Module not found: .*?\\}")
            .append("\\}\\}\\);require\\(\\{cache:\\{\\}\\}\\);require\\(\\[\\\"p1/a\\\"\\]\\);").toString());
    assertTrue(p.matcher(result).find());

    // Ensure that package name in require list get's translated to package main module
    requestAttributes.clear();
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    modules.setDeps(Arrays.asList(new String[] { "foo" }));
    in = layer.getInputStream(mockRequest, mockResponse);
    writer = new StringWriter();
    CopyUtil.copy(in, writer);
    result = writer.toString();
    System.out.println(result);
    p = Pattern.compile(new StringBuffer().append("require\\(\\{cache:\\{")
            .append("\\\"foo/main\\\":function\\(\\)\\{.*?Module not found: .*?\\}")
            .append("\\}\\}\\);require\\(\\{cache:\\{\\}\\}\\);require\\(\\[\\\"foo/main\\\"\\]\\);")
            .toString());
    assertTrue(p.matcher(result).find());
}

From source file:com.yahoo.ycsb.db.couchbase2.Couchbase2Client.java

/**
 * Encode the source into a String for storage.
 *
 * @param source the source value./*from  w w w  .ja va2  s . c  o m*/
 * @return the encoded string.
 */
private String encode(final HashMap<String, ByteIterator> source) {
    HashMap<String, String> stringMap = StringByteIterator.getStringMap(source);
    ObjectNode node = JacksonTransformers.MAPPER.createObjectNode();
    for (Map.Entry<String, String> pair : stringMap.entrySet()) {
        node.put(pair.getKey(), pair.getValue());
    }
    JsonFactory jsonFactory = new JsonFactory();
    Writer writer = new StringWriter();
    try {
        JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer);
        JacksonTransformers.MAPPER.writeTree(jsonGenerator, node);
    } catch (Exception e) {
        throw new RuntimeException("Could not encode JSON value");
    }
    return writer.toString();
}

From source file:com.fer.hr.olap.query.OlapQuery.java

public String getMdx() {
    final Writer writer = new StringWriter();
    if (SaikuProperties.olapConvertQuery) {
        try {/* w ww. j ava 2 s.  c  o  m*/
            SelectNode s = QueryConverter.convert(query);
            s.unparse(new ParseTreeWriter(new PrintWriter(writer)));
        } catch (SaikuIncompatibleException se) {
            log.debug("Cannot convert to new query model mdx, falling back to old version", se);
            this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
        } catch (Exception e) {
            throw new SaikuServiceException("Cannot convert to new query model", e);
        }
    } else {
        this.query.getSelect().unparse(new ParseTreeWriter(new PrintWriter(writer)));
    }
    return writer.toString();
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

private String renderSubjectTemplate(String emailTitle, Map<String, Serializable> input) {
    Configuration stringCfg = rh.getEngineConfiguration();
    Writer out;
    try {//from   w  w w.j  a  va  2  s . c  o m
        Template templ = new Template("subjectTemplate", new StringReader(emailTitle), stringCfg);
        out = new StringWriter();
        templ.process(input, out);
        out.flush();
    } catch (IOException | TemplateException e) {
        throw new NuxeoException("Error while rendering email subject: ", e);
    }
    return out.toString();
}

From source file:org.codice.ddf.security.handler.anonymous.AnonymousHandler.java

/**
 * Returns the UsernameToken marshalled as a String so that it can be attached to the
 * {@link org.codice.ddf.security.handler.api.HandlerResult} object.
 *
 * @param usernameTokenType//from  w w w. ja  va  2  s . c  o m
 * @return String
 */
private synchronized String getUsernameTokenElement(UsernameTokenType usernameTokenType) {
    Writer writer = new StringWriter();
    Marshaller marshaller = null;
    if (utContext != null) {
        try {
            marshaller = utContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        } catch (JAXBException e) {
            LOGGER.error("Exception while creating UsernameToken marshaller.", e);
        }

        JAXBElement<UsernameTokenType> usernameTokenElement = new JAXBElement<UsernameTokenType>(
                new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                        "UsernameToken"),
                UsernameTokenType.class, usernameTokenType);

        if (marshaller != null) {
            try {
                marshaller.marshal(usernameTokenElement, writer);
            } catch (JAXBException e) {
                LOGGER.error("Exception while writing username token.", e);
            }
        }
    }

    return writer.toString();
}

From source file:JDBCPool.dbcp.demo.sourcecode.BaseGenericObjectPool.java

/**
 * Gets the stack trace of an exception as a string.
 * @param e exception to trace/*from w  w w  .j  a  v a 2s . c  o m*/
 * @return exception stack trace as a string
 */
private String getStackTrace(Exception e) {
    // Need the exception in string form to prevent the retention of
    // references to classes in the stack trace that could trigger a memory
    // leak in a container environment.
    Writer w = new StringWriter();
    PrintWriter pw = new PrintWriter(w);
    e.printStackTrace(pw);
    return w.toString();
}

From source file:de.shadowhunt.subversion.internal.httpv1.CheckoutOperation.java

@Override
protected HttpUriRequest createRequest() {
    final Writer body = new StringBuilderWriter();
    try {//w ww  .  j a v a2  s . c  o m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("checkout");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("activity-set");
        writer.writeStartElement("href");
        final URI transactionURI = URIUtils.createURI(repository, transaction);
        writer.writeCData(transactionURI.toString());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // activity-set
        writer.writeEmptyElement("apply-to-version");
        writer.writeEndElement(); //checkout
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("CHECKOUT", uri);
    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.live.Live.java

protected void processingDone(final List<Archive> deployedArchives, final Experiment experiment,
        final QcContext context) {
    if (deployedArchives.size() < 1) {
        return; // not sure this will ever happen?
    }/* w  w  w.  ja  va  2 s. c  o  m*/
    final boolean isClinical = isClinical(deployedArchives);

    // create an email for the submitting center, telling them processing is complete
    final StringBuilder centerMailBody = new StringBuilder().append("Processing of your submission for '")
            .append(experiment.getName())
            .append("' has completed successfully.  The following archive(s) were deployed:\n\n");

    for (final Archive archive : deployedArchives) {
        scheduleCleanup(archive, false);
        archive.setDeployStatus(Archive.STATUS_AVAILABLE);
        commonArchiveQueries.updateArchiveStatus(archive);
        commonArchiveQueries.setToLatest(archive);
        diseaseArchiveQueries.updateArchiveStatus(archive);
        diseaseArchiveQueries.setToLatest(archive);

        // append name to center email body
        centerMailBody.append("\t").append(archive.getArchiveName()).append("\n");
        // and send out a "new archive available" email for each deployed archive to everyone
        final String subject = "New Archive Available - " + archive.getArchiveName();
        long archiveSize = commonArchiveQueries.getArchiveSize(archive.getId()) * 1024;
        final String body = new StringBuilder().append("A new archive is available.\n\n")
                .append("Archive Name\t").append(archive.getArchiveName()).append("\n\n")
                .append("Archive Size\t").append(FileUtil.getFormattedFileSize(archiveSize)).append("\n\n")
                .append("Browse Contents\t").append(getServerUrl()).append("/tcga/showFiles.htm?archiveId=")
                .append(archive.getId()).append("\n\n").append("Download\t").append(getServerUrl())
                .append(archive.getDeployLocation().replace('\\', '/')).append("\n\n")
                .append("#This is a tab delimited message").toString();
        if (mailSender.isMailEnabled()) {
            mailSender.send(archive.getTheCenter().getCommaSeparatedEmailList(), emailBcc, subject, body,
                    false);
        } else {
            logger.log(Level.DEBUG, "-- EMAIL --");
            logger.log(Level.DEBUG, "To: " + archive.getTheCenter().getCommaSeparatedEmailList());
            logger.log(Level.DEBUG, "Subject: " + subject);
            logger.log(Level.DEBUG, "Message: ");
            logger.log(Level.DEBUG, body);
        }

        // last step update archiveLog to indicate the archive has completed successfuly
        archiveLogger.endTransaction(archive.getArchiveName(), true);

    }
    // if there were any warnings, append them to the message that goes to the submitting center
    if (context.getWarningCount() > 0) {
        centerMailBody.append("\n\nWarning(s) recorded:\n");
        for (final String warning : context.getWarnings()) {
            centerMailBody.append("- ");
            centerMailBody.append(warning);
            centerMailBody.append("\n\n");
        }
    }
    emailCenter(
            context.getCenterName(), context.getPlatformName(), new StringBuilder().append("Processing of ")
                    .append(experiment.getName()).append(" was successful").toString(),
            centerMailBody.toString());

    if (isClinical) {
        Calendar whenToRun = Calendar.getInstance();
        whenToRun.add(Calendar.MINUTE, clinicalLoaderWaitMinutes);
        // for clinical archives update the archive status after loading the data
        for (final Archive archive : deployedArchives) {
            scheduleCleanup(archive, false);
            archive.setDeployedWarningMessages(context.getWarnings());
        }

        // clinical loader scheduling
        PrintWriter printWriter = null;
        try {
            liveScheduler.scheduleClinicalLoader(deployedArchives, whenToRun, experiment.getName(),
                    context.getStateContext());

        } catch (SchedulerException e) {
            logger.log(Level.ERROR, "Unable to schedule clinical data loading job " + e.getMessage());
            // email the full stack trace
            final Writer result = new StringWriter();
            //noinspection IOResourceOpenedButNotSafelyClosed
            printWriter = new PrintWriter(result);
            e.printStackTrace(printWriter);
            errorMailSender.send("Clinical Loader Error while scheduling clinical loader", result.toString());
            // last step update archiveLog to indicate the archive has completed unsuccessfuly
            archiveLogger.endTransaction(context.getStateContext().getTransactionId(), false);
        } finally {
            IOUtils.closeQuietly(printWriter);
        }
    }
}