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:org.apache.olingo.fit.V4Services.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 w  w .jav  a  2 s.c  om
        // 1. Fetch the contained entity to be removed
        final InputStream entry = FSManager.instance(version)
                .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(version).deleteFile(atomEntryRelativePath);

        // 3. Update the contained entity set
        final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString();
        final InputStream feedIS = FSManager.instance(version).readFile(atomFeedRelativePath, Accept.ATOM);
        final ResWrap<EntitySet> 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(version).putInMemory(new ByteArrayInputStream(content.toByteArray()),
                FSManager.instance(version).getAbsolutePath(atomFeedRelativePath, Accept.ATOM));

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

From source file:com.orange.api.atmosdav.AtmosDavServlet.java

public static String encode(String s) {
    int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now
    StringBuffer out = new StringBuffer(s.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);

    try {/*from   w w  w .j a va 2  s . c om*/
        OutputStreamWriter writer = new OutputStreamWriter(buf, dfltEncName);

        for (int i = 0; i < s.length(); i++) {
            int c = (int) s.charAt(i);

            if (dontNeedEncoding.get(c)) {
                out.append((char) c);
            } else {
                // convert to external encoding before hex conversion
                try {
                    writer.write(c);
                    /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                    if (c >= 0xD800 && c <= 0xDBFF) {
                        if ((i + 1) < s.length()) {
                            int d = (int) s.charAt(i + 1);
                            if (d >= 0xDC00 && d <= 0xDFFF) {
                                writer.write(d);
                                i++;
                            }
                        }
                    }
                    writer.flush();
                } catch (IOException e) {
                    buf.reset();
                    continue;
                }
                byte[] ba = buf.toByteArray();
                for (int j = 0; j < ba.length; j++) {
                    out.append('%');
                    char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                    // converting to use uppercase letter as part of
                    // the hex value if ch is a letter.
                    if (Character.isLetter(ch)) {
                        ch -= caseDiff;
                    }
                    out.append(ch);
                    ch = Character.forDigit(ba[j] & 0xF, 16);
                    if (Character.isLetter(ch)) {
                        ch -= caseDiff;
                    }
                    out.append(ch);
                }
                buf.reset();
            }
        }
        return out.toString();
    } catch (UnsupportedEncodingException e) {
        return s;
    }

}

From source file:org.apache.olingo.fit.V4Services.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 2s  . c o  m
        final Accept acceptType = Accept.parse(accept, version);
        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, version);
        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(version).putInMemory(utils.writeEntity(Accept.ATOM, entryContainer),
                FSManager.instance(version).getAbsolutePath(atomEntryRelativePath, Accept.ATOM));

        // 3. Update the contained entity set
        final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString();
        final InputStream feedIS = FSManager.instance(version).readFile(atomFeedRelativePath, Accept.ATOM);
        final ResWrap<EntitySet> 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(version).putInMemory(new ByteArrayInputStream(content.toByteArray()),
                FSManager.instance(version).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.deviceconnect.android.deviceplugin.irkit.IRKitManager.java

/**
 * ?./*from   www.  j  a  v  a 2 s. c o  m*/
 * @param conn HttpURLConnection
 * @param keyValues Query
 * @return Body?
 * @throws IOExceptionStream?
 */
private String executeRequest(final HttpURLConnection conn, final Map<String, String> keyValues)
        throws IOException {
    StringBuffer body = new StringBuffer();
    if (keyValues.size() > 0) {
        Uri.Builder builder = new Uri.Builder();
        Set<String> keys = keyValues.keySet();
        for (String key : keys) {
            builder.appendQueryParameter(key, keyValues.get(key));
        }
        String join = builder.build().getEncodedQuery();
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(join);
        out.flush();
        out.close();
        conn.connect();
        String st = null;
        InputStream in = null;
        try {
            in = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            while ((st = br.readLine()) != null) {
                body.append(st);
            }
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Http Request Error", e);
            }
            body = null;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "Http Request Error", e);
                }
            }
            conn.disconnect();

        }
    }
    return body.toString();
}

From source file:org.deviceconnect.android.deviceplugin.irkit.IRKitManager.java

/**
 * ??./*w  w w.java2 s. c om*/
 * 
 * @param ip IRKit?IP
 * @param message 
 * @param callback ??????
 */
public void sendMessage(final String ip, final String message, final PostMessageCallback callback) {
    mExecutor.execute(new Runnable() {

        @Override
        public void run() {
            HttpURLConnection req = null;
            boolean result = false;
            try {
                req = createPostRequest(ip, "/messages");
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "ip=" + ip + " post message : " + message);
                }
                req.setRequestProperty("Content-Length", String.valueOf(message.length()));
                OutputStreamWriter out = new OutputStreamWriter(req.getOutputStream());
                out.write(message);
                out.flush();
                req.connect();
                out.close();
                int status = req.getResponseCode();
                if (status == STATUS_CODE_OK) {
                    result = true;
                }

                // ?IRKit??????????
                // IRKit??????????????
                try {
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                callback.onPostMessage(result);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (req != null) {
                    req.disconnect();
                }
                callback.onPostMessage(result);
            }

        }
    });
}

From source file:org.deviceconnect.android.deviceplugin.irkit.IRKitManager.java

/**
 * ?./*from  w ww  .  j  a va2s .c o m*/
 * 
 * @param conn 
 * @param bodyData ??
 * @return ?????null?
 */
