Java Code Examples for java.io.OutputStreamWriter

The following are top voted examples for showing how to use java.io.OutputStreamWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: nanobrowser   File: TripleStoreAccess.java View source code Vote up 7 votes
public static void runUpdateQuery(String query) {
	for (String qu : query.split("\n\n")) {
		// SPARQLRepository does not implement update queries
		try {
			URL url = new URL(endpointURL);
		    URLConnection connection = url.openConnection();
		    connection.setDoOutput(true);
		    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
		    wr.write("query=" + URLEncoder.encode(sparqlPrefixes + qu, "UTF8"));
		    wr.flush();
		    connection.getInputStream().close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
 
Example 2
Project: phonegap-geolocation   File: DiskLruCache.java View source code Vote up 6 votes
/** Sets the value at [email protected] index} to [email protected] value}. */
public void set(int index, String value) throws IOException {
  Writer writer = null;
  try {
    writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
    writer.write(value);
  } finally {
    Util.closeQuietly(writer);
  }
}
 
Example 3
Project: breakout   File: BimapperStreamBimapper.java View source code Vote up 6 votes
@Override
public void write( T t , OutputStream out ) throws Exception
{
	OutputStreamWriter writer = null;
	try
	{
		writer = new OutputStreamWriter( out );
		writer.write( format.map( t ) );
		writer.flush( );
	}
	finally
	{
		if( closeStreams && writer != null )
		{
			try
			{
				writer.close( );
			}
			catch( Exception ex )
			{
				
			}
		}
	}
}
 
Example 4
Project: aipo   File: JetspeedDiskCache.java View source code Vote up 6 votes
/**
 Get an Entry given a Reader and the URL from which it has been fetched.
@see DiskCache#getEntry( String url, Reader is )
*/
public DiskCacheEntry getEntry( String url, 
                                Reader is ) throws IOException { 

    String uri = URIEncoder.encode( url );
    String oldfilename = this.getRoot() + "/old." + uri;
    String filename = DiskCacheUtils.getFile( this, url ).getAbsolutePath();
    String newfilename = this.getRoot() + "/new." + uri;
    File file = new File( DiskCacheUtils.getFile( this, url ).getAbsolutePath() );
    File newfile = new File( newfilename);

    OutputStreamWriter os = new OutputStreamWriter (new FileOutputStream( newfile ), "utf-8" );

    //now process the InputStream...
    char chars[] = new char[200];

    int readCount = 0;
    while( ( readCount = is.read( chars )) > 0 ) {
        os.write(chars, 0, readCount);
    }

    is.close();
    os.close();
    
    File oldfile = new File( oldfilename);
    if(oldfile.exists())
        oldfile.delete();
    if(newfile.exists() && newfile.length() > 0) {
        file = new File( filename );
        file.renameTo(oldfile);
        newfile.renameTo(file);
    }
    try {
        if( oldfile.exists() )
            oldfile.delete();
    } catch (Exception e) {
        logger.info("Exception " + 
                 e.getMessage() + 
                 " while deleting " + oldfilename, e);
    }
    JetspeedDiskCacheEntry dce = (JetspeedDiskCacheEntry) entries.get(url.intern());
    if (dce != null )
        {
            dce.setFile( file );
            return dce;
        } else {
            return this.getEntry(url, false);
        }
    
}
 
Example 5
Project: k3po   File: RobotIT.java View source code Vote up 6 votes
@Test
public void shouldReadRegexGroupNoCapturesOK() throws Exception {
    // @formatter:off
    String script =
        "connect tcp://localhost:8080\n" +
        "connected\n" +
        "read  /Hello (.*)\\n/\n" +
        "close\n" +
        "closed\n";

    String expected = script;
    // @formatter:on

    server.bind(new InetSocketAddress("localhost", 8080));

    robot.prepareAndStart(script).await();

    accepted = server.accept();

    OutputStreamWriter writer = new OutputStreamWriter(accepted.getOutputStream());
    writer.write("Hello World\n");
    writer.flush();

    robot.finish().await();

    assertEquals(expected, robot.getObservedScript());

    assertEquals(-1, accepted.getInputStream().read());
}
 
Example 6
Project: angularjs-navigation-master-detail   File: DiskLruCache.java View source code Vote up 6 votes
/** Sets the value at [email protected] index} to [email protected] value}. */
public void set(int index, String value) throws IOException {
  Writer writer = null;
  try {
    writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
    writer.write(value);
  } finally {
    Util.closeQuietly(writer);
  }
}
 
Example 7
Project: phonegap-plugin-wizPurchase   File: DiskLruCache.java View source code Vote up 6 votes
/** Sets the value at [email protected] index} to [email protected] value}. */
public void set(int index, String value) throws IOException {
  Writer writer = null;
  try {
    writer = new OutputStreamWriter(newOutputStream(index), Util.UTF_8);
    writer.write(value);
  } finally {
    Util.closeQuietly(writer);
  }
}
 
Example 8
Project: fiji   File: AbstractInterpreter.java View source code Vote up 6 votes
private void saveHistory() {
	String path = ij.Prefs.getPrefsDir() + "/" + getClass().getName() + ".log";
	File f = new File(path);
	if (!f.getParentFile().canWrite()) {
		IJ.log("Could not save history for " + getClass().getName() + "\nat path: " + path);
		return;
	}
	Writer writer = null;
	try {
		writer = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(f)), "8859_1");

		final int MAX_LINES = 2000;

		// Write all lines up to MAX_LINES
		int first = al_lines.size() - MAX_LINES;
		if (first < 0) first = 0;
		String rep = new StringBuffer().append('\n').append(getLineCommentMark()).toString();
		String separator = getLineCommentMark() + "\n";
		for (int i=first; i<al_lines.size(); i++) {
			// Separate executed code blocks with a empty comment line:
			writer.write(separator);
			String block = (String)al_lines.get(i);
			// If block threw an Exception when executed, save it as commented out:
			if (!valid_lines.get(i)) {
				block = getLineCommentMark() + block;
				block = block.replaceAll("\n", rep);
			}
			if (!block.endsWith("\n")) block += "\n";
			writer.write(block);
		}
		writer.flush();
	} catch (Throwable e) {
		IJ.log("Could NOT save history log file!");
		IJ.log(e.toString());
	} finally {
		try {
			writer.close();
		} catch (java.io.IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
 
Example 9
Project: jentrata-msh   File: IOHandler.java View source code Vote up 6 votes
/**
 * Reads an array of bytes from a reader.
 * 
 * @param reader the reader to be read.
 * @param charset the charset used to convert the characters. 
 * @return an array of bytes read from the specified reader.
 * @throws IOException if there is IO error occurred during the operation.
 */
public static byte[] readBytes(Reader reader, Charset charset) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(out, charset); 
    pipe(reader, writer);
    byte[] bytes = out.toByteArray();
    writer.close();
    out.close();
    return bytes;
}
 
Example 10
Project: eadventure   File: StringWriter.java View source code Vote up 6 votes
public boolean write(OutputStream outputStream,
		Map<EAdString, String> strings) {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		TransformerFactory tf = TransformerFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.newDocument();

		Element mainNode = doc.createElement("resources");

		for (Entry<EAdString, String> entry : strings.entrySet()) {
			Element newElement = doc.createElement("string");
			newElement.setAttribute("name", entry.getKey().toString());
			newElement.setTextContent(entry.getValue());
			Node newNode = doc.adoptNode(newElement);
			mainNode.appendChild(newNode);
		}
		doc.adoptNode(mainNode);
		doc.appendChild(mainNode);

		Transformer transformer = tf.newTransformer();

		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
				outputStream, "UTF-8");
		transformer.transform(new DOMSource(doc), new StreamResult(
				outputStreamWriter));
		outputStreamWriter.close();

		return true;
	} catch (Exception e) {
		logger.error("Could not write strings file", e);
		return false;
	}
}
 
Example 11
Project: xface-android   File: XFileUtils.java View source code Vote up 6 votes
/**
 * ??????????
 *
 * @param filePath
 *            ???????
 * @param fileContent
 *            ???????
 * @return ????true?????false
 */
public static boolean writeFileByString(String filePath, String fileContent) {
    if (null == filePath || null == fileContent) {
        return false;
    }
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                new FileOutputStream(filePath));
        outputStreamWriter.write(fileContent, 0, fileContent.length());
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
        XLog.d(CLASS_NAME, e.getMessage());
        return false;
    }
    return true;
}
 
