Example usage for java.io OutputStreamWriter getEncoding

List of usage examples for java.io OutputStreamWriter getEncoding

Introduction

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

Prototype

public String getEncoding() 

Source Link

Document

Returns the name of the character encoding being used by this stream.

Usage

From source file:com.example.android.networkconnect.MainActivity.java

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//from w  w  w.jav  a  2  s  .c o m

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        try {

            String headerName = null;

            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                //data=data+"Header Nme : " + headerName;
                //data=data+conn.getHeaderField(i);
                // Log.i (TAG,headerName);
                Log.i(TAG, headerName + ": " + conn.getHeaderField(i));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

        // conn= (HttpsURLConnection) url.wait(); ;
        //(HttpsURLConnection) url.openConnection();

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

From source file:org.apache.jackrabbit.core.persistence.xml.XMLPersistenceManager.java

/**
 * {@inheritDoc}//  ww  w .  jav a  2 s. c om
 */
protected void store(NodeState state) throws ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    NodeId id = state.getNodeId();
    String nodeFilePath = buildNodeFilePath(id);
    FileSystemResource nodeFile = new FileSystemResource(itemStateFS, nodeFilePath);
    try {
        nodeFile.makeParentDirs();
        OutputStream os = nodeFile.getOutputStream();
        Writer writer = null;
        try {
            String encoding = DEFAULT_ENCODING;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(os, encoding));
            } catch (UnsupportedEncodingException e) {
                // should never get here!
                OutputStreamWriter osw = new OutputStreamWriter(os);
                encoding = osw.getEncoding();
                writer = new BufferedWriter(osw);
            }

            String parentId = (state.getParentId() == null) ? "" : state.getParentId().toString();
            String encodedNodeType = Text.encodeIllegalXMLCharacters(state.getNodeTypeName().toString());
            writer.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n");
            writer.write("<" + NODE_ELEMENT + " " + UUID_ATTRIBUTE + "=\"" + id + "\" " + PARENTUUID_ATTRIBUTE
                    + "=\"" + parentId + "\" " + MODCOUNT_ATTRIBUTE + "=\"" + state.getModCount() + "\" "
                    + NODETYPE_ATTRIBUTE + "=\"" + encodedNodeType + "\">\n");

            // mixin types
            writer.write("\t<" + MIXINTYPES_ELEMENT + ">\n");
            for (Name mixin : state.getMixinTypeNames()) {
                writer.write("\t\t<" + MIXINTYPE_ELEMENT + " " + NAME_ATTRIBUTE + "=\""
                        + Text.encodeIllegalXMLCharacters(mixin.toString()) + "\"/>\n");
            }
            writer.write("\t</" + MIXINTYPES_ELEMENT + ">\n");

            // properties
            writer.write("\t<" + PROPERTIES_ELEMENT + ">\n");
            for (Name propName : state.getPropertyNames()) {
                writer.write("\t\t<" + PROPERTY_ELEMENT + " " + NAME_ATTRIBUTE + "=\""
                        + Text.encodeIllegalXMLCharacters(propName.toString()) + "\">\n");
                // @todo serialize type, definition id and values
                writer.write("\t\t</" + PROPERTY_ELEMENT + ">\n");
            }
            writer.write("\t</" + PROPERTIES_ELEMENT + ">\n");

            // child nodes
            writer.write("\t<" + NODES_ELEMENT + ">\n");
            for (ChildNodeEntry entry : state.getChildNodeEntries()) {
                writer.write("\t\t<" + NODE_ELEMENT + " " + NAME_ATTRIBUTE + "=\""
                        + Text.encodeIllegalXMLCharacters(entry.getName().toString()) + "\" " + UUID_ATTRIBUTE
                        + "=\"" + entry.getId() + "\">\n");
                writer.write("\t\t</" + NODE_ELEMENT + ">\n");
            }
            writer.write("\t</" + NODES_ELEMENT + ">\n");

            writer.write("</" + NODE_ELEMENT + ">\n");
        } finally {
            writer.close();
        }
    } catch (Exception e) {
        String msg = "failed to write node state: " + id;
        log.debug(msg);
        throw new ItemStateException(msg, e);
    }
}

