Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:net.ymate.framework.core.util.WebUtils.java

/**
 * @param request         HttpServletRequest
 * @param response        HttpServletResponse
 * @param jspFile         JSP/*from w  w w  .ja  v a2 s .  com*/
 * @param charsetEncoding ?
 * @return JSPHTML??
 * @throws ServletException ?
 * @throws IOException      ?
 */
public static String includeJSP(HttpServletRequest request, HttpServletResponse response, String jspFile,
        String charsetEncoding) throws ServletException, IOException {
    final OutputStream _output = new ByteArrayOutputStream();
    final PrintWriter _writer = new PrintWriter(new OutputStreamWriter(_output));
    final ServletOutputStream _servletOutput = new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            _output.write(b);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            _output.write(b, off, len);
        }
    };
    HttpServletResponse _response = new HttpServletResponseWrapper(response) {
        @Override
        public ServletOutputStream getOutputStream() {
            return _servletOutput;
        }

        @Override
        public PrintWriter getWriter() {
            return _writer;
        }
    };
    charsetEncoding = StringUtils.defaultIfEmpty(charsetEncoding, response.getCharacterEncoding());
    _response.setCharacterEncoding(StringUtils.defaultIfEmpty(charsetEncoding,
            WebMVC.get().getModuleCfg().getDefaultCharsetEncoding()));
    request.getRequestDispatcher(jspFile).include(request, _response);
    _writer.flush();
    return _output.toString();
}

From source file:org.saiku.adhoc.rest.StandaloneCdaResource.java

@GET
@Produces({ "application/xml" })
@Path("/listParameters")
public String listParameters(@QueryParam("outputType") String outputType,
        @QueryParam("solution") String solution, @QueryParam("path") String path,
        @QueryParam("file") String file, @QueryParam("dataAccessId") String dataAccessId) {

    final IParameterProvider pathParams = null;
    final OutputStream out = new ByteArrayOutputStream();

    Map<String, Object> params = new HashMap<String, Object>();

    params.put("path", path);
    params.put("solution", "");
    params.put("dataAccessId", dataAccessId);
    params.put("outputType", outputType);
    params.put("file", file);
    IParameterProvider requestParams = new SimpleParameterProvider(params);

    try {//from   w  w  w .  j ava  2  s  .com
        listParameters(requestParams, out);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return out.toString();

}

From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java

/**
 * //from   w  w w. j  a  v a2  s .  c om
 * @param username : 
 * @param calendarId
 * @param type
 * @param eventId
 * @return Icalendar data
 * @throws Exception
 */
@GET
//@Produces("text/calendar")
@Path("/subscribe/{username}/{calendarId}/{type}")
public Response publicProcess(@PathParam("username") String username,
        @PathParam("calendarId") String calendarId, @PathParam("type") String type) throws Exception {
    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    cacheControl.setNoStore(true);
    try {
        CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer()
                .getComponentInstanceOfType(CalendarService.class);
        Calendar calendar = null;
        if (type.equals(Utils.PRIVATE_TYPE + "")) {
            calendar = calService.getUserCalendar(username, calendarId);
        } else if (type.equals(Utils.SHARED_TYPE + "")) {
            try {
                calendar = calService.getSharedCalendars(username, false).getCalendarById(calendarId);
            } catch (NullPointerException ex) {
            }
        } else {
            try {
                calendar = calService.getGroupCalendar(calendarId);
            } catch (PathNotFoundException ex) {
            }
        }
        if ((calendar == null) || Utils.isEmpty(calendar.getPublicUrl())) {
            return Response.status(HTTPStatus.LOCKED).entity("Calendar " + calendarId + " is not public access")
                    .cacheControl(cacheControl).build();
        }

        CalendarImportExport icalEx = calService.getCalendarImportExports(CalendarService.ICALENDAR);
        OutputStream out = icalEx.exportCalendar(username, Arrays.asList(calendarId), type, -1);
        InputStream in = new ByteArrayInputStream(out.toString().getBytes());
        return Response.ok(in, "text/calendar").header("Cache-Control", "private max-age=600, s-maxage=120")
                .header("Content-Disposition", "attachment;filename=\"" + calendarId + ".ics")
                .cacheControl(cacheControl).build();
    } catch (NullPointerException ne) {
        return Response.ok(null, "text/calendar").header("Cache-Control", "private max-age=600, s-maxage=120")
                .header("Content-Disposition", "attachment;filename=\"" + calendarId + ".ics")
                .cacheControl(cacheControl).build();
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e.getMessage());
        return Response.status(HTTPStatus.INTERNAL_ERROR).entity(e).cacheControl(cacheControl).build();
    }
}

