Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*from w  ww. j a v  a 2s.  c om*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:org.apache.olingo.client.core.serialization.ODataBinderImpl.java

@Override
public ClientEntitySet getODataEntitySet(final ResWrap<EntityCollection> resource) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        try {//from w  w  w  .  j  a  va2  s. c  o  m
            client.getSerializer(ContentType.JSON).write(writer, resource.getPayload());
        } catch (final ODataSerializerException e) {
            LOG.debug("EntitySet -> ODataEntitySet:\n{}", writer.toString());
        }
        writer.flush();
        LOG.debug("EntitySet -> ODataEntitySet:\n{}", writer.toString());
    }

    final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI()
            : ContextURLParser.parse(resource.getContextURL()).getServiceRoot();

    final URI next = resource.getPayload().getNext();

    final ClientEntitySet entitySet = next == null ? client.getObjectFactory().newEntitySet()
            : client.getObjectFactory().newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getPayload().getCount() != null) {
        entitySet.setCount(resource.getPayload().getCount());
    }

    for (Operation op : resource.getPayload().getOperations()) {
        ClientOperation operation = new ClientOperation();
        operation.setTarget(URIUtils.getURI(base, op.getTarget()));
        operation.setTitle(op.getTitle());
        operation.setMetadataAnchor(op.getMetadataAnchor());
        entitySet.getOperations().add(operation);
    }

    for (Entity entityResource : resource.getPayload().getEntities()) {
        add(entitySet, getODataEntity(
                new ResWrap<Entity>(resource.getContextURL(), resource.getMetadataETag(), entityResource)));
    }

    if (resource.getPayload().getDeltaLink() != null) {
        entitySet.setDeltaLink(URIUtils.getURI(base, resource.getPayload().getDeltaLink()));
    }
    odataAnnotations(resource.getPayload(), entitySet);

    return entitySet;
}

From source file:org.apache.olingo.client.core.serialization.ODataBinderImpl.java