From source file:org.apache.jackrabbit.core.persistence.xml.XMLPersistenceManager.java

/**
 * {@inheritDoc}/*  ww  w.ja  v  a 2s. com*/
 */
protected void store(PropertyState state) throws ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    String propFilePath = buildPropFilePath(state.getPropertyId());
    FileSystemResource propFile = new FileSystemResource(itemStateFS, propFilePath);
    try {
        propFile.makeParentDirs();
        OutputStream os = propFile.getOutputStream();
        // write property state to xml file
        Writer writer = null;
        try {
            String encoding = DEFAULT_ENCODING;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(os, encoding));
            } catch (UnsupportedEncodingException e) {
                // should never get here!
                OutputStreamWriter osw = new OutputStreamWriter(os);
                encoding = osw.getEncoding();
                writer = new BufferedWriter(osw);
            }

            String typeName;
            int type = state.getType();
            try {
                typeName = PropertyType.nameFromValue(type);
            } catch (IllegalArgumentException iae) {
                // should never be getting here
                throw new ItemStateException("unexpected property-type ordinal: " + type, iae);
            }

            writer.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n");
            writer.write("<" + PROPERTY_ELEMENT + " " + NAME_ATTRIBUTE + "=\""
                    + Text.encodeIllegalXMLCharacters(state.getName().toString()) + "\" " + PARENTUUID_ATTRIBUTE
                    + "=\"" + state.getParentId() + "\" " + MULTIVALUED_ATTRIBUTE + "=\""
                    + Boolean.toString(state.isMultiValued()) + "\" " + MODCOUNT_ATTRIBUTE + "=\""
                    + state.getModCount() + "\" " + TYPE_ATTRIBUTE + "=\"" + typeName + "\">\n");
            // values
            writer.write("\t<" + VALUES_ELEMENT + ">\n");
            InternalValue[] values = state.getValues();
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    writer.write("\t\t<" + VALUE_ELEMENT + ">");
                    InternalValue val = values[i];
                    if (val != null) {
                        if (type == PropertyType.BINARY) {
                            // special handling required for binary value:
                            // put binary value in BLOB store
                            InputStream in = val.getStream();
                            String blobId = blobStore.createId(state.getPropertyId(), i);
                            try {
                                blobStore.put(blobId, in, val.getLength());
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                            // store id of BLOB as property value
                            writer.write(blobId);
                            // replace value instance with value backed by resource
                            // in BLOB store and discard old value instance (e.g. temp file)
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                // optimization: if the BLOB store is resource-based
                                // retrieve the resource directly rather than having
                                // to read the BLOB from an input stream
                                FileSystemResource fsRes = ((ResourceBasedBLOBStore) blobStore)
                                        .getResource(blobId);
                                values[i] = InternalValue.create(fsRes);
                            } else {
                                in = blobStore.get(blobId);
                                try {
                                    values[i] = InternalValue.create(in);
                                } finally {
                                    try {
                                        in.close();
                                    } catch (IOException e) {
                                        // ignore
                                    }
                                }
                            }
                            val.discard();
                        } else {
                            writer.write(Text.encodeIllegalXMLCharacters(val.toString()));
                        }
                    }
                    writer.write("</" + VALUE_ELEMENT + ">\n");
                }
            }
            writer.write("\t</" + VALUES_ELEMENT + ">\n");
            writer.write("</" + PROPERTY_ELEMENT + ">\n");
        } finally {
            writer.close();
        }
    } catch (Exception e) {
        String msg = "failed to store property state: " + state.getParentId() + "/" + state.getName();
        log.debug(msg);
        throw new ItemStateException(msg, e);
    }
}

From source file:org.structr.web.basic.UiScriptingTest.java