From source file:com.comcast.cmb.test.tools.CNSTestingUtils.java

public static String doGetSubscriptionAttributes(CNSControllerServlet cns, User user, OutputStream out,
        String subscriptionArn) throws Exception {
    SimpleHttpServletRequest request = new SimpleHttpServletRequest();
    Map<String, String[]> params = new HashMap<String, String[]>();

    addParam(params, "Action", "GetSubscriptionAttributes");
    if (subscriptionArn != null) {
        addParam(params, "SubscriptionArn", subscriptionArn);
    }/*from w  w w  .ja va  2s  . c o  m*/

    addParam(params, "AWSAccessKeyId", user.getAccessKey());

    request.setParameterMap(params);
    ((SimpleHttpServletRequest) request).setParameterMap(params);
    SimpleHttpServletResponse response = new SimpleHttpServletResponse();
    response.setOutputStream(out);

    cns.doGet(request, response);
    response.getWriter().flush();

    return out.toString();
}

From source file:org.jenkinsci.plugins.drupal.beans.DrushInvocation.java

/**
 * Return true if the site is already installed, false otherwise.
 *///from   w  w w . j a v a 2s .  c  o  m
public boolean status() {
    ArgumentListBuilder args = getArgumentListBuilder();
    args.add("status").add("--format=json");

    OutputStream json = new ByteArrayOutputStream();
    try {
        execute(args, new StreamTaskListener(json));
    } catch (IOException e1) {
        listener.getLogger().println(e1);
        return false;
    } catch (InterruptedException e2) {
        listener.getLogger().println(e2);
        return false;
    }

    JSONObject values = (JSONObject) JSONValue.parse(json.toString());
    if (values == null) {
        listener.getLogger().println("[DRUPAL] Could not determine the site status.");
        return false;
    }

    return values.containsKey("db-name");
}

From source file:org.kalypsodeegree_impl.io.sax.test.MarshallEnvelopeTest.java

@Test
public void writeEnvelope() throws IOException, SAXException {
    /* Output: to stream */
    final OutputStream os = new ByteArrayOutputStream();

    final XMLReader reader = SaxParserTestUtils.createXMLReader(os);

    /* Test data */
    final GM_Position lower = GeometryFactory.createGM_Position(1.0, 2.0);
    final GM_Position upper = GeometryFactory.createGM_Position(3.0, 4.0);
    final GM_Envelope expected = GeometryFactory.createGM_Envelope(lower, upper, "EPSG:31467");

    final EnvelopeMarshaller marshaller = new EnvelopeMarshaller(reader);
    SaxParserTestUtils.marshallDocument(reader, marshaller, expected);
    os.close();//from   w ww .ja  v  a  2s  .  c o m

    final URL url = getClass().getResource("/etc/test/resources/envelope_marshall.gml");
    final String actualContent = os.toString();

    SaxParserTestUtils.assertContentEquals(url, actualContent);
}

From source file:org.ebayopensource.turmeric.eclipse.services.ui.actions.GenerateConfigs.java