private String executeRequest(final HttpURLConnection conn, final String bodyData) {
    String body = null;
    InputStream in = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        if (bodyData != null && bodyData.length() > 0) {
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(bodyData);
            out.flush();
            out.close();
        }
        conn.connect();
        int resp = conn.getResponseCode();
        if (resp == 200) {
            in = conn.getInputStream();
            int len;
            byte[] buf = new byte[4096];
            while ((len = in.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            in.close();
        } else {
            in = conn.getErrorStream();
            int len;
            byte[] buf = new byte[4096];
            while ((len = in.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            in.close();
        }
        body = new String(baos.toByteArray(), "UTF-8");
    } catch (IOException e) {
        if (BuildConfig.DEBUG) {
            Log.e(TAG, "IOException", e);
        }
        body = null;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Http Request Error", e);
            }
        }
        conn.disconnect();
    }
    return body;
}

From source file:org.araqne.confdb.file.Exporter.java

public void exportData(OutputStream os) throws IOException {
    if (os == null)
        throw new IllegalArgumentException("export output stream cannot be null");

    logger.debug("araqne confdb: start export data");
    db.lock();//  w w w.j  a v a  2 s  .co  m
    try {
        OutputStreamWriter writer = new OutputStreamWriter(os, Charset.forName("utf-8"));
        JSONWriter jw = new JSONWriter(writer);

        jw.object();

        jw.key("metadata");
        jw.object();
        jw.key("version").value(1);
        jw.key("date").value(sdf.format(new Date()));
        jw.endObject();

        jw.key("collections");
        jw.object();

        for (String name : db.getCollectionNames()) {
            ConfigCollection col = db.getCollection(name);

            // collection name
            jw.key(name);

            // typed doc list
            jw.array();

            jw.value("list");

            // doc list begin
            jw.array();

            ConfigIterator it = col.findAll();
            try {
                while (it.hasNext()) {
                    Object doc = it.next().getDocument();
                    jw.value(insertType(doc));
                }
            } finally {
                it.close();
            }

            // end of doc list
            jw.endArray();

            // end of typed list
            jw.endArray();
        }

        // end of collection
        jw.endObject();

        // end of master doc
        jw.endObject();
        writer.flush();
        logger.debug("araqne confdb: export complete");
    } catch (JSONException e) {
        throw new IOException(e);
    } finally {
        db.unlock();
    }
}

From source file:org.alfresco.repo.transfer.fsr.FileTransferReceiver.java

public void generateRequsite(String transferId, OutputStream requsiteStream) throws TransferException {
    log.debug("Generate Requisite for transfer:" + transferId);
    try {/*from   w  w  w.ja  va2 s .c  om*/
        File snapshotFile = getSnapshotFile(transferId);

        if (snapshotFile.exists()) {
            log.debug("snapshot does exist");
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser parser = saxParserFactory.newSAXParser();
            OutputStreamWriter dest = new OutputStreamWriter(requsiteStream, "UTF-8");

            XMLTransferRequsiteWriter writer = new XMLTransferRequsiteWriter(dest);
            TransferManifestProcessor processor = manifestProcessorFactory
                    .getRequsiteProcessor(FileTransferReceiver.this, transferId, writer);

            XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

            /**
             * Now run the parser
             */
            parser.parse(snapshotFile, reader);

            /**
             * And flush the destination in case any content remains in the writer.
             */
            dest.flush();

        }
        log.debug("Generate Requisite done transfer:" + transferId);

    } catch (Exception ex) {
        if (TransferException.class.isAssignableFrom(ex.getClass())) {
            throw (TransferException) ex;
        } else {
            throw new TransferException(MSG_ERROR_WHILE_GENERATING_REQUISITE, ex);
        }
    }

}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {//from   ww w. j a v a 2  s  . c om
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.common.log.newproxy.BizStaticFileAppender.java

/**
 * ???//from w  w w . ja  va 2s  .com
 * @param event LoggingEvent
 * @return boolean ?
 */
private boolean log2extraFile(LoggingEvent event) {
    //?
    boolean hasLog = false;

    //StringBuffer lastDay=new StringBuffer();
    if (inCheckTrap() && event != null) {
        Object msg = event.getMessage();
        boolean needAppendExtra = isLog2Extra(msg);
        if (needAppendExtra) {//??
            String statPath = LogHelper.getLogRootPath() + FILE_SEP + "log" + FILE_SEP + CHECKFILE_PATH
                    + FILE_SEP;
            File path = new File(statPath);
            if (!path.exists()) {
                path.mkdir();
            }

            String extraFileName = getExtraLogFileName();
            extFile = new File(path, extraFileName);
            OutputStreamWriter exSw;
            FileOutputStream exFw;
            try {
                if (extFile.exists()) {//
                    exFw = new FileOutputStream(extFile, true);
                } else {//
                    exFw = new FileOutputStream(extFile);
                }
                exSw = new OutputStreamWriter(exFw, encoding);
                if (msg instanceof String) {
                    exSw.write((String) msg + NEXT_LINE);
                    hasLog = true;
                } else if (msg instanceof BizLogContent) {
                    String content = ((BizLogContent) msg).toString();
                    exSw.write(content + NEXT_LINE);
                    hasLog = true;
                }
                exSw.flush();
                exFw.flush();
                exSw.close();
                exFw.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }
    return hasLog;
}