Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java

/**
 * //from www .  j  av  a 2 s.  com
 * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String)
 */
public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig,
        RegressionTestType regressionConfig, String delimiter, String printOutputType)
        throws CompositeException {
    // Set the command and action name
    String command = "executeWs";
    String actionName = "REGRESSION_TEST";

    // Check the input parameter values:
    if (cisServerConfig == null || regressionConfig == null) {
        throw new CompositeException(
                "XML Configuration objects are not initialized when trying to run Regression test.");
    }

    URLConnection urlConn = null;
    BufferedReader rd = null;
    OutputStreamWriter wr = null;
    int rows = 0;
    String host = cisServerConfig.getHostname();
    int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port
    boolean useHttps = cisServerConfig.isUseHttps();

    // Execute the webservice
    try {
        // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
        if (CommonUtils.isExecOperation()) {
            boolean encrypt = item.encrypt;
            // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting.
            if (useHttps && !encrypt) {
                encrypt = true;
                RegressionManagerUtils.printOutputStr(printOutputType, "summary",
                        "The regression input file encrypt=false has been overridden by useHttps=true for path="
                                + item.path,
                        "");
            }

            String urlString = "http://" + host + ":" + wsPort + item.path;
            if (encrypt) {
                urlString = "https://" + host + ":" + (wsPort + 2) + item.path;
            }
            RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, "");
            URL url = new URL(urlString);
            urlConn = url.openConnection();
            if (encrypt) {
                // disable hostname verification
                ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                });

            }
            // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users
            String credentials = cisServerConfig.getUser() + ":"
                    + CommonUtils.decrypt(cisServerConfig.getPassword());
            String encoded = Base64EncodeDecode.encodeString(credentials);
            urlConn.setRequestProperty("Authorization", "Basic " + encoded);

            urlConn.setRequestProperty("SOAPAction", item.action);
            urlConn.setRequestProperty("Content-Type", item.contentType);
            urlConn.setDoOutput(true);

            wr = new OutputStreamWriter(urlConn.getOutputStream());
            wr.write(item.input);
            wr.flush();

            // Get the response
            rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String line;
            StringBuffer buf = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                rows++;
                buf.append(line);
                if (outputFile != null)
                    CommonUtils.appendContentToFile(outputFile, line);
            }
            line = buf.toString();
            RegressionManagerUtils.printOutputStr(printOutputType, "results", line, "");
            if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) {
                if (rd != null) {
                    rd.close();
                }
                if (wr != null) {
                    wr.close();
                }
                throw new IllegalStateException("Fault encountered.");
            }
            if (line.trim().length() == 0) {
                if (rd != null) {
                    rd.close();
                }
                if (wr != null) {
                    wr.close();
                }
                throw new IllegalStateException("No response document.");
            }
            urlConn.getInputStream().close();
            //              urlConn.getOutputStream().flush();
            wr.close();
            rd.close();
            RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", "");
        } else {
            logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                    + "] WAS NOT PERFORMED.\n");
        }

        return rows;
    } catch (IOException e) {
        try {
            HttpURLConnection httpConn = (HttpURLConnection) urlConn;
            BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
            String line;
            StringBuffer buf = new StringBuffer();
            while ((line = brd.readLine()) != null) {
                buf.append(line + "\n");
            }
            brd.close();
            String error = buf.toString();
            throw new ApplicationException("executeWs(): " + error, e);

        } catch (Exception err) {
            String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]";
            //debug:               System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************");
            throw new ApplicationException("executeWs(): " + error, err);
        }
    } finally {
        try {
            if (rd != null) {
                rd.close();
            }
            if (wr != null) {
                wr.close();
            }
        } catch (Exception e) {
            rd = null;
            wr = null;
            throw new CompositeException(
                    "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): "
                            + e.getMessage());
        }
    }
}

From source file:org.apache.olingo.fit.Services.java