@Override
public ClientEntity getODataEntity(final ResWrap<Entity> resource) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        try {/*from   w w  w  .j  a  v  a  2s  .  c  o m*/
            client.getSerializer(ContentType.JSON).write(writer, resource.getPayload());
        } catch (final ODataSerializerException e) {
            LOG.debug("EntityResource -> ODataEntity:\n{}", writer.toString());
        }
        writer.flush();
        LOG.debug("EntityResource -> ODataEntity:\n{}", writer.toString());
    }

    final ContextURL contextURL = ContextURLParser.parse(resource.getContextURL());
    final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI()
            : contextURL.getServiceRoot();
    final EdmType edmType = findType(resource.getPayload().getType(), contextURL, resource.getMetadataETag());
    FullQualifiedName typeName = null;
    if (resource.getPayload().getType() == null) {
        if (edmType != null) {
            typeName = edmType.getFullQualifiedName();
        }
    } else {
        typeName = new FullQualifiedName(resource.getPayload().getType());
    }

    final ClientEntity entity = resource.getPayload().getSelfLink() == null
            ? client.getObjectFactory().newEntity(typeName)
            : client.getObjectFactory().newEntity(typeName,
                    URIUtils.getURI(base, resource.getPayload().getSelfLink().getHref()));

    if (StringUtils.isNotBlank(resource.getPayload().getETag())) {
        entity.setETag(resource.getPayload().getETag());
    }

    if (resource.getPayload().getEditLink() != null) {
        entity.setEditLink(URIUtils.getURI(base, resource.getPayload().getEditLink().getHref()));
    }

    for (Link link : resource.getPayload().getAssociationLinks()) {
        entity.addLink(client.getObjectFactory().newAssociationLink(link.getTitle(),
                URIUtils.getURI(base, link.getHref())));
    }

    odataNavigationLinks(edmType, resource.getPayload(), entity, resource.getMetadataETag(), base);

    for (Link link : resource.getPayload().getMediaEditLinks()) {
        if (link.getRel().startsWith(Constants.NS_MEDIA_READ_LINK_REL)) {
            entity.addLink(client.getObjectFactory().newMediaReadLink(link.getTitle(),
                    URIUtils.getURI(base, link.getHref()), link.getType(), link.getMediaETag()));
        } else {
            entity.addLink(client.getObjectFactory().newMediaEditLink(link.getTitle(),
                    URIUtils.getURI(base, link.getHref()), link.getType(), link.getMediaETag()));
        }
    }

    for (Operation op : resource.getPayload().getOperations()) {
        ClientOperation operation = new ClientOperation();
        operation.setTarget(URIUtils.getURI(base, op.getTarget()));
        operation.setTitle(op.getTitle());
        operation.setMetadataAnchor(op.getMetadataAnchor());
        entity.getOperations().add(operation);
    }

    if (resource.getPayload().isMediaEntity()) {
        entity.setMediaEntity(true);
        entity.setMediaContentSource(URIUtils.getURI(base, resource.getPayload().getMediaContentSource()));
        entity.setMediaContentType(resource.getPayload().getMediaContentType());
        entity.setMediaETag(resource.getPayload().getMediaETag());
    }

    Map<String, Integer> countMap = new HashMap<String, Integer>();
    for (final Property property : resource.getPayload().getProperties()) {
        EdmType propertyType = null;
        if (edmType instanceof EdmEntityType) {
            EdmElement edmProperty = ((EdmEntityType) edmType).getProperty(property.getName());
            if (edmProperty != null) {
                propertyType = edmProperty.getType();
                if (edmProperty instanceof EdmNavigationProperty && !property.isNull()) {
                    final String propertyTypeName = propertyType.getFullQualifiedName()
                            .getFullQualifiedNameAsString();
                    entity.addLink(createLinkFromNavigationProperty(property, propertyTypeName,
                            countMap.remove(property.getName())));
                    continue;
                }
            } else {
                int idx = property.getName().indexOf(Constants.JSON_COUNT);
                if (idx != -1) {
                    String navigationName = property.getName().substring(0, idx);
                    edmProperty = ((EdmEntityType) edmType).getProperty(navigationName);
                    if (edmProperty != null) {
                        if (edmProperty instanceof EdmNavigationProperty) {
                            ClientLink link = entity.getNavigationLink(navigationName);
                            if (link == null) {
                                countMap.put(navigationName, (Integer) property.getValue());
                            } else {
                                link.asInlineEntitySet().getEntitySet().setCount((Integer) property.getValue());
                            }
                        }
                    }
                }
            }
        }
        add(entity, getODataProperty(propertyType, property));
    }

    if (!countMap.isEmpty()) {
        for (String name : countMap.keySet()) {
            entity.addLink(createLinkFromEmptyNavigationProperty(name, countMap.get(name)));
        }
    }

    entity.setId(resource.getPayload().getId());
    odataAnnotations(resource.getPayload(), entity);

    return entity;
}

From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java