private String getEncodingInUse() {
    OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
    return writer.getEncoding();
}

From source file:tufts.vue.action.ActionUtil.java

private static void doMarshallMap(final File targetFile, final File tmpFile, final LWMap map)
        throws java.io.IOException, org.exolab.castor.xml.MarshalException,
        org.exolab.castor.xml.ValidationException, org.exolab.castor.mapping.MappingException {
    final String path = tmpFile.getAbsolutePath().replaceAll("%20", " ");
    final FileOutputStream fos = new FileOutputStream(path);
    final OutputStreamWriter writer;
    FileDescriptor FD = null;/*  www .  j a  v a 2  s  .co  m*/

    try {
        FD = fos.getFD();
        // getting the FileDescriptor is not required -- we just use it
        // for a final call to sync after we save to increase the likelyhood
        // of our save file actually making it to disk.
    } catch (Throwable t) {
        Log.warn("No FileDescriptor for " + path + "; failsafe sync will be skipped: " + t);
    }

    if (OUTPUT_ENCODING.equals("UTF-8") || OUTPUT_ENCODING.equals("UTF8")) {
        writer = new OutputStreamWriter(fos, OUTPUT_ENCODING);
    } else {

        // For the actual file writer we can use the default encoding because we're
        // marshalling specifically in US-ASCII.  E.g., because we direct castor to
        // fully encode any special characters via setEncoding("US-ASCII"), we'll
        // only have ASCII chars to write anyway, and any default encoding will
        // handle that...

        writer = new OutputStreamWriter(fos);

        // below creates duplicate FOS, but may be better for debug?  (MarshallException's can find file?)
        //if (FD == null)
        //    writer = new FileWriter(path);
        //else
        //    writer = new FileWriter(FD);

    }

    if (DEBUG.IO) {
        try {
            Log.debug(String.format("%s; %s; encoding: \"%s\", which will represent \"%s\" XML content",
                    tmpFile, writer, writer.getEncoding(), OUTPUT_ENCODING));
        } catch (Throwable t) {
            Log.warn(t);
        }
    }

    //=======================================================
    // Marshall the map to the tmp file:
    // ---------------------------------

    marshallMapToWriter(writer, map, targetFile, tmpFile);

    //=======================================================

    // Run a filesystem sync if we can just to be sure: Especially helpful on some
    // linux file systems, such as Ext3, which may not normally touch the disk for
    // another 5 seconds, or XFS/Ext4, which may take their own sweet time.
    // For more see:
    // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/317781/comments/54

    if (DEBUG.IO)
        Log.debug("flushing " + writer);
    writer.flush();

    if (FD != null) {
        try {
            if (DEBUG.IO)
                Log.debug("syncing " + FD + "; for " + tmpFile);
            // just as backup -- must however be done before writer.close()
            FD.sync();
            Log.info(" sync'd " + FD + "; for " + tmpFile);
        } catch (Throwable t) {
            Log.warn("after save to " + targetFile + "; sync failed: " + t);
        }
    }

    if (DEBUG.IO)
        Log.debug("closing " + writer);
    writer.close();
    if (DEBUG.IO)
        Log.debug(" closed " + writer);

}

From source file:org.jibble.pircbot.PircBot.java

/**
 * Attempt to connect to the specified IRC server using the supplied
 * password./*from w w w.  j  av a  2  s  .  co  m*/
 * The onConnect method is called upon success.
 *
 * @param hostname The hostname of the server to connect to.
 * @param port     The port number to connect to on the server.
 * @param password The password to use to join the server.
 * @throws IOException               if it was not possible to connect to the server.
 * @throws IrcException              if the server would not let us join it.
 * @throws NickAlreadyInUseException if our nick is already in use on the server.
 */