@DELETE
@Path("/Accounts({entityId})/{containedEntitySetName}({containedEntityId})")
public Response removeContainedEntity(@PathParam("entityId") final String entityId,
        @PathParam("containedEntitySetName") final String containedEntitySetName,
        @PathParam("containedEntityId") final String containedEntityId) {

    try {/*from  w ww.  j  a v  a2 s. com*/
        // 1. Fetch the contained entity to be removed
        final InputStream entry = FSManager.instance().readFile(containedPath(entityId, containedEntitySetName)
                .append('(').append(containedEntityId).append(')').toString(), Accept.ATOM);
        final ResWrap<Entity> container = atomDeserializer.toEntity(entry);

        // 2. Remove the contained entity
        final String atomEntryRelativePath = containedPath(entityId, containedEntitySetName).append('(')
                .append(containedEntityId).append(')').toString();
        FSManager.instance().deleteFile(atomEntryRelativePath);

        // 3. Update the contained entity set
        final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString();
        final InputStream feedIS = FSManager.instance().readFile(atomFeedRelativePath, Accept.ATOM);
        final ResWrap<EntityCollection> feedContainer = atomDeserializer.toEntitySet(feedIS);
        feedContainer.getPayload().getEntities().remove(container.getPayload());

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, feedContainer);
        writer.flush();
        writer.close();

        FSManager.instance().putInMemory(new ByteArrayInputStream(content.toByteArray()),
                FSManager.instance().getAbsolutePath(atomFeedRelativePath, Accept.ATOM));

        return xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT);
    } catch (Exception e) {
        return xml.createFaultResponse(Accept.XML.toString(), e);
    }
}

From source file:org.apache.olingo.fit.Services.java

@POST
@Path("/Accounts({entityId})/{containedEntitySetName:.*}")
public Response postContainedEntity(@Context final UriInfo uriInfo,
        @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
        @PathParam("entityId") final String entityId,
        @PathParam("containedEntitySetName") final String containedEntitySetName, final String entity) {

    try {/*from   w w w .  j  a  v a 2 s . c o m*/
        final Accept acceptType = Accept.parse(accept);
        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final AbstractUtilities utils = getUtilities(acceptType);

        // 1. parse the entry (from Atom or JSON)
        final ResWrap<Entity> entryContainer;
        final Entity entry;
        final Accept contentTypeValue = Accept.parse(contentType);
        if (Accept.ATOM == contentTypeValue) {
            entryContainer = atomDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING));
            entry = entryContainer.getPayload();
        } else {
            final ResWrap<Entity> jcontainer = jsonDeserializer
                    .toEntity(IOUtils.toInputStream(entity, Constants.ENCODING));
            entry = jcontainer.getPayload();

            entryContainer = new ResWrap<Entity>(jcontainer.getContextURL(), jcontainer.getMetadataETag(),
                    entry);
        }

        final EdmTypeInfo contained = new EdmTypeInfo.Builder()
                .setTypeExpression(
                        metadata.getNavigationProperties("Accounts").get(containedEntitySetName).getType())
                .build();
        final String entityKey = getUtilities(contentTypeValue)
                .getDefaultEntryKey(contained.getFullQualifiedName().getName(), entry);

        // 2. Store the new entity
        final String atomEntryRelativePath = containedPath(entityId, containedEntitySetName).append('(')
                .append(entityKey).append(')').toString();
        FSManager.instance().putInMemory(utils.writeEntity(Accept.ATOM, entryContainer),
                FSManager.instance().getAbsolutePath(atomEntryRelativePath, Accept.ATOM));

        // 3. Update the contained entity set
        final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString();
        final InputStream feedIS = FSManager.instance().readFile(atomFeedRelativePath, Accept.ATOM);
        final ResWrap<EntityCollection> feedContainer = atomDeserializer.toEntitySet(feedIS);
        feedContainer.getPayload().getEntities().add(entry);

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, feedContainer);
        writer.flush();
        writer.close();

        FSManager.instance().putInMemory(new ByteArrayInputStream(content.toByteArray()),
                FSManager.instance().getAbsolutePath(atomFeedRelativePath, Accept.ATOM));

        // Finally, return
        return utils.createResponse(uriInfo.getRequestUri().toASCIIString() + "(" + entityKey + ")",
                utils.writeEntity(acceptType, entryContainer), null, acceptType, Response.Status.CREATED);
    } catch (Exception e) {
        LOG.error("While creating new contained entity", e);
        return xml.createFaultResponse(accept, e);
    }
}

From source file:org.apache.olingo.fit.Services.java