Example 12
Project: avaje-ebeanorm   File: DnodeReader.java View source code Vote up 6 votes
public Dnode parseXml(String str) {
    
    try {
        ByteArrayOutputStream bao = new ByteArrayOutputStream(str.length());
        OutputStreamWriter osw = new OutputStreamWriter(bao);
        
        StringReader sr = new StringReader(str);
        
        int charBufferSize = 1024;
        char[] buf = new char[charBufferSize];
        int len;
        while ((len = sr.read(buf, 0, buf.length)) != -1) {
            osw.write(buf, 0, len);
        }
        sr.close();
        osw.flush();
        osw.close();
        
        bao.flush();
        bao.close();

        InputStream is = new ByteArrayInputStream(bao.toByteArray());
        return parseXml(is);
        
    } catch (IOException ex){
        throw new RuntimeException(ex);
    }
}
 
Example 13
Project: infoeducatie-android   File: HttpHelper.java View source code Vote up 6 votes
public static HttpURLConnection createHttpUrlConnection(String path,
                                                          String method, Object body) throws IOException {
/* create a simple http url connection */
      URL url = new URL(path);
      HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
      boolean methodIsGet = method.toLowerCase().equals("get");
/* if we do a get request we must set this to false */
      ;
      httpCon.setDoOutput(!methodIsGet);
      httpCon.setRequestMethod(method);
      httpCon.setRequestProperty("Accept", "application/json");
      httpCon.setRequestProperty("Content-Type", "application/json");
      if (body != null) {
          // if we have a body add it
          OutputStreamWriter out = new OutputStreamWriter(
                  httpCon.getOutputStream());

          out.write(gson.toJson(body));
          out.close();
      }
      return httpCon;
  }
 