private String network2String(final DirectedGraphToGraphAdapter<String, PhyloEdge<String>> speciesNetwork) {
    Func1<String, String> _getNetworkNodeLabel = new Func1<String, String>() {
        public String execute(String node) {
            return node;
        }/*  w w w.  j  av a 2 s .  c o  m*/
    };

    Func1<String, Iterable<String>> _getDestinationNodes = new Func1<String, Iterable<String>>() {
        public Iterable<String> execute(String node) {
            return new GetDirectSuccessors<String, PhyloEdge<String>>().execute(speciesNetwork, node);
        }
    };

    Func2<String, String, String> _getNetworkDistanceForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getBranchLength() == null) {
                return null;
            }
            return edge.getBranchLength() + "";
        }
    };

    Func2<String, String, String> _getProbabilityForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getProbability() == null) {
                return null;
            }
            return edge.getProbability() + "";
        }
    };

    Func2<String, String, String> _getSupportForPrint = new Func2<String, String, String>() {
        public String execute(String parent, String child) {
            PhyloEdge<String> edge = speciesNetwork.getEdge(parent, child);
            if (edge.getSupport() == null) {
                return null;
            }
            return edge.getSupport() + "";
        }
    };

    Func1<String, HybridNodeType> _getHybridTypeForPrint = new Func1<String, HybridNodeType>() {
        public HybridNodeType execute(String node) {
            int inDegree = new GetInDegree<String, PhyloEdge<String>>().execute(speciesNetwork, node);
            return inDegree == 2 ? HybridNodeType.Hybridization : null;
        }
    };

    Func1<String, String> _getHybridNodeIndexForPrint = new Func1<String, String>() {
        List<String> hybridNodes = new ArrayList<String>();

        public String execute(String node) {
            int inDegree = new GetInDegree<String, PhyloEdge<String>>().execute(speciesNetwork, node);
            if (inDegree == 2) {
                int index = hybridNodes.indexOf(node) + 1;
                if (index == 0) {
                    hybridNodes.add(node);
                    return hybridNodes.size() + "";
                } else {
                    return index + "";
                }
            } else {
                return null;
            }
        }
    };

    try {
        StringWriter sw = new StringWriter();
        //   new RichNewickPrinterCompact<String>().print(true, "R", _getNetworkNodeLabel, _getDestinationNodes, _getNetworkDistanceForPrint, _getSupportForPrint, _getProbabilityForPrint, _getHybridNodeIndexForPrint, _getHybridTypeForPrint, sw);
        RichNewickPrinterCompact<String> printer = new RichNewickPrinterCompact<String>();
        printer.setGetBranchLength(_getNetworkDistanceForPrint);
        printer.setGetProbability(_getProbabilityForPrint);
        printer.setGetSupport(_getSupportForPrint);

        printer.print(true, new FindRoot<String>().execute(speciesNetwork), _getNetworkNodeLabel,
                _getDestinationNodes, _getHybridNodeIndexForPrint, _getHybridTypeForPrint, sw);
        sw.flush();
        sw.close();
        return sw.toString();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.getStackTrace();
    }
    return null;
}

From source file:org.ajax4jsf.context.ViewResources.java