private Response patchEntityInternal(final UriInfo uriInfo, final String accept, final String contentType,
        final String prefer, final String ifMatch, final String entitySetName, final String entityId,
        final String changes) {

    try {//ww w .j  av  a  2 s  .c  o  m
        final Accept acceptType = Accept.parse(accept);

        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final Map.Entry<String, InputStream> entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM);

        final String etag = Commons.getETag(entityInfo.getKey());
        if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
            throw new ConcurrentModificationException("Concurrent modification");
        }

        final Accept contentTypeValue = Accept.parse(contentType);

        final Entity entryChanges;

        if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        } else if (contentTypeValue == Accept.ATOM) {
            entryChanges = atomDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING))
                    .getPayload();
        } else {
            final ResWrap<Entity> jcont = jsonDeserializer
                    .toEntity(IOUtils.toInputStream(changes, Constants.ENCODING));
            entryChanges = jcont.getPayload();
        }

        final ResWrap<Entity> container = atomDeserializer.toEntity(entityInfo.getValue());

        for (Property property : entryChanges.getProperties()) {
            final Property _property = container.getPayload().getProperty(property.getName());
            if (_property == null) {
                container.getPayload().getProperties().add(property);
            } else {
                _property.setValue(property.getValueType(), property.getValue());
            }
        }

        for (Link link : entryChanges.getNavigationLinks()) {
            container.getPayload().getNavigationLinks().add(link);
        }

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, container);
        writer.flush();
        writer.close();

        final InputStream res = xml.addOrReplaceEntity(entityId, entitySetName,
                new ByteArrayInputStream(content.toByteArray()), container.getPayload());

        final ResWrap<Entity> cres = atomDeserializer.toEntity(res);

        normalizeAtomEntry(cres.getPayload(), entitySetName, entityId);

        final String path = Commons.getEntityBasePath(entitySetName, entityId);
        FSManager.instance().putInMemory(cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY));

        final Response response;
        if ("return-content".equalsIgnoreCase(prefer)) {
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(),
                    xml.readEntity(entitySetName, entityId, acceptType).getValue(), null, acceptType,
                    Response.Status.OK);
        } else {
            res.close();
            response = xml.createResponse(uriInfo.getRequestUri().toASCIIString(), null, null, acceptType,
                    Response.Status.NO_CONTENT);
        }

        if (StringUtils.isNotBlank(prefer)) {
            response.getHeaders().put("Preference-Applied", Collections.<Object>singletonList(prefer));
        }

        return response;
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

From source file:org.apache.olingo.fit.Services.java