Example 14
Project: krypton   File: WaitStrategiesTest.java View source code Vote up 6 votes
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
	try {
		response.setHeader("Cache-Control", "no-cache");
		OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
		writer.write("<html><head/><body>");
		writer.write("<div>" + CHUNK_OF_DATA.toString() + "</div>");
		writer.flush();
		Thread.sleep(BLOCKING_TIME);
		writer.write("<div id=\"helloworld\">Hello World</div></body></html>");
		writer.close();
	} catch (InterruptedException e) {
	}
}
 
Example 15
Project: Roid-Library   File: RLFileUtil.java View source code Vote up 6 votes
/**
 * @param filename
 * @param content
 */
public void write2Sd(String filename, String content) {
    try {
        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(content);
        bw.flush();
        osw.flush();
        bw.close();
        osw.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: pentaho-metadata-editor   File: LocaleExportProgressDialog.java View source code Vote up 6 votes
public void open() throws Exception {
  IRunnableWithProgress op = new IRunnableWithProgress() {
    public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
      try {
        monitor.beginTask(Messages.getString("LocaleExportProgressDialog.USER_EXPORTING_LOCALE"), 100); //$NON-NLS-1$
        
        monitor.worked(20);
        
        monitor.subTask(Messages.getString("LocaleExportProgressDialog.USER_INITIALIZING")); //$NON-NLS-1$
        Thread.sleep(500);
        monitor.worked(5);
        
        monitor.subTask(Messages.getString("LocaleExportProgressDialog.USER_EXPORTING")); //$NON-NLS-1$
        Properties props = localizationUtility.exportLocalizedProperties(schemaMeta, locale);
        Thread.sleep(500);
        monitor.worked(40);
        
        monitor.subTask(Messages.getString("LocaleExportProgressDialog.USER_WRITING")); //$NON-NLS-1$
        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        props.store(osw, null);
        
        osw.flush();
        osw.close();
        
        fos.flush();
        fos.close();
        Thread.sleep(750);
        monitor.worked(30);

        monitor.subTask(Messages.getString("LocaleExportProgressDialog.USER_FINALIZING")); //$NON-NLS-1$
        Thread.sleep(500);
        monitor.worked(5);
        monitor.done();
      } catch (Exception e) {
        throw new InvocationTargetException(e);
      }
    }
  };
  
  ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
  pmd.run(false, false, op);
}
 
Example 17
Project: RandomActsOfKindness   File: ConnectionHandler.java View source code Vote up 6 votes
private static HttpURLConnection buildPostRequest(String url, String content) throws IOException {
    URL requestURL = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) requestURL.openConnection();
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("charset", "utf-8");

    connection.setRequestProperty("Content-Length", "" + content.getBytes().length);
    connection.setUseCaches (false);
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(content);
    writer.flush();
    writer.close();

    return connection;
}
 
Example 18
Project: android-platform-tools-base   File: LintUtilsTest.java View source code Vote up 6 votes
private static void checkEncoding(String encoding, boolean writeBom, String lineEnding)
        throws Exception {
    @SuppressWarnings("StringBufferReplaceableByString")
    StringBuilder sb = new StringBuilder();

    // Norwegian extra vowel characters such as "latin small letter a with ring above"
    String value = "\u00e6\u00d8\u00e5";
    String expected = "First line." + lineEnding + "Second line." + lineEnding
            + "Third line." + lineEnding + value + lineEnding;
    sb.append(expected);
    File file = File.createTempFile("getEncodingTest" + encoding + writeBom, ".txt");
    file.deleteOnExit();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
    OutputStreamWriter writer = new OutputStreamWriter(stream, encoding);

    if (writeBom) {
        String normalized = encoding.toLowerCase(Locale.US).replace("-", "_");
        if (normalized.equals("utf_8")) {
            stream.write(0xef);
            stream.write(0xbb);
            stream.write(0xbf);
        } else if (normalized.equals("utf_16")) {
            stream.write(0xfe);
            stream.write(0xff);
        } else if (normalized.equals("utf_16le")) {
            stream.write(0xff);
            stream.write(0xfe);
        } else if (normalized.equals("utf_32")) {
            stream.write(0x0);
            stream.write(0x0);
            stream.write(0xfe);
            stream.write(0xff);
        } else if (normalized.equals("utf_32le")) {
            stream.write(0xff);
            stream.write(0xfe);
            stream.write(0x0);
            stream.write(0x0);
        } else {
            fail("Can't write BOM for encoding " + encoding);
        }
    }
    writer.write(sb.toString());
    writer.close();

    String s = LintUtils.getEncodedString(new LintCliClient(), file);
    assertEquals(expected, s);
}
 