public void run(final IAction action) {
    if (SOALogger.DEBUG)
        logger.entering(action, selection);
    try {/*from  www . j a  va  2  s. c o  m*/
        if (selection == null)
            return;

        final IProject project = ActionUtil.preValidateAction(selection.getFirstElement(), logger);
        if (project == null)
            return;

        final IStatus status = new AbstractBaseAccessValidator() {

            @Override
            public List<IResource> getReadableFiles() {
                final List<IResource> result = new ArrayList<IResource>();
                return result;
            }

            @Override
            public List<IResource> getWritableFiles() {
                //we should ensure that the client config folder is writable
                final List<IResource> result = new ArrayList<IResource>();
                result.add(project.getFolder(SOAConsumerProject.META_SRC_ClIENT_CONFIG));
                return result;
            }
        }.validate(project.getName());

        final String messages = ValidateUtil.getFormattedStatusMessagesForAction(status);
        if (messages != null) {
            UIUtil.showErrorDialog(UIUtil.getActiveShell(), "Error", messages, (Throwable) null);
            return;
        }
        WorkspaceJob buildJob = new WorkspaceJob("Generating Configs for" + project.getName()) {
            public boolean belongsTo(Object family) {
                return false;
            }

            public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
                try {
                    monitor.beginTask(getName(), ProgressUtil.PROGRESS_STEP * 5);
                    if (ActionUtil.generateConfigs(project, monitor).isOK()) {
                        //set support_zero_config to false
                        IFile file = SOAConsumerUtil.getConsumerPropertiesFile(project);
                        if (file.isAccessible()) {
                            Properties props = new Properties();
                            InputStream input = null;
                            OutputStream output = null;
                            try {
                                input = file.getContents();
                                props.load(input);
                                props.setProperty(SOAProjectConstants.PROPS_SUPPORT_ZERO_CONFIG,
                                        Boolean.FALSE.toString());
                                output = new ByteArrayOutputStream();
                                props.store(output, SOAProjectConstants.PROPS_COMMENTS);
                                WorkspaceUtil.writeToFile(output.toString(), file, monitor);
                            } finally {
                                IOUtils.closeQuietly(input);
                                IOUtils.closeQuietly(output);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);
                    throw new SOAActionExecutionFailedException(e);
                } finally {
                    monitor.done();
                    WorkspaceUtil.refresh(monitor, project);
                }
                return Status.OK_STATUS;
            }
        };
        buildJob.setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(project));
        GlobalRepositorySystem.instanceOf().getActiveRepositorySystem()
                .trackingUsage(new TrackingEvent(getClass().getName(), TrackingEvent.TRACKING_ACTION));
        UIUtil.runJobInUIDialog(buildJob).schedule();

    } catch (Exception e) {
        logger.error(e);
        UIUtil.showErrorDialog(e);
    } finally {
        if (SOALogger.DEBUG)
            logger.exiting();
    }
}

From source file:org.wso2.carbon.core.persistence.AbstractPersistenceManager.java

private String prettyPrintXml(OMElement xml) throws PersistenceException {
    if (xml == null) {
        return null;
    }/*  w  ww  .  j  a  va 2 s.  c  o  m*/
    try {
        OutputStream baos = new ByteArrayOutputStream();
        XMLPrettyPrinter.prettify(xml, baos);
        return baos.toString();
    } catch (Exception e) {
        throw new PersistenceException("error while comparing service parameter content.", e);
    }
}

From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java

/**
 * {@inheritDoc}/*from   ww  w  . j  a v  a 2s  .  c o m*/
 */
public void addOrUpdateAxisClientService(String serviceName, Map<String, String> parameters)
        throws SAXException, IOException {

    createAxisClientConfigFile();
    String axisClientPath = getAxisClientConfigPath();
    Document document = XmlUtils.getDocumentBuilder().parse(new File(axisClientPath));

    Element deployment = (Element) document.getFirstChild();

    Element serviceElementDescriptor = getAxisClientService(document, serviceName, parameters);

    List<Element> previousServices = XmlUtils
            .findElements("/deployment/service[@name='".concat(serviceName).concat("']"), deployment);

    if (previousServices.isEmpty()) {
        deployment.appendChild(serviceElementDescriptor);
    } else {
        deployment.replaceChild(serviceElementDescriptor, previousServices.get(0));
    }

    OutputStream outputStream = new ByteArrayOutputStream();

    Transformer transformer = XmlUtils.createIndentingTransformer();

    XmlUtils.writeXml(transformer, outputStream, document);

    fileManager.createOrUpdateTextFileIfRequired(axisClientPath, outputStream.toString(), false);

}

From source file:org.nuxeo.theme.html.servlets.Resources.java