public final synchronized void connect(String hostname, int port, String password)
        throws IOException, IrcException, NickAlreadyInUseException {

    _server = hostname;
    _port = port;
    _password = password;

    if (isConnected()) {
        throw new IOException("The PircBot is already connected to an IRC server.  Disconnect first.");
    }

    // Don't clear the outqueue - there might be something important in it!

    // Clear everything we may have know about channels.
    this.removeAllChannels();

    // Connect to the server.
    Socket socket = new Socket(hostname, port);
    logger.info("*** Connected to server.");

    _inetAddress = socket.getLocalAddress();

    _detector = new UniversalDetector(null);

    String defaultEncoding = null;

    OutputStreamWriter outputStreamWriter = null;

    if (getEncoding() != null) {
        // Assume the specified encoding is valid for this JVM.
        outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), getEncoding());
    } else {
        // Otherwise, just use the JVM's default encoding.
        outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
    }

    defaultEncoding = outputStreamWriter.getEncoding();

    BufferedWriter bwriter = new BufferedWriter(outputStreamWriter);

    // Attempt to join the server.
    if (password != null && !password.equals("")) {
        OutputThread.sendRawLine(this, bwriter, "PASS " + password);
    }
    String nick = this.getName();
    OutputThread.sendRawLine(this, bwriter, "NICK " + nick);
    OutputThread.sendRawLine(this, bwriter, "USER " + this.getLogin() + " 8 * :" + this.getVersion());

    _inputThread = new InputThread(this, socket, socket.getInputStream(), bwriter, defaultEncoding);

    boolean connected = false;

    // Read stuff back from the server to see if we connected.
    int tries = 1;
    byte[] buffer = new byte[BUFFER_SIZE];
    int readBytes = -1;
    String overflow = "";
    while ((readBytes = socket.getInputStream().read(buffer)) > -1) {

        String encoding = detect(buffer);
        if (logger.isDebugEnabled()) {
            logger.debug("Detected encoding from IRC Server: {} (may be null)", encoding);
        }
        if (StringUtils.isBlank(encoding)) {
            encoding = defaultEncoding;
        }

        String decodedBuffer = new String(buffer, 0, readBytes, Charset.forName(encoding));
        String[] lines = (overflow + decodedBuffer).split("\\r?\\n");

        // if the buffer does not end with a \n, then maybe the last sentence is not complete
        // We need to save this part for the next round.
        if (!decodedBuffer.endsWith("\n")) {
            overflow = lines[lines.length - 1];
            lines = ArrayUtils.remove(lines, lines.length - 1);
        } else {
            overflow = "";
        }

        for (String line : lines) {

            if (StringUtils.isNotBlank(line)) {

                this.handleLine(line);

                int firstSpace = line.indexOf(" ");
                int secondSpace = line.indexOf(" ", firstSpace + 1);
                if (secondSpace >= 0) {
                    String code = line.substring(firstSpace + 1, secondSpace);

                    if (code.equals("004")) {
                        // We're connected to the server.
                        connected = true;
                        break;
                    } else if (code.equals("433")) {
                        if (_autoNickChange) {
                            tries++;
                            nick = getName() + tries;
                            OutputThread.sendRawLine(this, bwriter, "NICK " + nick);
                        } else {
                            socket.close();
                            _inputThread = null;
                            throw new NickAlreadyInUseException(line);
                        }
                    } else if (code.equals("439")) {
                        // No action required.
                    } else if (code.startsWith("5") || code.startsWith("4")) {
                        socket.close();
                        _inputThread = null;
                        throw new IrcException("Could not log into the IRC server: " + line);
                    }
                }
                this.setNick(nick);
            }
        }

        if (connected) {
            break;
        }
    }

    logger.info("*** Logged onto server.");

    // This makes the socket timeout on read operations after 5 minutes.
    // Maybe in some future version I will let the user change this at runtime.
    socket.setSoTimeout(5 * 60 * 1000);

    // Now start the InputThread to read all other lines from the server.
    _inputThread.start();

    // Now start the outputThread that will be used to send all messages.
    if (_outputThread == null) {
        _outputThread = new OutputThread(this, _outQueue);
        _outputThread.start();
    }

    this.onConnect();

}