public void processHeadResources(FacesContext context) throws FacesException {

    RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    renderKit = rkFactory.getRenderKit(context, context.getViewRoot().getRenderKitId());

    boolean scriptsOff = false;

    processStyles = true;//from  w w  w.  j a v a2  s  . c  om
    processScripts = true;
    useSkinning = false;

    ajaxRequest = AjaxContext.getCurrentInstance(context).isAjaxRequest(context);

    if (log.isDebugEnabled()) {
        log.debug("Process component tree for collect used scripts and styles");
    }

    String skinStyleSheetUri = null;
    String skinExtendedStyleSheetUri = null;

    Skin skin = null;
    try {
        skin = SkinFactory.getInstance().getSkin(context);
        // For a "NULL" skin, do not collect components stylesheets
        if ("false".equals(skin.getParameter(context, Skin.loadStyleSheets))) {
            processStyles = false;
        }
        // Set default style sheet for current skin.
        skinStyleSheetUri = (String) skin.getParameter(context, Skin.generalStyleSheet);
        // Set default style sheet for current skin.
        skinExtendedStyleSheetUri = (String) skin.getParameter(context, Skin.extendedStyleSheet);
    } catch (SkinNotFoundException e) {
        if (log.isWarnEnabled()) {
            log.warn("Current Skin is not found", e);
        }
    }

    resourceBuilder = InternetResourceBuilder.getInstance();

    ResponseWriter oldResponseWriter = context.getResponseWriter();

    componentWriter = new HeadResponseWriter("component");
    userWriter = new HeadResponseWriter("user");

    try {
        componentWriter.startDocument();
        userWriter.startDocument();

        context.setResponseWriter(componentWriter);

        // Check init parameters for a resources processing.
        if (null != scriptStrategy) {
            if (InternetResourceBuilder.LOAD_NONE.equals(scriptStrategy)) {
                scriptsOff = true;
                processScripts = false;
            } else if (InternetResourceBuilder.LOAD_ALL.equals(scriptStrategy)) {
                processScripts = false;
                // For an "ALL" strategy, it is not necessary to load scripts in the ajax request
                if (!ajaxRequest) {
                    try {
                        resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT)
                                .encode(context, null);
                        resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_UI_SCRIPT)
                                .encode(context, null);

                    } catch (ResourceNotFoundException e) {
                        if (log.isWarnEnabled()) {
                            log.warn("No aggregated javaScript library found " + e.getMessage());
                        }
                    }

                }
            }
        }

        if (InternetResourceBuilder.LOAD_NONE.equals(styleStrategy)) {
            processStyles = false;
        } else if (InternetResourceBuilder.LOAD_ALL.equals(styleStrategy)) {
            processStyles = false;
            // For an "ALL" strategy, it is not necessary to load styles
            // in the ajax request
            if (!ajaxRequest) {

                try {
                    useSkinning = encodeSkinningResources(context, resourceBuilder);

                    resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_STYLE).encode(context,
                            null);

                } catch (ResourceNotFoundException e) {
                    if (log.isWarnEnabled()) {
                        log.warn("No stylesheet found " + e.getMessage());
                    }
                }

            }
        } else {
            useSkinning = encodeSkinningResources(context, resourceBuilder);
        }

        //traverse components
        traverse(context, context.getViewRoot());

        context.setResponseWriter(componentWriter);

        QueueRegistry queueRegistry = QueueRegistry.getInstance(context);
        if (Boolean.valueOf(getInitParameterValue(context, "org.richfaces.queue.global.enabled"))) {
            queueRegistry.setShouldCreateDefaultGlobalQueue();
        }

        if (queueRegistry.hasQueuesToEncode()) {
            InternetResource queueScriptResource = resourceBuilder.getResource(QUEUE_SCRIPT_RESOURCE);
            queueScriptResource.encode(context, null);
        }

        // Append Skin StyleSheet after a
        if (null != skinStyleSheetUri) {
            String resourceURL = context.getApplication().getViewHandler().getResourceURL(context,
                    skinStyleSheetUri);

            URIInternetResource resourceImpl = new URIInternetResource();
            resourceImpl.setUri(resourceURL);
            resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
            resourceImpl.encode(context, null);

            useSkinning = true;
        }

        if (null != skinExtendedStyleSheetUri && extendedSkinningAllowed) {
            String resourceURL = context.getApplication().getViewHandler().getResourceURL(context,
                    skinExtendedStyleSheetUri);

            URIInternetResource resourceImpl = new URIInternetResource();
            resourceImpl.setUri(resourceURL);
            resourceImpl.setRenderer(resourceBuilder.getStyleRenderer());
            resourceImpl.encode(context, null, EXTENDED_SKINNING);

            useSkinning = true;
        }

        if (useSkinning && extendedSkinningAllowed) {
            if (!ajaxRequest) {
                if (!scriptsOff) {
                    //skinning levels aren't dynamic, page-level setting cannot be changed 
                    //by AJAX request
                    EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);
                } else {

                    Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap();
                    if (applicationMap.get(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY) == null) {
                        //do it once per application life - strategies can be changed dynamically
                        ResponseWriter writer = context.getResponseWriter();
                        try {
                            StringWriter stringWriter = new StringWriter();

                            if (oldResponseWriter != null) {
                                context.setResponseWriter(oldResponseWriter.cloneWithWriter(stringWriter));
                            } else {
                                context.setResponseWriter(this.renderKit.createResponseWriter(stringWriter,
                                        "text/html", "US-ASCII"));
                            }

                            EXTENDED_SKINNING_ON_RESOURCE.encode(context, null);

                            stringWriter.flush();

                            if (log.isInfoEnabled()) {
                                log.info(
                                        "Extended skinning is on and NONE scripts loading strategy was detected. "
                                                + "Do not forget that one of "
                                                + InternetResourceBuilder.SKINNING_SCRIPT + " or "
                                                + InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT
                                                + " resources should be presented "
                                                + "on the page together with the following code: \n"
                                                + stringWriter.getBuffer().toString()
                                                + "\nfor extended level of skinning to work.");
                            }
                        } finally {
                            if (writer != null) {
                                context.setResponseWriter(writer);
                            }
                        }

                        applicationMap.put(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY, Boolean.TRUE);
                    }
                }
            }

            if (processScripts) {
                InternetResource resource = resourceBuilder.createResource(null,
                        InternetResourceBuilder.SKINNING_SCRIPT);

                resource.encode(context, null);
            }
        }

        componentWriter.endDocument();
        userWriter.endDocument();
    } catch (IOException e) {
        throw new FacesException(e.getLocalizedMessage(), e);
    } finally {
        if (oldResponseWriter != null) {
            context.setResponseWriter(oldResponseWriter);
        }
    }
}