@POST
@Path("/{entitySetName}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM })
public Response postNewEntity(@Context final UriInfo uriInfo,
        @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType,
        @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer,
        @PathParam("entitySetName") final String entitySetName, final String entity) {

    try {//from w  ww .  j av a  2 s .  co m
        final Accept acceptType = Accept.parse(accept);
        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final ResWrap<Entity> container;

        final org.apache.olingo.fit.metadata.EntitySet entitySet = metadata.getEntitySet(entitySetName);

        final Entity entry;
        final String entityKey;
        if (xml.isMediaContent(entitySetName)) {
            entry = new Entity();
            entry.setMediaContentType(ContentType.APPLICATION_OCTET_STREAM.toContentTypeString());
            entry.setType(entitySet.getType());

            entityKey = xml.getDefaultEntryKey(entitySetName, entry);

            xml.addMediaEntityValue(entitySetName, entityKey,
                    IOUtils.toInputStream(entity, Constants.ENCODING));

            final Pair<String, EdmPrimitiveTypeKind> id = Commons.getMediaContent().get(entitySetName);
            if (id != null) {
                final Property prop = new Property();
                prop.setName(id.getKey());
                prop.setType(id.getValue().toString());
                prop.setValue(ValueType.PRIMITIVE, id.getValue() == EdmPrimitiveTypeKind.Int32
                        ? Integer.parseInt(entityKey)
                        : id.getValue() == EdmPrimitiveTypeKind.Guid ? UUID.fromString(entityKey) : entityKey);
                entry.getProperties().add(prop);
            }

            final Link editLink = new Link();
            editLink.setHref(Commons.getEntityURI(entitySetName, entityKey));
            editLink.setRel("edit");
            editLink.setTitle(entitySetName);
            entry.setEditLink(editLink);

            entry.setMediaContentSource(URI.create(editLink.getHref() + "/$value"));

            container = new ResWrap<Entity>((URI) null, null, entry);
        } else {
            final Accept contentTypeValue = Accept.parse(contentType);
            if (Accept.ATOM == contentTypeValue) {
                container = atomDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING));
            } else {
                container = jsonDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING));
            }
            entry = container.getPayload();
            updateInlineEntities(entry);

            entityKey = xml.getDefaultEntryKey(entitySetName, entry);
        }

        normalizeAtomEntry(entry, entitySetName, entityKey);

        final ByteArrayOutputStream content = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);
        atomSerializer.write(writer, container);
        writer.flush();
        writer.close();

        final InputStream serialization = xml.addOrReplaceEntity(entityKey, entitySetName,
                new ByteArrayInputStream(content.toByteArray()), entry);

        ResWrap<Entity> result = atomDeserializer.toEntity(serialization);
        result = new ResWrap<Entity>(URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName
                + Constants.get(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)), null, result.getPayload());

        final String path = Commons.getEntityBasePath(entitySetName, entityKey);
        FSManager.instance().putInMemory(result, path + Constants.get(ConstantKey.ENTITY));

        final String location;

        if ((this instanceof KeyAsSegment)) {
            location = uriInfo.getRequestUri().toASCIIString() + "/" + entityKey;

            final Link editLink = new Link();
            editLink.setRel("edit");
            editLink.setTitle(entitySetName);
            editLink.setHref(location);

            result.getPayload().setEditLink(editLink);
        } else {
            location = uriInfo.getRequestUri().toASCIIString() + "(" + entityKey + ")";
        }

        final Response response;
        if ("return-no-content".equalsIgnoreCase(prefer)) {
            response = xml.createResponse(location, null, null, acceptType, Response.Status.NO_CONTENT);
        } else {
            response = xml.createResponse(location, xml.writeEntity(acceptType, result), null, acceptType,
                    Response.Status.CREATED);
        }

        if (StringUtils.isNotBlank(prefer)) {
            response.getHeaders().put("Preference-Applied", Collections.<Object>singletonList(prefer));
        }

        return response;
    } catch (Exception e) {
        LOG.error("While creating new entity", e);
        return xml.createFaultResponse(accept, e);
    }
}

From source file:com.MainFiles.Functions.java

