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.glucosio.android.tools.ReadingToCSV.java

public Uri createCSV(final ArrayList<GlucoseReading> readings, String um) {

    File file = new File(context.getFilesDir().getAbsolutePath(), "glucosio_exported_data.csv"); //Getting a file within the dir.

    try {//  w w w  .j  av  a2s  .  com
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);

        osw.append(context.getResources().getString(R.string.dialog_add_concentration));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_measured));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_date));
        osw.append(',');

        osw.append(context.getResources().getString(R.string.dialog_add_time));
        osw.append('\n');

        FormatDateTime dateTool = new FormatDateTime(context);

        if ("mg/dL".equals(um)) {
            for (int i = 0; i < readings.size(); i++) {

                osw.append(readings.get(i).getReading() + "mg/dL");
                osw.append(',');

                osw.append(readings.get(i).getReading_type() + "");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        } else {
            GlucosioConverter converter = new GlucosioConverter();

            for (int i = 0; i < readings.size(); i++) {

                osw.append(converter.glucoseToMmolL(readings.get(i).getReading()) + "mmol/L");
                osw.append(',');

                osw.append(dateTool.convertRawDate(readings.get(i).getCreated() + ""));
                osw.append(',');

                osw.append(dateTool.convertRawTime(readings.get(i).getCreated() + ""));
                osw.append('\n');
            }
        }

        osw.flush();
        osw.close();
        Log.i("Glucosio", "Done exporting readings");

    } catch (Exception e) {
        e.printStackTrace();
    }

    context.grantUriPermission(context.getPackageName(), Uri.parse(file.getAbsolutePath()),
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

    return FileProvider.getUriForFile(context, context.getPackageName() + ".provider.fileprovider",
            file.getAbsoluteFile());
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

public void getObjectProfile(Context context, String PID, Date asOfDateTime, boolean xml,
        HttpServletRequest request, HttpServletResponse response) throws ServerException {

    OutputStreamWriter out = null;
    Date versDateTime = asOfDateTime;
    ObjectProfile objProfile = null;/*  w  w  w  . jav  a  2  s  .co  m*/
    PipedWriter pw = null;
    PipedReader pr = null;
    try {
        pw = new PipedWriter();
        pr = new PipedReader(pw);
        objProfile = m_access.getObjectProfile(context, PID, asOfDateTime);
        if (objProfile != null) {
            // Object Profile found.
            // Serialize the ObjectProfile object into XML
            new ProfileSerializerThread(context, PID, objProfile, versDateTime, pw).start();
            if (xml) {
                // Return results as raw XML
                response.setContentType(CONTENT_TYPE_XML);

                // Insures stream read from PipedReader correctly translates
                // utf-8
                // encoded characters to OutputStreamWriter.
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                char[] buf = new char[BUF];
                int len = 0;
                while ((len = pr.read(buf, 0, BUF)) != -1) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } else {
                // Transform results into an html table
                response.setContentType(CONTENT_TYPE_HTML);
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                File xslFile = new File(m_server.getHomeDir(), "access/viewObjectProfile.xslt");
                Templates template = XmlTransformUtility.getTemplates(xslFile);
                Transformer transformer = template.newTransformer();
                transformer.setParameter("fedora", context.getEnvironmentValue(FEDORA_APP_CONTEXT_NAME));
                transformer.transform(new StreamSource(pr), new StreamResult(out));
            }
            out.flush();

        } else {
            throw new GeneralException("No object profile returned");
        }
    } catch (ServerException e) {
        throw e;
    } catch (Throwable th) {
        String message = "Error getting object profile";
        logger.error(message, th);
        throw new GeneralException(message, th);
    } finally {
        try {
            if (pr != null) {
                pr.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Throwable th) {
            String message = "Error closing output";
            logger.error(message, th);
            throw new StreamIOException(message);
        }
    }
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public void saveCookies() {
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;
    // make dirs//from   w  w w .j a  va  2  s  . co  m
    File dir1 = new File(this.main_aagtl.main_dir + "/config");
    dir1.mkdirs();
    // save cookies to file
    try {
        File cookie_file = new File(this.main_aagtl.main_dir + "/config/cookie.txt");
        fOut = new FileOutputStream(cookie_file);
        osw = new OutputStreamWriter(fOut);
        osw.write(cookie_jar.toString());
        osw.flush();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("saveCookies: Exception1");
    } finally {
        try {
            osw.close();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("saveCookies: Exception2");
        }
    }
}

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

@PATCH
@Path("/{entitySetName}({entityId})")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
public Response patchEntity(@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,
        @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) final String ifMatch,
        @PathParam("entitySetName") final String entitySetName, @PathParam("entityId") final String entityId,
        final String changes) {

    try {//from  w w w  .  java2  s  .co m
        final Accept acceptType = Accept.parse(accept, version);

        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(), version);
        if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) {
            throw new ConcurrentModificationException("Concurrent modification");
        }

        final Accept contentTypeValue = Accept.parse(contentType, version);

        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(version).putInMemory(cres,
                path + File.separatorChar + Constants.get(version, 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.AbstractServices.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  w  w  .j  a  va 2  s. c o m
        final Accept acceptType = Accept.parse(accept, version);
        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 EntityImpl();
            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 PropertyImpl();
                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 LinkImpl();
            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, version);
            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(version, ConstantKey.ODATA_METADATA_PREFIX) + entitySetName
                        + Constants.get(version, ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)),
                null, result.getPayload());

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

        final String location;

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

            final Link editLink = new LinkImpl();
            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.techventus.server.voice.Voice.java

/**
 * Send an SMS./*  ww w  .ja  v  a 2 s. c  o m*/
 *
 * @param destinationNumber the destination number
 * @param txt the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String sendSMS(String destinationNumber, String txt) throws IOException {
    String out = "";
    String smsdata = "";

    smsdata += URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc);
    smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc);
    smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
    URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/");

    URLConnection smsconn = smsurl.openConnection();
    smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    smsconn.setRequestProperty("User-agent", USER_AGENT);

    smsconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream());
    callwr.write(smsdata);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;
}