From source file:com.aimluck.eip.gpdb.util.GpdbUtils.java

/**
 * ??????/*from ww w .ja va  2s . c om*/
 * 
 * @param gpdbItemList
 * 
 * @return
 */
public static String createMsgForPc(RunData rundata, EipTGpdb gpdb, String gpdbItemName, String dispValue,
        Boolean isNew) throws ALDBErrorException {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    ALEipUser loginUser = null;
    ALBaseUser user = null;

    try {
        loginUser = ALEipUtils.getALEipUser(rundata);
        user = (ALBaseUser) JetspeedSecurity.getUser(new UserIdPrincipal(loginUser.getUserId().toString()));
    } catch (Exception e) {
        return "";
    }
    context.put("loginUser", loginUser.getAliasName().toString());
    context.put("hasEmail", !user.getEmail().equals(""));
    context.put("email", user.getEmail());
    context.put("isNew", isNew);
    // 
    context.put("GpdbName", gpdb.getGpdbName());
    // ??
    context.put("GpdbItemName", gpdbItemName);
    context.put("DispValue", dispValue);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/gpdb-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/gpdb-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;
}

From source file:com.moviejukebox.tools.WebBrowser.java

@SuppressWarnings("resource")
public String request(URL url, Charset charset) throws IOException {
    LOG.debug("Requesting {}", url.toString());

    // get the download limit for the host
    ThreadExecutor.enterIO(url);/*from w w  w .j  a  va 2 s .c  om*/
    StringWriter content = new StringWriter(10 * 1024);
    try {

        URLConnection cnx = null;

        try {
            cnx = openProxiedConnection(url);

            sendHeader(cnx);
            readHeader(cnx);

            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;

            try (InputStream inputStream = cnx.getInputStream()) {

                // If we fail to get the URL information we need to exit gracefully
                if (charset == null) {
                    inputStreamReader = new InputStreamReader(inputStream, getCharset(cnx));
                } else {
                    inputStreamReader = new InputStreamReader(inputStream, charset);
                }
                bufferedReader = new BufferedReader(inputStreamReader);

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    content.write(line);
                }

                // Attempt to force close connection
                // We have HTTP connections, so these are always valid
                content.flush();

            } catch (FileNotFoundException ex) {
                LOG.error("URL not found: {}", url.toString());
            } catch (IOException ex) {
                LOG.error("Error getting URL {}, {}", url.toString(), ex.getMessage());
            } finally {
                // Close resources
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (Exception ex) {
                        /* ignore */ }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (Exception ex) {
                        /* ignore */ }
                }
            }
        } catch (SocketTimeoutException ex) {
            LOG.error("Timeout Error with {}", url.toString());
        } finally {
            if (cnx != null) {
                if (cnx instanceof HttpURLConnection) {
                    ((HttpURLConnection) cnx).disconnect();
                }
            }
        }
        return content.toString();
    } finally {
        content.close();
        ThreadExecutor.leaveIO();
    }
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

public synchronized HttpResponse recordResponse(HttpResponse response) {
    try {/*from w w  w .  j  a va 2 s .c o m*/
        StringWriter out = new StringWriter();
        out.write("\n<response ");

        out.write("statusCode=\"");
        int statusCode = response.getStatusLine().getStatusCode();
        out.write(String.valueOf(statusCode).trim());
        out.write("\" ");
        out.write("statusReason=\"");
        String reasonPhrase = response.getStatusLine().getReasonPhrase();
        out.write(String.valueOf(reasonPhrase).trim());
        out.write("\">\n");
        out.write("<headers>");
        Header[] allHeaders = response.getAllHeaders();
        out.write(serialize(allHeaders));
        String serializedEntity = null;
        if (response.getEntity() != null) {
            out.write("</headers>\n<data><![CDATA[");
            serializedEntity = serialize(response.getEntity().getContent());
            serializedEntity = serializedEntity.replaceAll("<!\\[CDATA\\[", "\\!\\[CDATA\\[")
                    .replaceAll("\\]\\]>", "\\]\\]");
            out.write(serializedEntity);
            out.write("]]></data>\n</response>");
        } else {
            out.write("</headers>\n</response>");
        }
        out.flush();
        out.close();
        writeData(out.toString());

        return buildResponse(allHeaders, statusCode, reasonPhrase, serializedEntity);

    } catch (IOException e) {
        throw new UnsupportedOperationException(e);
    }
}