public String getCustomerDetails(String strAccountNumber) throws IOException {
    String[] strCustomerNameArray;
    String strCustomerName = "";
    String fname = "";
    String mname = "";
    String lname = "";
    try {//w w  w  .j a  v a  2 s  .  c o  m
        URL url = new URL(CUSTOMER_DETAILS_URL);
        Map<String, String> params = new LinkedHashMap<>();

        params.put("username", CUSTOMER_DETAILS_USERNAME);
        params.put("password", CUSTOMER_DETAILS_PASSWORD);
        params.put("source", CUSTOMER_DETAILS_SOURCE_ID);
        params.put("account", strAccountNumber);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        String urlParameters = postData.toString();
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String result = "";
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        while ((line = reader.readLine()) != null) {
            result += line;
        }
        writer.close();
        reader.close();

        JSONObject respobj = new JSONObject(result);
        if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) {
            if (respobj.has("FSTNAME")) {
                fname = respobj.get("FSTNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("MIDNAME")) {
                mname = respobj.get("MIDNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("LSTNAME")) {
                lname = respobj.get("LSTNAME").toString().toUpperCase() + ' ';
            }
            strCustomerName = fname + mname + lname;
        } else {
            strCustomerName = "N/A";
        }

    } catch (Exception ex) {
        this.log("\nINFO : Function getCustomerDetails() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "ERROR");
    }

    // System.out.println(strCustomerName);
    return strCustomerName;
}

From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

public void getRawTextFromUrlIfNeeded(DocumentPojo doc, SourceRssConfigPojo feedConfig) throws IOException {
    if (null != doc.getFullText()) { // Nothing to do
        return;/* w  w w.  j av a2s.co  m*/
    }
    Scanner s = null;
    OutputStreamWriter wr = null;
    try {
        URL url = new URL(doc.getUrl());
        URLConnection urlConnect = null;
        String postContent = null;
        if (null != feedConfig) {
            urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
            if (null != feedConfig.getUserAgent()) {
                urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
            } // TESTED (by hand)
            if (null != feedConfig.getHttpFields()) {
                for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                    if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                        postContent = httpFieldPair.getValue();
                        urlConnect.setDoInput(true);
                        urlConnect.setDoOutput(true);
                    } else {
                        urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                    }
                }
            } //TESTED (by hand)
        } else {
            urlConnect = url.openConnection();
        }
        InputStream urlStream = null;
        try {
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } catch (SecurityException se) {
            throw se;
        } catch (Exception e) { // Try one more time, this time exception out all the way
            securityManager.setSecureFlag(false); // (some file stuff - so need to re-enable)
            if (null != feedConfig) {
                urlConnect = url.openConnection(ProxyManager.getProxy(url, feedConfig.getProxyOverride()));
                if (null != feedConfig.getUserAgent()) {
                    urlConnect.setRequestProperty("User-Agent", feedConfig.getUserAgent());
                } // TESTED
                if (null != feedConfig.getHttpFields()) {
                    for (Map.Entry<String, String> httpFieldPair : feedConfig.getHttpFields().entrySet()) {
                        if (httpFieldPair.getKey().equalsIgnoreCase("content")) {
                            urlConnect.setDoInput(true); // (need to do this again)
                            urlConnect.setDoOutput(true);
                        } else {
                            urlConnect.setRequestProperty(httpFieldPair.getKey(), httpFieldPair.getValue());
                        }
                    }
                } //TESTED
            } else {
                urlConnect = url.openConnection();
            }
            securityManager.setSecureFlag(true); // (disallow file/local URL access)
            if (null != postContent) {
                wr = new OutputStreamWriter(urlConnect.getOutputStream());
                wr.write(postContent.toCharArray());
                wr.flush();
            } //TESTED
            urlStream = urlConnect.getInputStream();
        } finally {
            securityManager.setSecureFlag(false); // (turn security check for local URL/file access off)
        }
        // Grab any interesting header fields
        Map<String, List<String>> headers = urlConnect.getHeaderFields();
        BasicDBObject metadataHeaderObj = null;
        for (Map.Entry<String, List<String>> it : headers.entrySet()) {
            if (null != it.getKey()) {
                if (it.getKey().startsWith("X-") || it.getKey().startsWith("Set-")
                        || it.getKey().startsWith("Location")) {
                    if (null == metadataHeaderObj) {
                        metadataHeaderObj = new BasicDBObject();
                    }
                    metadataHeaderObj.put(it.getKey(), it.getValue());
                }
            }
        } //TESTED
          // Grab the response code
        try {
            HttpURLConnection httpUrlConnect = (HttpURLConnection) urlConnect;
            int responseCode = httpUrlConnect.getResponseCode();
            if (200 != responseCode) {
                if (null == metadataHeaderObj) {
                    metadataHeaderObj = new BasicDBObject();
                }
                metadataHeaderObj.put("responseCode", String.valueOf(responseCode));
            }
        } //TESTED
        catch (Exception e) {
        } // interesting, not an HTTP connect ... shrug and carry on
        if (null != metadataHeaderObj) {
            doc.addToMetadata("__FEED_METADATA__", metadataHeaderObj);
        } //TESTED
        s = new Scanner(urlStream, "UTF-8");
        doc.setFullText(s.useDelimiter("\\A").next());
    } catch (MalformedURLException me) { // This one is worthy of a more useful error message
        throw new MalformedURLException(me.getMessage()
                + ": Likely because the document has no full text (eg JSON) and you are calling a contentMetadata block without setting flags:'m' or 'd'");
    } finally { //(release resources)
        if (null != s) {
            s.close();
        }
        if (null != wr) {
            wr.close();
        }
    }

}

From source file:org.apache.olingo.fit.Services.java

/**
 * Retrieve property sample./*from   ww w. j a  v a 2 s .  c  o  m*/
 *
 * @param accept Accept header.
 * @param entitySetName Entity set name.
 * @param entityId entity id.
 * @param path path.
 * @param format format query option.
 * @return property.
 */