Example 19
Project: ics-openvpn   File: IOUtils.java View source code Vote up 6 votes
/**
 * Copy chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code> using the default character encoding of the
 * platform, and calling flush.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * <p>
 * Due to the implementation of OutputStreamWriter, this method performs a
 * flush.
 * <p>
 * This method uses [email protected] OutputStreamWriter}.
 *
 * @param input  the <code>Reader</code> to read from
 * @param output  the <code>OutputStream</code> to write to
 * @throws NullPointerException if the input or output is null
 * @throws IOException if an I/O error occurs
 * @since 1.1
 */
public static void copy(Reader input, OutputStream output)
        throws IOException {
    OutputStreamWriter out = new OutputStreamWriter(output);
    copy(input, out);
    // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    // have to flush here.
    out.flush();
}
 
Example 20
Project: ics-openvpn   File: IOUtils.java View source code Vote up 6 votes
/**
 * Copy chars from a <code>Reader</code> to bytes on an
 * <code>OutputStream</code> using the specified character encoding, and
 * calling flush.
 * <p>
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedReader</code>.
 * <p>
 * Character encoding names can be found at
 * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
 * <p>
 * Due to the implementation of OutputStreamWriter, this method performs a
 * flush.
 * <p>
 * This method uses [email protected] OutputStreamWriter}.
 *
 * @param input  the <code>Reader</code> to read from
 * @param output  the <code>OutputStream</code> to write to
 * @param encoding  the encoding to use, null means platform default
 * @throws NullPointerException if the input or output is null
 * @throws IOException if an I/O error occurs
 * @since 1.1
 */
public static void copy(Reader input, OutputStream output, String encoding)
        throws IOException {
    if (encoding == null) {
        copy(input, output);
    } else {
        OutputStreamWriter out = new OutputStreamWriter(output, encoding);
        copy(input, out);
        // XXX Unless anyone is planning on rewriting OutputStreamWriter,
        // we have to flush here.
        out.flush();
    }
}
 
Example 21
Project: k3po   File: RobotIT.java View source code Vote up 6 votes
@Test
public void shouldReadRegexGroupCapturesOK() throws Exception {
    // @formatter:off
    String script =
        "connect tcp://localhost:8080\n" +
        "connected\n" +
        "read  /Hello (?<var>.*)\\n/\n" +
        "read \"Hello \"\n" +
        "read ${var}\n" +
        "read \"\\n\"\n" +
        "close\n" +
        "closed\n";

    String expected = script;
    // @formatter:on

    server.bind(new InetSocketAddress("localhost", 8080));

    robot.prepareAndStart(script).await();

    accepted = server.accept();

    OutputStreamWriter writer = new OutputStreamWriter(accepted.getOutputStream());
    writer.write("Hello World\n");
    writer.write("Hello World\n");
    writer.flush();

    robot.finish().await();

    assertEquals(expected, robot.getObservedScript());

    assertEquals(-1, accepted.getInputStream().read());
}
 
Example 22
Project: fiji   File: WavefrontExporter.java View source code Vote up 6 votes
/** Utility method to encode text data in 8859_1. */
static public boolean saveToFile(final File f, final String data)
						throws IOException {
	if (null == f) return false;
	OutputStreamWriter dos = new OutputStreamWriter(
		new BufferedOutputStream(
		 // encoding in Latin 1 (for macosx not to mess around
		new FileOutputStream(f), data.length()), "8859_1");
	dos.write(data, 0, data.length());
	dos.flush();
	return true;
}
 