protected void doProcess(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return;/*from  w  w w. j a  v a 2  s.  c o  m*/
    }
    final Matcher m = pathPattern.matcher(pathInfo);
    if (!m.matches()) {
        log.error(String.format("Invalid resource path: %s", pathInfo));
        return;
    }

    final TypeRegistry typeRegistry = Manager.getTypeRegistry();
    final ThemeManager themeManager = Manager.getThemeManager();

    String contentType = null;
    String resourceSuffix = null;
    final List<String> resourceNames = Arrays.asList(m.group(1).split(","));
    for (String resourceName : resourceNames) {
        String previousContentType = contentType;
        if (resourceName.endsWith(".js")) {
            contentType = "text/javascript";
            resourceSuffix = ".js";
        } else if (resourceName.endsWith(".css")) {
            contentType = "text/css";
            resourceSuffix = ".css";
        } else if (resourceName.endsWith(".json")) {
            contentType = "text/json";
            resourceSuffix = ".json";
        }

        if (contentType == null) {
            log.error("Resource names must end with .js, .css or .json: " + pathInfo);
            return;
        }

        if (previousContentType != null && !contentType.equals(previousContentType)) {
            log.error("Combined resources must be of the same type: " + pathInfo);
            return;
        }
    }
    response.addHeader("content-type", contentType);

    // cache control
    final String applicationPath = request.getParameter("path");
    if (applicationPath != null) {
        ApplicationType application = (ApplicationType) Manager.getTypeRegistry().lookup(TypeFamily.APPLICATION,
                applicationPath);
        if (application != null) {
            Utils.setCacheHeaders(response, application.getResourceCaching());
        }
    }

    StringBuilder text = new StringBuilder();
    String basePath = request.getParameter("basepath");

    // plug additional resources for this page
    List<String> allResourceNames = new ArrayList<String>();
    allResourceNames.addAll(themeManager.getOrderedResourcesAndDeps(resourceNames));
    for (String resourceName : allResourceNames) {
        if (!resourceName.endsWith(resourceSuffix)) {
            continue;
        }
        final OutputStream out = new ByteArrayOutputStream();
        String source = themeManager.getResource(resourceName);
        if (source == null) {
            ResourceType resource = (ResourceType) typeRegistry.lookup(TypeFamily.RESOURCE, resourceName);
            if (resource == null) {
                log.error(String.format("Resource not registered %s.", resourceName));
                continue;
            }
            writeResource(resource, out);
            source = out.toString();

            if (resourceName.endsWith(".js")) {
                // do not shrink the script when Dev mode is enabled
                if (resource.isShrinkable() && !Framework.isDevModeSet()) {
                    try {
                        source = JSUtils.compressSource(source);
                    } catch (ThemeException e) {
                        log.warn("failed to compress javascript source: " + resourceName);
                    }
                }
            } else if (resourceName.endsWith(".css")) {
                // fix CSS url(...) declarations;
                String cssContextPath = resource.getContextPath();
                if (cssContextPath != null) {
                    source = CSSUtils.expandPartialUrls(source, cssContextPath);
                }

                // expands system variables
                source = Framework.expandVars(source);

                // expand ${basePath}
                source = source.replaceAll("\\$\\{basePath\\}", Matcher.quoteReplacement(basePath));
                // also expand ${org.nuxeo.ecm.contextPath}
                source = source.replaceAll("\\$\\{org.nuxeo.ecm.contextPath\\}",
                        Matcher.quoteReplacement(basePath));

                // do not shrink the CSS when Dev mode is enabled
                if (resource.isShrinkable() && !Framework.isDevModeSet()) {
                    try {
                        source = CSSUtils.compressSource(source);
                    } catch (ThemeException e) {
                        log.warn("failed to compress CSS source: " + resourceName);
                    }
                }
            }
            // do not cache the resource when Dev mode is enabled
            if (!Framework.isDevModeSet()) {
                themeManager.setResource(resourceName, source);
            }
        }
        text.append(source);
        if (out != null) {
            out.close();
        }
    }

    boolean supportsGzip = Utils.supportsGzip(request);
    OutputStream os = response.getOutputStream();
    BufferingServletOutputStream.stopBuffering(os);
    if (supportsGzip) {
        response.setHeader("Content-Encoding", "gzip");
        // Needed by proxy servers
        response.setHeader("Vary", "Accept-Encoding");
        os = new GZIPOutputStream(os);
    }

    try {
        os.write(text.toString().getBytes());
        os.close();
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && "Broken pipe".equals(cause.getMessage())) {
            log.debug("Swallowing: " + e);
        } else {
            throw e;
        }
    }

    log.debug(
            String.format("Served resource(s): %s %s", pathInfo, supportsGzip ? "with gzip compression" : ""));
}