@GET
@Path("/{entitySetName}({entityId})/{path:.*}")
public Response getPath(@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept,
        @PathParam("entitySetName") final String entitySetName, @PathParam("entityId") final String entityId,
        @PathParam("path") final String path,
        @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) {

    // default utilities
    final AbstractUtilities utils = xml;

    try {
        if (utils.isMediaContent(entitySetName + "/" + path)) {
            return navigateStreamedEntity(entitySetName, entityId, path);
        } else {
            Accept acceptType = null;
            if (StringUtils.isNotBlank(format)) {
                acceptType = Accept.valueOf(format.toUpperCase());
            } else if (StringUtils.isNotBlank(accept)) {
                acceptType = Accept.parse(accept, null);
            }

            try {
                final LinkInfo linkInfo = xml.readLinks(entitySetName, entityId, path, Accept.XML);
                final Map.Entry<String, List<String>> links = xml.extractLinkURIs(linkInfo.getLinks());
                final InputStream stream = xml.readEntities(links.getValue(), path, links.getKey(),
                        linkInfo.isFeed());

                final ByteArrayOutputStream content = new ByteArrayOutputStream();
                final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING);

                final ResWrap<?> container = linkInfo.isFeed() ? atomDeserializer.toEntitySet(stream)
                        : atomDeserializer.toEntity(stream);
                if (acceptType == Accept.ATOM) {
                    atomSerializer.write(writer, container);
                } else {
                    jsonSerializer.write(writer, container);
                }
                writer.flush();
                writer.close();

                final String basePath = Commons.getEntityBasePath(entitySetName, entityId);

                return xml.createResponse(null, new ByteArrayInputStream(content.toByteArray()),
                        Commons.getETag(basePath), acceptType);

            } catch (NotFoundException e) {
                // if the given path is not about any link then search for property
                return navigateProperty(acceptType, entitySetName, entityId, path, false);
            }
        }
    } catch (Exception e) {
        return utils.createFaultResponse(accept, e);
    }
}

From source file:org.cipango.callflow.JmxMessageLog.java

protected byte[] generateGraph(List<MessageInfo> messages, String xslUri, boolean includeMsg)
        throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStreamWriter out = new OutputStreamWriter(os);
    out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    if (xslUri != null)
        out.write("<?xml-stylesheet href=\"" + xslUri + "\" type=\"text/xsl\"?>\n");
    out.write("<data>\n");
    out.write("\t<hosts>\n");
    Map<String, Integer> hostsMap = new HashMap<String, Integer>();
    Iterator<MessageInfo> it = messages.iterator();
    int indexLocal = -1;
    int index = 1;
    while (it.hasNext()) {
        MessageInfo info = it.next();/*from ww  w.j  a va2  s  . c o m*/
        if (!hostsMap.containsKey(info.getLocalKey())) {
            if (indexLocal == -1) {
                out.write("\t\t<host>");
                String alias = _alias.get(info.getLocalKey());
                out.write(alias == null ? "Cipango" : alias);
                out.write("</host>\n");
                indexLocal = index++;
            }
            hostsMap.put(info.getLocalKey(), indexLocal);
        }

        if (!hostsMap.containsKey(info.getRemoteKey())) {
            out.write("\t\t<host>");
            String alias = _alias.get(info.getRemoteKey());
            out.write(alias == null ? info.getRemote() : alias);
            out.write("</host>\n");
            hostsMap.put(info.getRemoteKey(), index++);
        }
    }
    out.write("\t</hosts>\n");

    it = messages.iterator();
    out.write("\t<messages>\n");
    while (it.hasNext()) {
        MessageInfo info = it.next();
        out.write("\t\t<message from=\"");
        if (info.getDirection() == IN) {
            out.write(String.valueOf(hostsMap.get(info.getRemoteKey())));
            out.write("\" to=\"");
            out.write(String.valueOf(hostsMap.get(info.getLocalKey())));
            out.write("\">\n");
        } else {
            out.write(String.valueOf(hostsMap.get(info.getLocalKey())));
            out.write("\" to=\"");
            out.write(String.valueOf(hostsMap.get(info.getRemoteKey())));
            out.write("\">\n");
        }
        out.write("\t\t\t<name>");
        out.write(info.getShortName());
        out.write("</name>\n");
        out.write("\t\t\t<date>");
        out.write(info.getFormatedDate());
        out.write("</date>\n");
        if (includeMsg) {
            StringBuilder sb = new StringBuilder(info.getMessage().toString());
            replaceAll(sb, "<", "&lt;");
            replaceAll(sb, ">", "&gt;");
            String msg = sb.toString();
            int nbLines = 1;
            for (int i = 0; i < msg.length(); i++)
                if (msg.charAt(i) == '\n')
                    nbLines++;
            out.write("\t\t\t<content nbLines=\"" + nbLines + "\">");
            out.write(msg);
            out.write("</content>\n");
        }
        out.write("\t\t</message>\n");
    }
    out.write("\t</messages>\n");
    out.write("</data>\n");
    out.flush();
    return os.toByteArray();
}