Example 23
Project: JerseyTest   File: JSONListElementProvider.java View source code Vote up 6 votes
@Override
public final void writeList(Class<?> elementType, Collection<?> t, MediaType mediaType, Charset c, Marshaller m, OutputStream entityStream) throws JAXBException, IOException {
    final OutputStreamWriter osw = new OutputStreamWriter(entityStream, c);

    JSONConfiguration origJsonConfig = JSONConfiguration.DEFAULT;
    if (m instanceof JSONConfigurated) {
        origJsonConfig = ((JSONConfigurated)m).getJSONConfiguration();
    }

    final JSONConfiguration unwrappingJsonConfig =
            JSONConfiguration.createJSONConfigurationWithRootUnwrapping(origJsonConfig, true);

    final XMLStreamWriter jxsw = Stax2JsonFactory.createWriter(osw, unwrappingJsonConfig, true);
    final String invisibleRootName = getRootElementName(elementType);
    final String elementName = getElementName(elementType);

    try {
        if (!origJsonConfig.isRootUnwrapping()) {
          osw.append(String.format("{\"%s\":", elementName));
          osw.flush();
        }
        jxsw.writeStartDocument();
        jxsw.writeStartElement(invisibleRootName);
        for (Object o : t) {
                m.marshal(o, jxsw);
        }
        jxsw.writeEndElement();
        jxsw.writeEndDocument();
        jxsw.flush();
        if (!origJsonConfig.isRootUnwrapping()) {
          osw.append("}");
          osw.flush();
        }
    } catch (XMLStreamException ex) {
        Logger.getLogger(JSONListElementProvider.class.getName()).log(Level.SEVERE, null, ex);
        throw new JAXBException(ex.getMessage(), ex);
    }
}
 
Example 24
Project: js-invulnerable   File: CompileTask.java View source code Vote up 6 votes
private void writeResult(String source) {
  if (this.outputFile.getParentFile().mkdirs()) {
    log("Created missing parent directory " +
        this.outputFile.getParentFile(), Project.MSG_DEBUG);
  }

  try {
    OutputStreamWriter out = new OutputStreamWriter(
        new FileOutputStream(this.outputFile), outputEncoding);
    out.append(source);
    out.flush();
    out.close();
  } catch (IOException e) {
    throw new BuildException(e);
  }

  log("Compiled javascript written to " + this.outputFile.getAbsolutePath(),
      Project.MSG_DEBUG);
}
 
Example 25
Project: zeppelin   File: InterpreterFactory.java View source code Vote up 6 votes
private void saveToFile() throws IOException {
  String jsonString;

  synchronized (interpreterSettings) {
    InterpreterInfoSaving info = new InterpreterInfoSaving();
    info.interpreterBindings = interpreterBindings;
    info.interpreterSettings = interpreterSettings;

    jsonString = gson.toJson(info);
  }

  File settingFile = new File(conf.getInterpreterSettingPath());
  if (!settingFile.exists()) {
    settingFile.createNewFile();
  }

  FileOutputStream fos = new FileOutputStream(settingFile, false);
  OutputStreamWriter out = new OutputStreamWriter(fos);
  out.append(jsonString);
  out.close();
  fos.close();
}
 
Example 26
Project: cvRecognition   File: input.java View source code Vote up 6 votes
private void writeToFile(String data) {
//        Toast.makeText(getApplicationContext(),"asdasd", Toast.LENGTH_SHORT).show();
        try {
            //Toast.makeText(getApplicationContext(),"in try", Toast.LENGTH_SHORT).show();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fName + ".txt", Context.MODE_PRIVATE));
            outputStreamWriter.append(data);
            outputStreamWriter.close();
           //    Toast.makeText(getApplicationContext(), "data written", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            //Toast.makeText(getApplicationContext(),"write failed", Toast.LENGTH_LONG).show();
            Log.e("Exception", "File write failed: " + e.toString());
        }
    }
 
Example 27
Project: jgit   File: InfoRefsServlet.java View source code Vote up 6 votes
public void doGet(final HttpServletRequest req,
		final HttpServletResponse rsp) throws IOException {
	// Assume a dumb client and send back the dumb client
	// version of the info/refs file.
	rsp.setContentType(HttpSupport.TEXT_PLAIN);
	rsp.setCharacterEncoding(Constants.CHARACTER_ENCODING);

	final Repository db = getRepository(req);
	final OutputStreamWriter out = new OutputStreamWriter(
			new SmartOutputStream(req, rsp), Constants.CHARSET);
	final RefAdvertiser adv = new RefAdvertiser() {
		@Override
		protected void writeOne(final CharSequence line) throws IOException {
			// Whoever decided that info/refs should use a different
			// delimiter than the native git:// protocol shouldn't
			// be allowed to design this sort of stuff. :-(
			out.append(line.toString().replace(' ', '\t'));
		}

		@Override
		protected void end() {
			// No end marker required for info/refs format.
		}
	};
	adv.init(db);
	adv.setDerefTags(true);

	Map<String, Ref> refs = db.getAllRefs();
	refs.remove(Constants.HEAD);
	adv.send(refs);
	out.close();
}
 
Example 28
Project: ecologylabFundamental   File: NIOClient.java View source code Vote up 6 votes
private byte[] compress(StringBuilder src) throws IOException
{
	ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(1024);
	DeflaterOutputStream zipStream = new DeflaterOutputStream(byteArrayStream);
	OutputStreamWriter encodingStream = new OutputStreamWriter(zipStream, CHARSET);

	encodingStream.append(src);
	encodingStream.flush();
	zipStream.flush();
	zipStream.finish();
	byteArrayStream.flush();

	return byteArrayStream.toByteArray();
}
 