From source file:de.tu_dortmund.ub.data.dswarm.Init.java

/**
 * creates a data model from given resource + configuration JSON (+ optional input schema)
 *
 * @param resourceJSON/*from   www . j  ava 2s . c om*/
 * @param configurationJSON
 * @param optionalInputSchema
 * @param name
 * @param description
 * @return responseJson
 * @throws Exception
 */
private String createDataModel(final JsonObject resourceJSON, final JsonObject configurationJSON,
        final Optional<JsonObject> optionalInputSchema, final String name, final String description,
        final String serviceName, final String engineDswarmAPI, final boolean doIngest) throws Exception {

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.QUESTION_MARK
                + DswarmBackendStatics.DO_DATA_MODEL_INGEST_IDENTIFIER + APIStatics.EQUALS + doIngest;

        final HttpPost httpPost = new HttpPost(uri);

        final StringWriter stringWriter = new StringWriter();
        final JsonGenerator jp = Json.createGenerator(stringWriter);

        jp.writeStartObject();
        jp.write(DswarmBackendStatics.NAME_IDENTIFIER, name);
        jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, description);
        jp.write(CONFIGURATION_IDENTIFIER, configurationJSON);
        jp.write(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER, resourceJSON);

        if (optionalInputSchema.isPresent()) {

            LOG.info("[{}][{}] add existing input schema to input data model", serviceName, cnt);

            jp.write(DswarmBackendStatics.SCHEMA_IDENTIFIER, optionalInputSchema.get());
        }

        jp.writeEnd();

        jp.flush();
        jp.close();

        final StringEntity reqEntity = new StringEntity(stringWriter.toString(),
                ContentType.create(APIStatics.APPLICATION_JSON_MIMETYPE, Consts.UTF_8));

        stringWriter.flush();
        stringWriter.close();

        httpPost.setEntity(reqEntity);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();

            final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                    httpResponse.getStatusLine().getReasonPhrase());

            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 201: {

                LOG.info(message);

                LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, response));

                return response;
            }
            default: {

                LOG.error(message);

                throw new Exception("something went wrong at data model creation: " + message + " " + response);
            }
            }
        }
    }
}

From source file:org.multicore_association.measure.cycle.generate.CodeGen.java

/**
 * Header generating process.//from  ww  w .j  a  v a  2s  . c  om
 * @param funcNameList list of the functions output for header file
 * @param fileName generated file name
 * @return
 */
private boolean dumpCHeader(List<String> funcNameList, String fileName) {

    Properties p = new Properties();
    p.setProperty("resource.loader", "class");
    p.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    p.setProperty("input.encoding", "UTF-8");

    Velocity.init(p);
    Velocity.setProperty("file.resource.loader.path", "/");
    VelocityContext context = new VelocityContext();
    context.put(VLT_KEY_FUNC_NAME_LIST, funcNameList);
    context.put(VLT_KEY_TIMESTAMP, timestamp);
    StringWriter writer = new StringWriter();

    Template template = Velocity.getTemplate(VLT_HEADER_TEMPLATE_NAME);

    template.merge(context, writer);

    File file;
    if (param.getDestDir() != null && !param.getDestDir().equals("")) {
        file = new File(param.getDestDir(), fileName);
    } else {
        file = new File(fileName);
    }

    OutputStream os = null;
    Writer wr = null;
    BufferedWriter bwr = null;
    try {
        os = new FileOutputStream(file);
        wr = new OutputStreamWriter(os, "UTF-8");
        bwr = new BufferedWriter(wr);
        bwr.write(writer.toString());
        bwr.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (bwr != null)
            try {
                bwr.close();
            } catch (IOException e) {
            }
        if (wr != null)
            try {
                wr.close();
            } catch (IOException e) {
            }
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
            }
    }

    writer.flush();

    return true;
}