From source file:com.techventus.server.voice.Voice.java

/**
 * Send an SMS./*from   ww  w .  j a va 2s . c  o m*/
 *
 * @param destinationNumber the destination number
 * @param txt the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @param id the Text of the message. Messages longer than the allowed
 * character length will be split into multiple messages.
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String sendSMS(String destinationNumber, String txt, String id) throws IOException {
    String out = "";
    String smsdata = "";
    smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc);
    smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc);
    smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc);
    smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc);
    smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
    System.out.println("smsdata: " + smsdata);

    URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/");

    URLConnection smsconn = smsurl.openConnection();
    smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    smsconn.setRequestProperty("User-agent", USER_AGENT);

    smsconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream());
    callwr.write(smsdata);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;
}

From source file:com.techventus.server.voice.Voice.java

/**
 * Cancel a call that was just placed./*  w w w  .j av a2  s  .c  om*/
 * 
 * @param originNumber
 *            the origin number
 * @param destinationNumber
 *            the destination number
 * @param phoneType
 *            the phone type
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public String cancelCall(String originNumber, String destinationNumber, String phoneType) throws IOException {
    String out = "";
    String calldata = "";
    calldata += URLEncoder.encode("outgoingNumber", enc) + "=" + URLEncoder.encode("undefined", enc);
    calldata += "&" + URLEncoder.encode("forwardingNumber", enc) + "=" + URLEncoder.encode("undefined", enc);

    calldata += "&" + URLEncoder.encode("cancelType", enc) + "=" + URLEncoder.encode("C2C", enc);
    calldata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
    // POST /voice/call/connect/ outgoingNumber=[number to
    // call]&forwardingNumber=[forwarding
    // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from
    // page]
    URL callURL = new URL("https://www.google.com/voice/b/0/call/cancel/");

    URLConnection callconn = callURL.openConnection();
    callconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    callconn.setRequestProperty("User-agent", USER_AGENT);

    callconn.setDoOutput(true);
    OutputStreamWriter callwr = new OutputStreamWriter(callconn.getOutputStream());
    callwr.write(calldata);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(callconn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;

}

From source file:com.techventus.server.voice.Voice.java

/**
 * Executes the enable/disable action with the provided url params.
 *
 * @param paraString the URL Parameters (encoded), ie ?auth=3248sdf7234&enable=0&phoneId=1&enable=1&phoneId=2&_rnr_se=734682ghdsf
 * @return the raw response of the disable action.
 * @throws IOException Signals that an I/O exception has occurred.
 *//*from  ww w.java  2 s.  c  o  m*/
private String phonesEnableDisableApply(String paraString) throws IOException {
    String out = "";

    // POST /voice/call/connect/ outgoingNumber=[number to
    // call]&forwardingNumber=[forwarding
    // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from
    // page]

    //
    if (PRINT_TO_CONSOLE)
        System.out.println(phoneEnableURLString);
    if (PRINT_TO_CONSOLE)
        System.out.println(paraString);
    URL requestURL = new URL(phoneEnableURLString);

    URLConnection conn = requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;

}

From source file:com.techventus.server.voice.Voice.java

/**
 * Posts a settings change./*from  w w  w.j a va  2 s  . c o m*/
 *
 * @param requestURL the request url
 * @param paraString the para string
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String postSettings(URL requestURL, String paraString) throws IOException {
    String out = "";
    HttpURLConnection conn = (HttpURLConnection) requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    // Get the response
    conn.connect();
    int responseCode = conn.getResponseCode();
    if (PRINT_TO_CONSOLE)
        System.out.println(requestURL + " - " + conn.getResponseMessage());
    InputStream is;
    if (responseCode == 200) {
        is = conn.getInputStream();
    } else {
        is = conn.getErrorStream();
    }
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader callrd = new BufferedReader(isr);

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";
    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    if (PRINT_TO_CONSOLE)
        System.out.println(out);

    return out;
}