Example 29
Project: emf.compare   File: GitTestRepository.java View source code Vote up 6 votes
/**
 * Appends content to given file.
 *
 * @param file
 * @param content
 * @param append
 *            if true, then bytes will be written to the end of the file rather than the beginning
 * @throws IOException
 */
public void appendFileContent(File file, String content, boolean append) throws IOException {
	Writer fw = null;
	try {
		fw = new OutputStreamWriter(new FileOutputStream(file, append), "UTF-8");
		fw.append(content);
	} finally {
		if (fw != null) {
			fw.close();
		}
	}
}
 
Example 30
Project: picard-tools   File: BCF2Writer.java View source code Vote up 6 votes
@Override
public void writeHeader(VCFHeader header) {
    // make sure the header is sorted correctly
    header = new VCFHeader(header.getMetaDataInSortedOrder(), header.getGenotypeSamples());

    // create the config offsets map
    if ( header.getContigLines().isEmpty() ) {
        if ( ALLOW_MISSING_CONTIG_LINES ) {
            if ( GeneralUtils.DEBUG_MODE_ENABLED ) {
                System.err.println("No contig dictionary found in header, falling back to reference sequence dictionary");
            }
            createContigDictionary(VCFUtils.makeContigHeaderLines(getRefDict(), null));
        } else {
            throw new IllegalStateException("Cannot write BCF2 file with missing contig lines");
        }
    } else {
        createContigDictionary(header.getContigLines());
    }

    // set up the map from dictionary string values -> offset
    final ArrayList<String> dict = BCF2Utils.makeDictionary(header);
    for ( int i = 0; i < dict.size(); i++ ) {
        stringDictionaryMap.put(dict.get(i), i);
    }

    sampleNames = header.getGenotypeSamples().toArray(new String[header.getNGenotypeSamples()]);

    // setup the field encodings
    fieldManager.setup(header, encoder, stringDictionaryMap);

    try {
        // write out the header into a byte stream, get its length, and write everything to the file
        final ByteArrayOutputStream capture = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(capture);
        this.header = VCFWriter.writeHeader(header, writer, doNotWriteGenotypes, VCFWriter.getVersionLine(), "BCF2 stream");
        writer.append('\0'); // the header is null terminated by a byte
        writer.close();

        final byte[] headerBytes = capture.toByteArray();
        new BCFVersion(MAJOR_VERSION, MINOR_VERSION).write(outputStream);
        BCF2Type.INT32.write(headerBytes.length, outputStream);
        outputStream.write(headerBytes);
    } catch (IOException e) {
        throw new RuntimeException("BCF2 stream: Got IOException while trying to write BCF2 header", e);
    }
}
 
Example 31
Project: new-campus-app   File: Utils.java View source code Vote up 6 votes
/**
	 * Puts a .nomedia file into each directory listed, so the images don't 
	 * appear in the Gallery.
	 * 
	 * <pre>
	 * @throws Exception
	 * </pre>
	 */
	
	public static void ensureImagesAreNotIndexed() throws Exception{
//		ArrayList<String> directoriesNotToIndex = new ArrayList<String>();
//		directoriesNotToIndex.add("rss/cache");
//		directoriesNotToIndex.add("feeds/cache");
//		directoriesNotToIndex.add("gallery/cache");
		String[] directoriesNotToIndex ={"organisations/cache","links/cache","rss/cache","feeds/cache", "gallery/cache","news/cache"};
		for (String directory : directoriesNotToIndex){
			File file = new File(getCacheDir(directory)+".nomedia");
			if(!file.exists()){
				file.createNewFile();
				FileOutputStream fOut = new FileOutputStream(file);
				OutputStreamWriter myOutWriter = 
										new OutputStreamWriter(fOut);
				myOutWriter.append("1");
				myOutWriter.close();
				fOut.close();
			}
		}
	}
 
