Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

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 {// ww  w.j  a  v a 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:de.fahrgemeinschaft.FahrgemeinschaftConnector.java

@Override
public String publish(Ride offer) throws Exception {
    HttpURLConnection post;//from  w  w w  .  java2s .  c  om
    if (offer.getRef() == null) {
        post = (HttpURLConnection) new URL(endpoint + TRIP).openConnection();
        post.setRequestMethod(POST);
    } else {
        post = (HttpURLConnection) new URL(
                new StringBuffer().append(endpoint).append(TRIP).append(ID).append(offer.getRef()).toString())
                        .openConnection();
        post.setRequestMethod(PUT);
    }
    post.setRequestProperty("User-Agent", USER_AGENT);
    post.setRequestProperty(APIKEY, Secret.APIKEY);
    if (getAuth() != null)
        post.setRequestProperty(AUTHKEY, getAuth());
    post.setDoOutput(true);
    JSONObject json = new JSONObject();
    //        json.put("Smoker", "no");
    json.put(TRIPTYPE, OFFER);
    json.put(TRIP_ID, offer.getRef());
    json.put(ID_USER, get(USER));
    if (offer.getMode() != null && offer.getMode().equals(Mode.TRAIN)) {
        json.put(PLATE, BAHN);
    } else {
        json.put(PLATE, offer.get(PLATE));
    }
    if (offer.isActive()) {
        json.put(RELEVANCE, 10);
    } else {
        json.put(RELEVANCE, 0);
    }
    json.put(PLACES, offer.getSeats());
    json.put(PRICE, offer.getPrice() / 100);
    json.put(CONTACTMAIL, offer.get(EMAIL));
    json.put(CONTACTMOBILE, offer.get(MOBILE));
    json.put(CONTACTLANDLINE, offer.get(LANDLINE));
    String dep = fulldf.format(offer.getDep());
    json.put(STARTDATE, dep.subSequence(0, 8));
    json.put(STARTTIME, dep.subSequence(8, 12));
    json.put(DESCRIPTION, offer.get(COMMENT));
    if (!offer.getDetails().isNull(PRIVACY))
        json.put(PRIVACY, offer.getDetails().getJSONObject(PRIVACY));
    if (!offer.getDetails().isNull(REOCCUR))
        json.put(REOCCUR, offer.getDetails().getJSONObject(REOCCUR));
    ArrayList<JSONObject> routings = new ArrayList<JSONObject>();
    List<Place> stops = offer.getPlaces();
    int max = stops.size() - 1;
    for (int dest = max; dest >= 0; dest--) {
        for (int orig = 0; orig < dest; orig++) {
            int idx = (orig == 0 ? (dest == max ? 0 : dest) : -dest);
            JSONObject route = new JSONObject();
            route.put(ROUTING_INDEX, idx);
            route.put(ORIGIN, place(stops.get(orig)));
            route.put(DESTINATION, place(stops.get(dest)));
            routings.add(route);
        }
    }
    json.put(ROUTINGS, new JSONArray(routings));
    OutputStreamWriter out = new OutputStreamWriter(post.getOutputStream());
    out.write(json.toString());
    out.flush();
    out.close();
    JSONObject response = loadJson(post);
    if (!response.isNull(TRIP_ID_WITH_SMALL_t)) {
        offer.ref(response.getString(TRIP_ID_WITH_SMALL_t));
    }
    return offer.getRef();
}

From source file:com.doomy.padlock.MainFragment.java

public void superUserReboot(String mCommand) {
    Runtime mRuntime = Runtime.getRuntime();
    Process mProcess = null;/*from   w ww . j a v a  2  s  .c  o m*/
    OutputStreamWriter mWrite = null;

    try {
        mProcess = mRuntime.exec("su");
        mWrite = new OutputStreamWriter(mProcess.getOutputStream());
        mWrite.write(mCommand + "\n");
        mWrite.flush();
        mWrite.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {//w  w w.ja  v  a2 s . c o m
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:net.sf.jasperreports.AbstractTest.java

protected String errExportDigest(Throwable t)
        throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException {
    File outputFile = createXmlOutputFile();
    log.debug("Error stack trace at " + outputFile.getAbsolutePath());

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    FileOutputStream output = new FileOutputStream(outputFile);
    OutputStreamWriter osw = null;
    try {//from  w w  w .  java2s .  c o  m
        DigestOutputStream out = new DigestOutputStream(output, digest);
        //PrintStream ps = new PrintStream(out);
        //t.printStackTrace(ps);
        osw = new OutputStreamWriter(out, "UTF-8");
        osw.write(String.valueOf(t.getMessage()));
    } finally {
        osw.close();
        output.close();
    }

    return toDigestString(digest);
}

From source file:com.google.ytd.picasa.PicasaApiHelper.java

public String getResumableUploadUrl(com.google.ytd.model.PhotoEntry photoEntry, String title,
        String description, String albumId, Double latitude, Double longitude) throws IllegalArgumentException {
    LOG.info(String.format("Resumable upload request.\nTitle: %s\nDescription: %s\nAlbum: %s", title,
            description, albumId));/* www  . j av  a 2 s.  c  om*/

    // Picasa API resumable uploads are not currently documented publicly, but they're essentially
    // the same as what YouTube API offers:
    // http://code.google.com/apis/youtube/2.0/developers_guide_protocol_resumable_uploads.html
    // The Java client library does offer support for resumable uploads, but its use of threads
    // and some other assumptions makes it unsuitable for our purposes.
    try {
        URL url = new URL(String.format(RESUMABLE_UPLOADS_URL_FORMAT, albumId));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestMethod("POST");

        // Set all the GData request headers. These strings should probably be moved to CONSTANTS.
        connection.setRequestProperty("Content-Type", "application/atom+xml;charset=UTF-8");
        connection.setRequestProperty("Authorization",
                String.format("AuthSub token=\"%s\"", adminConfigDao.getAdminConfig().getPicasaAuthSubToken()));
        connection.setRequestProperty("GData-Version", "2.0");
        connection.setRequestProperty("Slug", photoEntry.getOriginalFileName());
        connection.setRequestProperty("X-Upload-Content-Type", photoEntry.getFormat());
        connection.setRequestProperty("X-Upload-Content-Length",
                String.valueOf(photoEntry.getOriginalFileSize()));

        // If we're given lat/long then create the element to geotag the picture; otherwise, pass in
        // and empty string for no geotag.
        String geoRss = "";
        if (latitude != null && longitude != null) {
            geoRss = String.format(GEO_RSS_XML_FORMAT, latitude, longitude);
            LOG.info("Geo RSS XML: " + geoRss);
        }

        String atomXml = String.format(UPLOAD_ENTRY_XML_FORMAT, StringEscapeUtils.escapeXml(title),
                StringEscapeUtils.escapeXml(description), geoRss);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(atomXml);
        writer.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String uploadUrl = connection.getHeaderField("Location");
            if (util.isNullOrEmpty(uploadUrl)) {
                throw new IllegalArgumentException("No Location header found in HTTP response.");
            } else {
                LOG.info("Resumable upload URL is " + uploadUrl);

                return uploadUrl;
            }
        } else {
            LOG.warning(String.format("HTTP POST to %s returned status %d (%s).", url.toString(),
                    connection.getResponseCode(), connection.getResponseMessage()));
        }
    } catch (MalformedURLException e) {
        LOG.log(Level.WARNING, "", e);

        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "", e);
    }

    return null;
}

From source file:fitnesse.wiki.FileSystemPage.java

protected synchronized void saveContent(String content) throws IOException {
    if (content == null) {
        return;/*from  ww  w . j  a  v  a  2s . c  o  m*/
    }

    final String separator = System.getProperty("line.separator");

    if (content.endsWith("|")) {
        content += separator;
    }

    //First replace every windows style to unix
    content = content.replaceAll("\r\n", "\n");
    //Then do the replace to match the OS.  This works around
    //a strange behavior on windows.
    content = content.replaceAll("\n", separator);

    String contentPath = getFileSystemPath() + contentFilename;
    final File output = new File(contentPath);
    OutputStreamWriter writer = null;
    try {
        if (output.exists())
            cmSystem.edit(contentPath);
        writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
        writer.write(content);
    } catch (UnsupportedEncodingException e) {
        throw new ImpossibleException("UTF-8 is a supported encoding", e);
    } finally {
        if (writer != null) {
            IOUtils.closeQuietly(writer);
            cmSystem.update(contentPath);
        }
    }
}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean login(String username, String password) throws IOException {
    preLogin();/*from  w  w  w  .  ja v a 2  s.  co m*/
    URL url = new URL(LOGIN_HOST + LOGIN_SUFFIX);
    HttpURLConnection httpURLConnection_a = (HttpURLConnection) url.openConnection();
    httpURLConnection_a.setRequestMethod("POST");
    httpURLConnection_a.setUseCaches(false);
    httpURLConnection_a.setInstanceFollowRedirects(false);
    httpURLConnection_a.setDoOutput(true);

    String OUTPUT_DATA = "username=";
    OUTPUT_DATA += username;
    OUTPUT_DATA += "&password=";
    OUTPUT_DATA += password;
    OUTPUT_DATA += "&submit=";
    OUTPUT_DATA += "&lt=" + LOGIN_PARAM_lt;
    OUTPUT_DATA += "&execution=" + LOGIN_PARAM_execution;
    OUTPUT_DATA += "&_eventId=" + LOGIN_PARAM__eventId;
    OUTPUT_DATA += "&rmShown=" + LOGIN_PARAM_rmShown;

    httpURLConnection_a.setRequestProperty("Cookie",
            "route=" + ROUTE
                    + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; JSESSIONID="
                    + LOGIN_JSESSIONID + "; BIGipServeridsnew.xidian.edu.cn=" + BIGIP_SERVER_IDS_NEW + ";");

    httpURLConnection_a.connect();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection_a.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(OUTPUT_DATA);
    outputStreamWriter.flush();
    outputStreamWriter.close();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection_a.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("a");
    if (elements.size() == 0)
        return false;
    String SYS_LOCATION = elements.get(0).attr("href");

    URL sys_location = new URL(SYS_LOCATION);
    HttpURLConnection httpUrlConnection_b = (HttpURLConnection) sys_location.openConnection();
    httpUrlConnection_b.setInstanceFollowRedirects(false);
    httpUrlConnection_b.connect();
    List<String> cookies_to_set = httpUrlConnection_b.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(11, e.indexOf(";"));
    httpURLConnection_a.disconnect();
    httpUrlConnection_b.disconnect();
    return checkIsLogin(username);
}

From source file:com.google.samples.quickstart.signin.MainActivity.java

private String downloadUrl(String myurl, String tokenid) throws IOException {
    InputStream is = null;//w w  w.  ja  v a  2 s.  c  om
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        JSONObject cred = new JSONObject();
        cred.put("tokenid", tokenid);

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(cred.toString());
        wr.flush();
        //con.setRequestMethod("POST");
        //conn.setRequestProperty("tokenid",tokenid);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response);

        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.hangum.tadpole.importdb.core.dialog.importdb.sql.SQLToDBImportDialog.java

private void saveLog() {
    try {/*from w  w w  .j  av  a 2 s  . c  om*/
        if (bufferBatchResult == null || "".equals(bufferBatchResult.toString())) { //$NON-NLS-1$
            MessageDialog.openError(null, Messages.CsvToRDBImportDialog_4,
                    Messages.SQLToDBImportDialog_LogEmpty);
            return;
        }
        String filename = PublicTadpoleDefine.TEMP_DIR + userDB.getDisplay_name() + "_SQLImportResult.log"; //$NON-NLS-1$

        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter bw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$

        bw.write(bufferBatchResult.toString());
        bw.close();

        String strImportResultLogContent = FileUtils.readFileToString(new File(filename));

        downloadExtFile(userDB.getDisplay_name() + "_SQLImportResult.log", strImportResultLogContent);//sbExportData.toString()); //$NON-NLS-1$
    } catch (Exception ee) {
        logger.error("log writer", ee); //$NON-NLS-1$
    }
}