From source file:net.mindengine.oculus.frontend.web.controllers.test.AjaxParameterSearchController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");

    String rId = request.getParameter("id");

    OutputStreamWriter w = new OutputStreamWriter(os);

    String rootId = rId;/* w w w  .  j  a  v a 2  s  .c o  m*/
    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"" + rootId + "\" >");

    List<Project> projects = null;
    List<TestGroup> groups = null;
    List<Test> tests = null;
    List<TestParameter> parameters = null;
    if (rId.equals("0")) {
        // Fetching a list of projects
        projects = projectDAO.getRootProjects();
    } else if (rId.startsWith("p")) {
        Long projectId = Long.parseLong(rId.substring(1));
        projects = projectDAO.getSubprojects(projectId);

        tests = testDAO.getTestsByProjectId(projectId, 0L);
        groups = testDAO.getProjectTestGroups(projectId);
    } else if (rId.startsWith("g")) {
        // g123_456 where 123 - id of a group and 456 - id of a project
        int dash = rId.indexOf("_");
        Long groupId = Long.parseLong(rId.substring(1, dash));
        Long projectId = Long.parseLong(rId.substring(dash + 1));

        tests = testDAO.getTestsByProjectId(projectId, groupId);
    } else if (rId.startsWith("t")) {
        Long testId = Long.parseLong(rId.substring(1));
        parameters = testDAO.getTestInputParameters(testId);
        parameters.addAll(testDAO.getTestOutputParameters(testId));
    }

    if (projects != null) {
        for (Project project : projects) {
            w.write("<item text=\"" + XmlUtils.escapeXml(project.getName()) + "\" " + "id=\"p" + project.getId()
                    + "\" im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" child=\"1\" "
                    + " nocheckbox=\"1\" >");
            w.write("</item>");
        }
    }
    if (groups != null) {
        for (TestGroup group : groups) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(group.getName()) + "\" ");
            w.write("id=\"g" + group.getId() + "_" + group.getProjectId() + "\" ");
            w.write("im0=\"folderClosed.gif\" im1=\"folderOpen.gif\" im2=\"folderClosed.gif\" ");
            w.write("child=\"1\" nocheckbox=\"1\"  >");
            w.write("</item>");
        }
    }
    if (tests != null) {
        for (Test test : tests) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(test.getName()) + "\" ");
            w.write("id=\"t" + test.getId() + "\" ");
            w.write("im0=\"iconTest.png\" im1=\"iconTest.png\" im2=\"iconTest.png\" ");
            w.write("child=\"1\" nocheckbox=\"1\"  >");
            w.write("</item>");
        }
    }
    if (parameters != null) {
        for (TestParameter parameter : parameters) {
            w.write("<item ");
            w.write("text=\"" + XmlUtils.escapeXml(parameter.getName()) + "\" ");
            w.write("id=\"tp" + parameter.getId() + "\" ");

            if (parameter.getType().equals(TestParameter.TYPE_INPUT)) {
                w.write("im0=\"iconParameterInput.png\" im1=\"iconParameterInput.png\" im2=\"iconParameterInput.png\" ");
            } else
                w.write("im0=\"iconParameterOutput.png\" im1=\"iconParameterOutput.png\" im2=\"iconParameterOutput.png\" ");
            w.write(" >");
            w.write("</item>");
        }
    }

    w.write("</tree>");
    w.flush();
    os.flush();
    os.close();
    return null;
}