Example 32
Project: wicket-pivot   File: PivotCsvExporter.java View source code Vote up 6 votes
@Override	
public void exportPivot(PivotModel pivotModel, OutputStream outputStream) throws IOException {
	PivotTableRenderModel renderModel = PivotTableRenderModel.create(pivotModel);

	OutputStreamWriter out = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));
	Map<Integer, Integer> rowSpanMap = new HashMap<Integer, Integer>();

	for (RenderRow row : renderModel.getAllRenderRows()) {
		int col = 0;
		for (RenderCell cell : row.getRenderCells()) {
			/*
			 * Check if we currently have a rowspan at this column from the
			 * parent row. We only support a colspan of 1 at the moment
			 * here, if rowspan > 1
			 */
			Integer rowSpan = rowSpanMap.get(col);
			if (rowSpan != null) {
				rowSpan--;
				if (rowSpan == 0)
					rowSpanMap.remove(col);
				else
					rowSpanMap.put(col, rowSpan);
				col++;
				out.append(seperator);
			}

			/*
			 * Output the Value
			 */
			Object rawValue = cell.getRawValue();
			if (rawValue != null)
				out.append(String.valueOf(rawValue));
			out.append(seperator);
			if (cell.getRowspan() > 1)
				rowSpanMap.put(col, cell.getRowspan() - 1);
			col++;

			/*
			 * We only support colspan _OR_ rowspan. The current PivotTable
			 * also doesnt have rowspan and colspan at the same time.
			 */
			for (int i = 1; i < cell.getColspan(); i++) {
				out.append(seperator);
				col++;
			}
		}
		out.append("\n");
	}
	out.flush();
}
 
Example 33
Project: closure-compiler-inline   File: CompileTask.java View source code Vote up 6 votes
private void writeResult(String source) {
  if (this.outputFile.getParentFile().mkdirs()) {
    log("Created missing parent directory " +
        this.outputFile.getParentFile(), Project.MSG_DEBUG);
  }

  try {
    OutputStreamWriter out = new OutputStreamWriter(
        new FileOutputStream(this.outputFile), outputEncoding);
    out.append(source);
    out.flush();
    out.close();
  } catch (IOException e) {
    throw new BuildException(e);
  }

  log("Compiled JavaScript written to " + this.outputFile.getAbsolutePath(),
      Project.MSG_DEBUG);
}
 
Example 34
Project: praxis-live   File: PXJDataObject.java View source code Vote up 6 votes
private FileObject constructProxy() throws Exception {

        FileSystem fs = FileUtil.createMemoryFileSystem();
        FileObject f = fs.getRoot().createData(pxjFile.getName(), "java");
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(f.getOutputStream());
            writer.append(constructProxyContent());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        f.setAttribute(PXJ_DOB_KEY, this);
        f.addFileChangeListener(new ProxyListener());
        return f;
    }
 
Example 35
Project: node-go-better-than-random   File: StringUtil.java View source code Vote up 6 votes
/** Get default encoding. */
public static String getDefaultEncoding()
{
    String encoding = System.getProperty("file.encoding");
    // Java 1.5 docs for System.getProperties do not guarantee the
    // existance of file.encoding
    if (encoding != null)
        return encoding;
    OutputStreamWriter out =
        new OutputStreamWriter(new ByteArrayOutputStream());
    return out.getEncoding();
}
 
Example 36
Project: extreme-fishbowl   File: FileWriterWithEncodingTest.java View source code Vote up 6 votes
public void setUp() {
    File encodingFinder = new File(getTestDirectory(), "finder.txt");
    OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(new FileOutputStream(encodingFinder));
        defaultEncoding = out.getEncoding();
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
    file1 = new File(getTestDirectory(), "testfile1.txt");
    file2 = new File(getTestDirectory(), "testfile2.txt");
    char[] arr = new char[1024];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = (char) i;
    }
    textContent = new String(arr);
}
 
Example 37
Project: open-mika   File: OutputStreamWriterTest.java View source code Vote up 6 votes
public void testGetEncoding_NotHistorical() {
    OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(new ByteArrayOutputStream(),
                "UTF-16BE");
    } catch (UnsupportedEncodingException e) {
        // ok
    }
    String result = out.getEncoding();
    assertEquals("UnicodeBigUnmarked", result);
}
 
Example 38
Project: ez-vcard   File: FoldedLineWriter.java View source code Vote up 6 votes
/**
 * Gets the writer's character encoding.
 * @return the writer's character encoding or null if undefined
 */
public Charset getEncoding() {
	if (!(writer instanceof OutputStreamWriter)) {
		return null;
	}

	OutputStreamWriter osw = (OutputStreamWriter) writer;
	String charsetStr = osw.getEncoding();
	return (charsetStr == null) ? null : Charset.forName(charsetStr);
}
 
Example 39
Project: Maven-Archetype   File: TemplateDescriptor.java View source code Vote up 6 votes
/**
 * Returns the canonical name of the default character encoding of this Java
 * virtual machine.
 *
 * @return the name of the default character encoding.
 */
private static String getDefaultEncoding()
{
    String name = System.getProperty( "file.encoding" );

    if ( name == null )
    {
        OutputStreamWriter out = new OutputStreamWriter( System.out );

        name = out.getEncoding();
    }

    name = Charset.forName( name ).name();

    return name;
}
 
Example 40
Project: GpsPrune   File: XmlUtils.java View source code Vote up 6 votes
/**
 * Get the default system encoding using a writer
 * @param inWriter writer object
 * @return string defining encoding
 */
public static String getEncoding(OutputStreamWriter inWriter)
{
	String encoding = inWriter.getEncoding();
	try {
		encoding =  Charset.forName(encoding).name();
	}
	catch (Exception e) {} // ignore failure to find encoding
	return encoding;
}
 
Example 41
Project: jacorb   File: CodeSet.java View source code Vote up 6 votes
private static String getDefaultEncoding()
{
    // See http://java.sun.com/j2se/1.4.1/docs/guide/intl/encoding.doc.html for
    // a list of encodings and their canonical names.
    //
    // http://developer.java.sun.com/developer/bugParade/bugs/4772857.html
    //
    // This allows me to get the actual canonical name of the encoding as the
    // System property may differ depending upon locale and OS.
    OutputStreamWriter defaultStream = new OutputStreamWriter( new ByteArrayOutputStream() );
    String sysenc = defaultStream.getEncoding();
    try
        {
            defaultStream.close();
        }
        catch( IOException e ) {}
    return sysenc;
}
 
Example 42
Project: ApacheCommonsIO-for-Android   File: FileWriterWithEncodingTest.java View source code Vote up 6 votes
@Override
public void setUp() {
    File encodingFinder = new File(getTestDirectory(), "finder.txt");
    OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(new FileOutputStream(encodingFinder));
        defaultEncoding = out.getEncoding();
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
    file1 = new File(getTestDirectory(), "testfile1.txt");
    file2 = new File(getTestDirectory(), "testfile2.txt");
    char[] arr = new char[1024];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = (char) i;
    }
    textContent = new String(arr);
}
 
Example 43
Project: AsyncWorldEdit   File: MetricsLite.java View source code Vote up 5 votes
/**
 * Generic method that posts a plugin to the metrics website
 */
private void postPlugin(boolean isPing) throws IOException {
    // The plugin's description file containg all of the plugin data such as name, version, author, etc
    final PluginDescriptionFile description = plugin.getDescription();

    // Construct the post data
    final StringBuilder data = new StringBuilder();
    data.append(encode("guid")).append('=').append(encode(guid));
    encodeDataPair(data, "version", description.getVersion());
    encodeDataPair(data, "server", Bukkit.getVersion());
    encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().size()));
    encodeDataPair(data, "revision", String.valueOf(REVISION));

    // If we're pinging, append it
    if (isPing) {
        encodeDataPair(data, "ping", "true");
    }

    // Create the url
    URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(plugin.getDescription().getName())));

    // Connect to the website
    URLConnection connection;

    // Mineshafter creates a socks proxy, so we can safely bypass it
    // It does not reroute POST requests so we need to go around it
    if (isMineshafterPresent()) {
        connection = url.openConnection(Proxy.NO_PROXY);
    } else {
        connection = url.openConnection();
    }

    connection.setDoOutput(true);

    // Write the data
    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(data.toString());
    writer.flush();

    // Now read the response
    final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final String response = reader.readLine();

    // close resources
    writer.close();
    reader.close();

    if (response == null || response.startsWith("ERR")) {
        throw new IOException(response); //Throw the exception
    }
    //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right
}
 
Example 44
Project: molgenis   File: GsonHttpMessageConverter.java View source code Vote up 5 votes
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException
{

	OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(),
			getCharset(outputMessage.getHeaders()));

	String callback = getCallbackParam();
	if (callback != null)
	{
		// this is a JSONP (JSON with padding) request
		writer.append(callback).append('(');
	}

	try
	{
		Type typeOfSrc = getType();

		if (LOG.isTraceEnabled())
		{
			StringBuilder sb = new StringBuilder();
			if (this.prefixJson)
			{
				sb.append("{} && ");
			}

			if (typeOfSrc != null)
			{
				sb.append(gson.toJson(o, typeOfSrc));
			}
			else
			{
				sb.append(gson.toJson(o));
			}

			LOG.debug("Json response:\n" + sb.toString());
			writer.write(sb.toString());
		}
		else
		{
			if (this.prefixJson)
			{
				writer.append("{} && ");
			}

			if (typeOfSrc != null)
			{
				this.gson.toJson(o, typeOfSrc, writer);
			}
			else
			{
				this.gson.toJson(o, writer);
			}
		}

		if (callback != null)
		{
			// this is a JSONP (JSON with padding) request
			writer.append(')');
		}
	}
	catch (JsonIOException ex)
	{
		throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
	}
	finally
	{
		IOUtils.closeQuietly(writer);
	}

}
 
Example 45
Project: ManagedRuntimeInitiative   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 46
Project: openjdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 47
Project: openjdk8-jdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 48
Project: jdk7-jdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 49
Project: jdk7u-jdk   File: Encodings.java View source code Vote up 5 votes
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}