Java Code Examples for java.io.OutputStream

The following are top voted examples for showing how to use java.io.OutputStream. 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: richfaces   File: FileManipulation.java View source code 8 votes vote down vote up
/**
 * Utility method for copying file
 * 
 * @param srcFile - source file
 * @param destFile - destination file
 */
public static void copyFile(File srcFile, File destFile) throws IOException {
    if (!srcFile.getPath().toLowerCase().endsWith(JPG) && !srcFile.getPath().toLowerCase().endsWith(JPEG)) {
        return;
    }
    final InputStream in = new FileInputStream(srcFile);
    final OutputStream out = new FileOutputStream(destFile);
    try {
        long millis = System.currentTimeMillis();
        CRC32 checksum;
        if (VERIFY) {
            checksum = new CRC32();
            checksum.reset();
        }
        final byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = in.read(buffer);
        while (bytesRead >= 0) {
            if (VERIFY) {
                checksum.update(buffer, 0, bytesRead);
            }
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer);
        }
        if (CLOCK) {
            millis = System.currentTimeMillis() - millis;
            // comment for now, kinda clogs the output console
            // System.out.println("Copy file '" + srcFile.getPath() + "' on " + millis / 1000L + " second(s)");
        }
    } catch (IOException e) {
        throw e;
    } finally {
        out.close();
        in.close();
    }
}
 
Example 2
Project: sslcertx   File: ParameterWriter.java View source code 6 votes vote down vote up
public static void write(OutputStream out, InputStream is, boolean noBackslashEscapes, boolean isText) throws IOException{
    if (isText) {
        out.write(QUOTE);
    } else {
        out.write(BINARY_INTRODUCER);
    }
    byte[] buffer = new byte[1024];
    int len;
    while ((len = is.read(buffer)) >= 0) {
        writeBytesEscaped(out, buffer, len, noBackslashEscapes);
    }
    out.write(QUOTE);
}
 
Example 3
Project: sslcertx   File: ParameterWriter.java View source code 6 votes vote down vote up
public static void write(OutputStream out, InputStream is, long length, boolean noBackslashEscapes, boolean isText) throws IOException{
    if (isText) {
        out.write(QUOTE);
    } else {
        out.write(BINARY_INTRODUCER);
    }
    byte[] buffer = new byte[1024];
    long bytesLeft = length;
    int len;

    for (;;) {
        int bytesToRead = (int)Math.min(bytesLeft, buffer.length);
        if(bytesToRead == 0)
            break;
        len = is.read(buffer,0, bytesToRead);
        if (len <= 0)
            break;
        writeBytesEscaped(out, buffer, len, noBackslashEscapes);
        bytesLeft -= len;
    }
    out.write(QUOTE);
}
 
Example 4
Project: sslcertx   File: ParameterWriter.java View source code 6 votes vote down vote up
public static void write(OutputStream out, java.io.Reader reader, boolean noBackslashEscapes) throws IOException {
    out.write(QUOTE);
    char[] buffer = new char[1024];
    int len;
    while ((len = reader.read(buffer)) >= 0) {
         writeBytesEscaped(out, new String(buffer,0, len).getBytes(UTF8), noBackslashEscapes);
    }
    out.write(QUOTE);
}
 
Example 5
Project: sslcertx   File: ParameterWriter.java View source code 6 votes vote down vote up
public static void write(OutputStream out, java.io.Reader reader, long length, boolean noBackslashEscapes)
         throws IOException{
    out.write(QUOTE);
    char[] buffer = new char[1024];
    long charsLeft = length;
    int len;

    for (;;) {
        int charsToRead = (int)Math.min(charsLeft, buffer.length);
        if(charsToRead == 0)
            break;
        len = reader.read(buffer,0, charsToRead);
        if (len <= 0)
            break;
        byte[] bytes = new String(buffer, 0, len).getBytes(UTF8);
        writeBytesEscaped(out, bytes, bytes.length, noBackslashEscapes);
        charsLeft -= len;
    }
    out.write(QUOTE);
}
 
Example 6
Project: jentrata-msh   File: AS2Message.java View source code 6 votes vote down vote up
/**
 * Writes the message to the given output stream.
 * 
 * @param outs the output stream to be written.
 * @throws AS2MessageException if unable to write the message.
 */
public void writeTo(OutputStream outs) throws AS2MessageException {
    try {
        Enumeration enumeration = headers.getAllHeaderLines();
        while (enumeration.hasMoreElements()) {
            outs.write((enumeration.nextElement() + "\r\n").getBytes());
        }
        bodyPart.writeTo(outs);
        outs.flush();
    } catch (Exception e) {
        throw new AS2MessageException("Unable to write message", e);
    }
}
 
Example 7
Project: jentrata-msh   File: AS2Message.java View source code 6 votes vote down vote up
/**
 * Writes the message to the given output stream.
 * 
 * @param outs the output stream to be written.
 * @throws AS2MessageException if unable to write the message.
 */
public void writeTo(OutputStream outs) throws AS2MessageException {
    try {
        Enumeration enumeration = headers.getAllHeaderLines();
        while (enumeration.hasMoreElements()) {
            outs.write((enumeration.nextElement() + "\r\n").getBytes());
        }
        bodyPart.writeTo(outs);
        outs.flush();
    } catch (Exception e) {
        throw new AS2MessageException("Unable to write message", e);
    }
}
 
Example 8
Project: jentrata-msh   File: IOHandler.java View source code 6 votes vote down vote up
/**
 * Pipes an input stream to an output stream. 
 * 
 * @param ins the input stream to be read.
 * @param out the output stream to be written.
 * @throws IOException if there is IO error occurred during the operation.
 */
public static void pipe(InputStream ins, OutputStream out) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    int len = ins.read(buffer);
    while (len != -1) {
        out.write(buffer, 0, len);
        len = ins.read(buffer);
    }
    out.flush();
}
 
Example 9
Project: jentrata-msh   File: ByteStreamDataContentHandler.java View source code 6 votes vote down vote up
/**
 * Converts the object to a byte stream of the specified MIME type and 
 * write it to the output stream. 
 * 
 * @param obj the object to be converted.
 * @param mimeType the requested MIME type of the resulting byte stream.
 * @param os the output stream into which to write the converted byte stream. 
 * @throws IOException if unable to convert the given object.
 * @see javax.activation.DataContentHandler#writeTo(java.lang.Object, java.lang.String, java.io.OutputStream)
 */
public void writeTo(Object obj, String mimeType, OutputStream os)
    throws IOException {
    
    byte[] bytes = null;
    if (obj instanceof InputStream) {
        IOHandler.pipe((InputStream) obj, os);
        return;
    }
    else if (obj instanceof DataSource) {
        IOHandler.pipe(((DataSource)obj).getInputStream(), os);
        return;
    }
    else if (obj instanceof byte[]) {
        bytes = (byte[])obj;
    } 
    else if (obj instanceof String) {
        bytes = ((String)obj).getBytes();
    }
    else {
        try {
            String methodName = "writeTo"; 
            Class[] outsParam = new Class[]{OutputStream.class};
            Instance instance = new Instance(obj);
            if (instance.isMethodExist(methodName, outsParam)) {
                instance.invoke(methodName, outsParam, new Object[]{os});
            }
            return;
        }
        catch (Exception e) {
            bytes = null;
        }
    }
    
    if (bytes==null) {
        throw new IOException("Unable to convert object of type " + (obj==null? "null":obj.getClass().getName()));
    }
    else {
        os.write(bytes);
    }
}
 
Example 10
Project: aws-toolkit-eclipse   File: Startup.java View source code 6 votes vote down vote up
/**
 * Records a list of the detected plugins (and their versions) which
 * contribute to the AWS Toolkit Overview view through the core plugin's
 * overview extension point.
 */
private void recordOverviewContributors() {
    File dataFile = getPropertiesFile();
    Properties properties = new Properties();

    Map<String, String> contributions = findOverviewContributors();
    for (String pluginName : contributions.keySet()) {
        String pluginVersion = contributions.get(pluginName);
        properties.put(pluginName, pluginVersion);
    }

    OutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream(dataFile);
        properties.store(outputStream, null);
    } catch (IOException e) {
        String errorMessage = "Unable to record registered components: " + e.getMessage();
        Status status = new Status(Status.ERROR, AwsToolkitCore.PLUGIN_ID, errorMessage, e);
        StatusManager.getManager().handle(status, StatusManager.LOG);
    } finally {
        try {outputStream.close();} catch (IOException ioe) {}
    }
}
 
Example 11
Project: apache-james-mime4j-groundhog   File: MessageWriter.java View source code 6 votes vote down vote up
/**
 * Write the specified <code>Entity</code> to the specified
 * <code>OutputStream</code>.
 * 
 * @param entity
 *            the <code>Entity</code> to write.
 * @param out
 *            the OutputStream to write to.
 * @throws IOException
 *             if an I/O error occurs.
 */
public void writeEntity(Entity entity, OutputStream out) throws IOException {
    final Header header = entity.getHeader();
    if (header == null)
        throw new IllegalArgumentException("Missing header");

    writeHeader(header, out);

    final Body body = entity.getBody();
    if (body == null)
        throw new IllegalArgumentException("Missing body");

    boolean binaryBody = body instanceof BinaryBody;
    OutputStream encOut = encodeStream(out, entity
            .getContentTransferEncoding(), binaryBody);

    writeBody(body, encOut);

    // close if wrapped (base64 or quoted-printable)
    if (encOut != out)
        encOut.close();
}
 
Example 12
Project: iswc2012metadata   File: ToolIO.java View source code 6 votes vote down vote up
/**
 * pipe a list of bytes into a file 
 * 
 * @param data
 * @param f
 * @return true if succeed.
 * @throws Sw4jException
 */
public static void pipeBytesToFile(byte[] data, File f, boolean bAppend, boolean bGzip)
throws Sw4jException {

	try {
		OutputStream out = prepareFileOutputStream(f, bAppend, bGzip);
		if (data.length>0){
			out.write(data);
		}
		out.flush();
		out.close();
		return ;
	} catch (IOException e) {
		Sw4jException e1 = new Sw4jException(Sw4jMessage.STATE_FATAL, e);
		getLogger().error(e1.getMessage());
		throw e1;
	}
}
 
Example 13
Project: dlna   File: HttpServer.java View source code 6 votes vote down vote up
/**
 * Retrieves the content of a sent file and saves it
 * to a temporary file.
 * The full path to the saved file is returned.
**/
private String saveTmpFile(byte[] b, int offset, int len)
{
	String path = "";
	if (len > 0)
	{
		String tmpdir = System.getProperty("java.io.tmpdir");
		try {
			File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir));
			OutputStream fstream = new FileOutputStream(temp);
			fstream.write(b, offset, len);
			fstream.close();
			path = temp.getAbsolutePath();
		} catch (Exception e) { // Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}
	return path;
}
 
Example 14
Project: Gui2Go   File: FileHelper.java View source code 6 votes vote down vote up
public static void copyDirectory(File srcPath, File dstPath)
			throws IOException
	{
		if (srcPath.isDirectory()) {
			if (!dstPath.exists()) {
				dstPath.mkdir();
			}

			String files[] = srcPath.list();
			for (int i = 0; i < files.length; i++) {
				copyDirectory(new File(srcPath, files[i]), new File(dstPath,
						files[i]));
			}
		} else {
			if (!srcPath.exists()) {
//				Log.d("Copy failure", "File or directory does not exist.");
			} else {
				InputStream in = new FileInputStream(srcPath);
				OutputStream out = new FileOutputStream(dstPath);

				// Transfer bytes from in to out
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			}
		}
		System.out.println("Directory copied.");
	}
 
Example 15
Project: JAME   File: LibraryService.java View source code 6 votes vote down vote up
/**
 * @param dataRow
 * @param file
 * @throws RenderServiceException
 */
public void exportClip(final RenderClipDataRow dataRow, final File file) throws RenderServiceException {
	try {
		final TwisterClipXMLImporter importer = new TwisterClipXMLImporter();
		final InputStream is = clipService.getInputStream(dataRow.getClipId());
		Document doc = XML.loadDocument(is, "twister-clip.xml");
		final TwisterClip clip = importer.importFromElement(doc.getDocumentElement());
		is.close();
		final TwisterClipXMLExporter exporter = new TwisterClipXMLExporter();
		doc = XML.createDocument();
		final XMLNodeBuilder builder = XML.createDefaultXMLNodeBuilder(doc);
		final Element element = exporter.exportToElement(clip, builder);
		doc.appendChild(element);
		final OutputStream os = new FileOutputStream(file);
		XML.saveDocument(os, "twister-clip.xml", doc);
		os.close();
	}
	catch (final Exception e) {
		throw new RenderServiceException(e);
	}
}
 
Example 16
Project: jbosgi   File: IOUtils.java View source code 6 votes vote down vote up
public static void copyStream(OutputStream output, InputStream input) throws IOException {
    try {
        byte[] bytes = new byte[1024];
        int r = input.read(bytes);
        while (r > 0) {
            output.write(bytes, 0, r);
            r = input.read(bytes);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        input.close();
        output.close();
    }
}
 
Example 17
Project: virgo.kernel   File: ResourceServlet.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String rawRequestPath = request.getPathInfo();
	
	if (log.isDebugEnabled()) {
		log.debug("Attempting to GET resource: " + rawRequestPath);
	}
	
	URL[] resources = getRequestResourceURLs(request);
	if (resources == null || resources.length == 0) {
		if (log.isDebugEnabled()) {
			log.debug("Resource not found: " + rawRequestPath);
		}
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return;
	}
	
	prepareResourcesResponse(response, resources, rawRequestPath);
	OutputStream out = selectOutputStream(request, response, resources, rawRequestPath);
	try {
		for (int i = 0; i < resources.length; i++) {
			URLConnection resourceConn = resources[i].openConnection();
			InputStream in = resourceConn.getInputStream();
			try {
				byte[] buffer = new byte[1024];
				int bytesRead = -1;
				while ((bytesRead = in.read(buffer)) != -1) {
					out.write(buffer, 0, bytesRead);
				}
			} finally {
				in.close();
			}
		}
	} finally {
		out.close();
	}
}
 
Example 18
Project: AndroidLibraryProject   File: JavaDESEncryption.java View source code 6 votes vote down vote up
private static void writeBytes(InputStream input, OutputStream output)
		throws IOException {
	byte[] writeBuffer = new byte[512];
	int readBytes = 0;

	while ((readBytes = input.read(writeBuffer)) >= 0) {
		output.write(writeBuffer, 0, readBytes);
	}

	output.close();
	input.close();
}
 
Example 19
Project: phonegap-geolocation   File: CordovaResourceApi.java View source code 6 votes vote down vote up
public void copyResource(OpenForReadResult input, OutputStream outputStream) throws IOException {
    assertBackgroundThread();
    try {
        InputStream inputStream = input.inputStream;
        if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
            FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
            FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
            long offset = 0;
            long length = input.length;
            if (input.assetFd != null) {
                offset = input.assetFd.getStartOffset();
            }
            outChannel.transferFrom(inChannel, offset, length);
        } else {
            final int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];
            
            for (;;) {
                int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
                
                if (bytesRead <= 0) {
                    break;
                }
                outputStream.write(buffer, 0, bytesRead);
            }
        }            
    } finally {
        input.inputStream.close();
        if (outputStream != null) {
            outputStream.close();
        }
    }
}
 
Example 20
Project: BioWiki   File: BioWikiDB.java View source code 6 votes vote down vote up
protected void copyDatabase() {
    String copyFrom = db.getPath();
    String copyTo = BioWiki.getContext().getExternalFilesDir(null).getAbsolutePath() + "/" + DATABASE_NAME + ".db";

    try {
        InputStream input = new FileInputStream(copyFrom);
        OutputStream output = new FileOutputStream(copyTo);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0)
            output.write(buffer, 0, length);

        output.flush();
        output.close();
        input.close();
    } catch (IOException e) {
        AppLog.e(AppLog.T.DB, "failed to copy database", e);
    }
}
 
Example 21
Project: breakout   File: BuilderGenerator.java View source code 6 votes vote down vote up
private static void copy( File src , File dest ) throws Exception
{
	InputStream in = new FileInputStream( src );
	OutputStream out = new FileOutputStream( dest );
	
	byte[ ] bytes = new byte[ 1024 ];
	
	int count;
	while( ( count = in.read( bytes ) ) >= 0 )
	{
		out.write( bytes , 0 , count );
	}
	
	out.flush( );
	out.close( );
	in.close( );
}
 
Example 22
Project: aws-toolkit-eclipse   File: RemoteCommandUtils.java View source code 6 votes vote down vote up
/**
 * Sends the SCP file header for the specified file to the specified output
 * stream.
 *
 * @param localFile
 *            The file to generate the header for.
 * @param out
 *            The output stream to write the header to.
 * @throws IOException
 *             If there are any problems writing the header.
 */
private void sendFileHeader(String localFile, OutputStream out) throws IOException {
    long filesize = (new File(localFile)).length();
    String command = "C0644 " + filesize + " ";
    command += localFile.substring(localFile.lastIndexOf('/') + 1);
    command += "\n";

    out.write(command.getBytes());
    out.flush();
}
 
Example 23
Project: netlib   File: HttpURLConnection.java View source code 6 votes vote down vote up
@Override
public void close () throws IOException {
    if (closed) {
        return;
    }
    closed = true;
    if (expected != -1L) {
        /* not chunked */
        if (written != expected) {
            error = true;
            errorExcp = new IOException ("insufficient data written");
            out.close ();
            throw errorExcp;
        }
        super.flush(); /* can't close the socket */
    } else {
        /* chunked */
        super.close (); /* force final chunk to be written */
        /* trailing \r\n */
        OutputStream o = http.getOutputStream();
        o.write ('\r');
        o.write ('\n');
        o.flush();
    }
}
 
Example 24
Project: speechalyzer   File: ClientHttpRequest.java View source code 6 votes vote down vote up
private static void pipe(InputStream in, OutputStream out) throws IOException {
  byte[] buf = new byte[500000];
  int nread;
  int navailable;
  int total = 0;
  synchronized (in) {
    while((nread = in.read(buf, 0, buf.length)) >= 0) {
      out.write(buf, 0, nread);
      total += nread;
    }
  }
  out.flush();
  buf = null;
  in.close();
}
 
Example 25
Project: jena   File: Query.java View source code 6 votes vote down vote up
/** Output the query
 * 
 * @param out     OutputStream
 * @param syntax  Syntax URI
 */

public void serialize(OutputStream out, Syntax syntax) { 
    IndentedWriter writer = new IndentedWriter(out) ;
    serialize(writer, syntax) ;
    writer.flush() ;
    try { out.flush() ; } catch (Exception ex) { } 
}
 
Example 26
Project: JerseyTest   File: RootElementWrapperTest.java View source code 6 votes vote down vote up
private void _testUnwrapOutput(String wrappedJson, String expectedJson) throws Exception {

        OutputStream result = new ByteArrayOutputStream();

        OutputStream inputOutput = RootElementWrapper.unwrapOutput(result);

        inputOutput.write(wrappedJson.getBytes());

        String resultJson = result.toString();

        System.out.println(String.format("Expected: %s, \nreturned: %s", expectedJson, resultJson));

        assertEquals(expectedJson, resultJson);
    }
 
Example 27
Project: stickypunch   File: ModuleFunctionalTest.java View source code 6 votes vote down vote up
private String extractAuthenticationToken(HttpResponse httpResponse) throws IOException {
    InputStream inputStream = httpResponse.getEntity().getContent();
    OutputStream outputStream = new ByteArrayOutputStream();
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry ze;
    byte[] buff = new byte[1024];
    while ((ze = zis.getNextEntry()) != null) {
        // get file name
        if (ze.getName().equals("website.json")) {
            int l = 0;
            // write buffer to file
            while ((l = zis.read(buff)) > 0) {
                outputStream.write(buff, 0, l);
            }
        }
    }
    String json = outputStream.toString();
    outputStream.close();
    zis.close();
    Website website = WebsiteObjectMapper.getInstance().readValue(json, Website.class);
    return website.getAuthenticationToken();
}
 
Example 28
Project: ha-bridge   File: DevModeResponse.java View source code 6 votes vote down vote up
private String dataReader(String filePath) {

		String content = null;
		try {
			InputStream input = getClass().getResourceAsStream(filePath);
			OutputStream out = new ByteArrayOutputStream();
			int read;
			byte[] bytes = new byte[1024];

			while ((read = input.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			content = out.toString();
		} catch (IOException e) {
			log.error("Error reading the file: " + filePath + " message: " + e.getMessage(), e);
		}
		return content;
	}
 
Example 29
Project: dataverse   File: DdiExportUtil.java View source code 6 votes vote down vote up
private static String dto2ddi(DatasetDTO datasetDto) throws XMLStreamException {
    OutputStream outputStream = new ByteArrayOutputStream();
    XMLStreamWriter xmlw = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream);
    xmlw.writeStartElement("codeBook");
    xmlw.writeDefaultNamespace("http://www.icpsr.umich.edu/DDI");
    writeAttribute(xmlw, "version", "2.0");
    createStdyDscr(xmlw, datasetDto);
    createdataDscr(xmlw, datasetDto.getDatasetVersion().getFiles());
    xmlw.writeEndElement(); // codeBook
    xmlw.flush();
    String xml = outputStream.toString();
    return XmlPrinter.prettyPrintXml(xml);
}
 
Example 30
Project: obaa   File: DublinCore.java View source code 6 votes vote down vote up
/**
 * 
 * @return [email protected] String} containing the XML correspondin to the current object.
 * @throws Exception In case a serializing error occurs
 */
public String toXml() throws Exception {
	OutputStream o = new ByteArrayOutputStream();
	Serializer serializer = new Persister();
	serializer.write(this, o);
	
	return o.toString();
}
 
Example 31
Project: resin   File: ResinEmbed.java View source code 6 votes vote down vote up
public String request(String input) throws IOException
{
  OutputStream os = new ByteArrayOutputStream();

  request(input, os);

  return os.toString();
}
 
Example 32
Project: jgit   File: DiffCommandTest.java View source code 6 votes vote down vote up
@Test
public void testDiffModified() throws Exception {
	write(new File(db.getWorkTree(), "test.txt"), "test");
	File folder = new File(db.getWorkTree(), "folder");
	folder.mkdir();
	write(new File(folder, "folder.txt"), "folder");
	Git git = new Git(db);
	git.add().addFilepattern(".").call();
	git.commit().setMessage("Initial commit").call();
	write(new File(folder, "folder.txt"), "folder change");

	OutputStream out = new ByteArrayOutputStream();
	List<DiffEntry> entries = git.diff().setOutputStream(out).call();
	assertEquals(1, entries.size());
	assertEquals(ChangeType.MODIFY, entries.get(0)
			.getChangeType());
	assertEquals("folder/folder.txt", entries.get(0)
			.getOldPath());
	assertEquals("folder/folder.txt", entries.get(0)
			.getNewPath());

	String actual = out.toString();
	String expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n"
			+ "index 0119635..95c4c65 100644\n"
			+ "--- a/folder/folder.txt\n"
			+ "+++ b/folder/folder.txt\n"
			+ "@@ -1 +1 @@\n"
			+ "-folder\n"
			+ "\\ No newline at end of file\n"
			+ "+folder change\n"
			+ "\\ No newline at end of file\n";
	assertEquals(expected.toString(), actual);
}
 
Example 33
Project: beowulf   File: XmlUtils.java View source code 6 votes vote down vote up
/**
 * Method is responsible for transforming the XMl to another formats using a
 * XSL and a parameter map.
 * 
 * @return
 * @throws TransformerException
 */
public static String transformXMLUsingXSL(String xslLocation, String sourceXml, Map<String, Object> parameters) throws TransformerException {

	logger.debug("Transforming the given xml using xsl `{}` with a substitution map.", xslLocation);
	InputStream sourceXmlStream = new ByteArrayInputStream(sourceXml.getBytes());
	OutputStream transformedXmlStream = transformXMLUsingXSL(xslLocation, sourceXmlStream, parameters);
	return transformedXmlStream.toString();
}
 
Example 34
Project: teiid-designer   File: MappingDocument.java View source code 6 votes vote down vote up
@Override
public String getMappingString() throws Exception{
 // Output the mapping objects to a stream
    String result = null;
    OutputStream moStream = null;
    try {
        moStream = new ByteArrayOutputStream();
        final PrintWriter pw = new PrintWriter(moStream, true);
        final MappingOutputter outputter = new MappingOutputter();
        outputter.write(this, pw); // TODO FIX/REPLACE??? , isNewlines(), isIndent());
        pw.flush();

        result = moStream.toString();
    } catch (final Exception e) {
        throw e;
    } finally {
        if (moStream != null) {
            try {
                moStream.close();
            } catch (final IOException e1) {
                throw e1;
            }
            moStream = null;
        }
    }
    return result;
}
 
Example 35
Project: sqlpower-library   File: PlDotIni.java View source code 6 votes vote down vote up
public String toString() {
    OutputStream out = new ByteArrayOutputStream();
    try {
        write(out);
    } catch (IOException e) {
        return "PlDotIni: toString: Couldn't create string description: "+e.getMessage();
    }
    return out.toString();
}
 
Example 36
Project: mkgmap   File: TestUtils.java View source code 6 votes vote down vote up
/**
 * Run with the given args.  Some standard arguments are added first.
 *
 * To run without the standard args, use runRaw().
 * @param in The arguments to use.
 */
public static Outputs run(String ... in) {
	List<String> args = new ArrayList<String>(Arrays.asList(in));
	args.add(0, Args.TEST_STYLE_ARG);

	OutputStream outsink = new ByteArrayOutputStream();
	PrintStream out = new PrintStream(outsink);

	OutputStream errsink = new ByteArrayOutputStream();
	PrintStream err = new PrintStream(errsink);

	PrintStream origout = System.out;
	PrintStream origerr = System.err;

	try {
		System.setOut(out);
		System.setErr(err);
		Main.mainNoSystemExit(args.toArray(new String[args.size()]));
	} finally {
		out.close();
		err.close();
		System.setOut(origout);
		System.setErr(origerr);
	}

	return new Outputs(outsink.toString(), errsink.toString());
}
 
Example 37
Project: korsakow-editor   File: FileExternalEncoder.java View source code 6 votes vote down vote up
protected void encode(Process process, File sourceFile, File destFile)
		throws EncoderException, InterruptedException
{
	OutputStream errBuff = new ByteArrayOutputStream();
	OutputStream outBuff = new ByteArrayOutputStream();
	int exitCode;

	exitCode = FileUtil.executeProcess(process, outBuff, errBuff);

	Logger.getLogger(getClass()).info(outBuff.toString());
	Logger.getLogger(getClass()).info(errBuff.toString());
	if (0 != exitCode) {
		throw new EncoderException(String.format("unknown error: code=%d, output=%s", exitCode, errBuff.toString()), errBuff.toString(), sourceFile);
	}
}
 
Example 38
Project: logwex   File: SimpleLogWExServletTest.java View source code 6 votes vote down vote up
@Test
public void testInit() throws Exception {
    Logger logger = Logger.getLogger(SimpleLogWExServlet.class);

    servlet.init();
    System.out.println("Log OK ? " + logger.isInfoEnabled());
    logger.info("Message");
    OutputStream stream = (OutputStream)ReflectionUtils.getFieldValue(servlet, "stream");
    //stream.flush();
    final String logs = stream.toString();
    assertEquals("Log text with SimpleLayout", "INFO - Message\n", logs);
    System.out.println(logs);
}
 
Example 39
Project: modeshape   File: JcrSessionTest.java View source code 6 votes vote down vote up
@Test
public void shouldExportMultiLinePropertiesInSystemView() throws Exception {
    initializeData();

    OutputStream os = new ByteArrayOutputStream();
    session.exportSystemView("/a/b/c", os, false, true);

    String fileContents = os.toString();
    assertTrue(fileContents.contains(MULTI_LINE_VALUE));
}
 
Example 40
Project: FScape   File: Presets.java View source code 6 votes vote down vote up
/**
 *	Schreibt die uebergebenen Properties in einen ByteStream und
 *	liefert diesen als String zurueck
 *
 *	@return	null bei Fehler
 */
public static String propertiesToValue( Properties val )
{
	final OutputStream	outStream	= new ByteArrayOutputStream();

	try {
		val.store( outStream, null );
		final String strVal = outStream.toString();		// now we have the Properties as a String
		outStream.close();
		return strVal;
	}
	catch( IOException e ) {
		return null;
	}	
}
 
Example 41
Project: mytracks   File: TrackWriterTest.java View source code 6 votes vote down vote up
/**
 * Makes the right sequence of calls to the writer in order to write the fake
 * track in [email protected] #track}.
 *
 * @param trackWriter the track writer
 * @return the written contents
 */
protected String writeTrack(TrackWriter trackWriter) throws Exception {
  OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE);
  trackWriter.prepare(output);
  trackWriter.writeHeader(new Track[] {track});
  trackWriter.writeBeginWaypoints(track);
  trackWriter.writeWaypoint(wp1);
  trackWriter.writeWaypoint(wp2);
  trackWriter.writeEndWaypoints();
  trackWriter.writeBeginTracks();
  trackWriter.writeBeginTrack(track, location1);
  trackWriter.writeOpenSegment();
  trackWriter.writeLocation(location1);
  trackWriter.writeLocation(location2);
  trackWriter.writeCloseSegment();
  trackWriter.writeOpenSegment();
  trackWriter.writeLocation(location3);
  trackWriter.writeLocation(location4);
  trackWriter.writeCloseSegment();
  trackWriter.writeEndTrack(track, location4);
  trackWriter.writeEndTracks();
  trackWriter.writeFooter();
  trackWriter.close();
  return output.toString();
}
 
Example 42
Project: ikvm-openjdk   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase();  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
            Class objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class[]{objClass, objClass});
            Method getDefault =
                socketFactoryClass.getMethod("getDefault", new Class[]{});
            this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 43
Project: xxl   File: Converters.java View source code 6 votes vote down vote up
/**
 * Returns the number of bytes needed to serialize the state (the
 * attributes) of the specified object. If the measuring fails this method
 * should return <code>-1.</code>
 * 
 * <p>This implementation creates an anonymous local class that implements
 * the interface <code>OutputStream</code>. The <code>write</code> method
 * of this local class only increases a counter and the
 * <code>hashCode</code> method returns it. Thereafter the specified object
 * is written to the <code>OutputStream</code> using the <code>write</code>
 * method of the converter. If this call succeeds the hashCode of the
 * <code>OutputStream</code> (the number of bytes written to the output
 * stream) is returned otherwise <code>-1</code> is returned.</p>
 *
 * @param <T> the type of the object to be converted.
 * @param converter the converter to be used for converting the object.
 * @param object the object to be converted.
 * @return the number of bytes needed to serialize the state (the
 *         attributes) of the specified object or <code>-1</code> if the
 *         measuring fails.
 */
public static <T> int sizeOf(Converter<? super T> converter, T object) {
	try {
		OutputStream output = new OutputStream() {
			int counter = 0;
			
			@Override
			public void write(int b) {
				counter++;
			}
			
			@Override
			public int hashCode() {
				return counter;
			}
		};
		converter.write(new DataOutputStream(output), object);
		return output.hashCode();
	}
	catch (IOException e) {
		return -1;
	}
}
 
Example 44
Project: ManagedRuntimeInitiative   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase();  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
            Class objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class[]{objClass, objClass});
            Method getDefault =
                socketFactoryClass.getMethod("getDefault", new Class[]{});
            this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 45
Project: openjdk   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase();  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
            Class objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class[]{objClass, objClass});
            Method getDefault =
                socketFactoryClass.getMethod("getDefault", new Class[]{});
            this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 46
Project: openjdk8-jdk   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase(Locale.ENGLISH);  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class<?> socketFactoryClass =
                    Obj.helper.loadClass(socketFactory);
            Class<?> objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class<?>[]{objClass, objClass});
            Method getDefault = socketFactoryClass.getMethod(
                                        "getDefault", new Class<?>[]{});
            this.factory =
                    (SocketFactory)getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 47
Project: jdk7-jdk   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase();  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
            Class objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class[]{objClass, objClass});
            Method getDefault =
                socketFactoryClass.getMethod("getDefault", new Class[]{});
            this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 48
Project: jdk7u-jdk   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
        Control[] bindCtls, OutputStream trace, String socketFactory) {
    this.version = version;
    this.hostname = hostname.toLowerCase();  // ignore case
    this.port = port;
    this.protocol = protocol;
    this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
    this.trace = trace;
    //
    // Needed for custom socket factory pooling
    //
    this.socketFactory = socketFactory;
    if ((socketFactory != null) &&
         !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
        try {
            Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
            Class objClass = Class.forName("java.lang.Object");
            this.sockComparator = socketFactoryClass.getMethod(
                            "compare", new Class[]{objClass, objClass});
            Method getDefault =
                socketFactoryClass.getMethod("getDefault", new Class[]{});
            this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
        } catch (Exception e) {
            // Ignore it here, the same exceptions are/will be handled by
            // LdapPoolManager and Connection classes.
            if (debug) {
                System.out.println("ClientId received an exception");
                e.printStackTrace();
            }
        }
    } else {
         isDefaultSockFactory = true;
    }

    // The SocketFactory field is not used in the myHash
    // computation as there is no right way to compute the hash code
    // for this field. There is no harm in skipping it from the hash
    // computation
    myHash = version + port
        + (trace != null ? trace.hashCode() : 0)
        + (this.hostname != null ? this.hostname.hashCode() : 0)
        + (protocol != null ? protocol.hashCode() : 0)
        + (ctlHash=hashCodeControls(bindCtls));
}
 
Example 49
Project: classlib6   File: ClientId.java View source code 6 votes vote down vote up
ClientId(int version, String hostname, int port, String protocol,
    Control[] bindCtls, OutputStream trace, String socketFactory) {
this.version = version;
this.hostname = hostname.toLowerCase();  // ignore case
this.port = port;
this.protocol = protocol;
this.bindCtls = (bindCtls != null ? (Control[]) bindCtls.clone() : null);
this.trace = trace;
//
// Needed for custom socket factory pooling
// 
this.socketFactory = socketFactory;
if ((socketFactory != null) && 
     !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
    try {
        Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
        Class objClass = Class.forName("java.lang.Object");
        this.sockComparator = socketFactoryClass.getMethod(
			"compare", new Class[]{objClass, objClass});
        Method getDefault =
	    socketFactoryClass.getMethod("getDefault", new Class[]{});
        this.factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
    } catch (Exception e) {
	// Ignore it here, the same exceptions are/will be handled by
	// LdapPoolManager and Connection classes.
        if (debug) {
	    System.out.println("ClientId received an exception");
	    e.printStackTrace();
        }
    }
} else {
     isDefaultSockFactory = true;
}	

// The SocketFactory field is not used in the myHash
// computation as there is no right way to compute the hash code
// for this field. There is no harm in skipping it from the hash
       // computation
myHash = version + port
    + (trace != null ? trace.hashCode() : 0)
    + (this.hostname != null ? this.hostname.hashCode() : 0)
    + (protocol != null ? protocol.hashCode() : 0)
    + (ctlHash=hashCodeControls(bindCtls));
   }
 
Example 50
Project: AndroidRepeaterProject   File: UnsignedInt.java View source code 6 votes vote down vote up
/**
* Writes a group of bits to a given output stream.
**
* Negative <VAR>count</VAR> is treated as zero. Important notes: if
* <VAR>count</VAR> is greater than <CODE>JavaConsts INT_SIZE</CODE>
* then the specified value (containing the bits to write) is
* zero-extended; <VAR>out</VAR> is a byte-oriented stream, so given
* bits are padded with zeros (on the most significant side); the
* bits are written starting from the most significant one.
**
* @param out
* the stream (must be non-<CODE>null</CODE>) to write to.
* @param unsignedValue
* the unsigned value, containing bits (in its lowest part) to be
* written.
* @param count
* the amount of bits to be written.
* @exception NullPointerException
* if <VAR>out</VAR> is <CODE>null</CODE>.
* @exception IOException
* if an I/O error occurs.
**
* @see #readBits(java.io.InputStream, int)
* @see #readByte(java.io.InputStream)
**
* @since 1.1
*/
public static final void writeBits(OutputStream out,
        int unsignedValue, int count)
 throws NullPointerException, IOException
{
 out.equals(out);
 if (count > 0)
 {
  int shift;
  if ((shift = count % JavaConsts.BYTE_SIZE) > 0)
   out.write((count -= shift) >= JavaConsts.INT_SIZE ? 0 :
    (unsignedValue >>> count) & ~(-1 << shift));
  while (count > JavaConsts.INT_SIZE)
  {
   out.write(0);
   count -= JavaConsts.BYTE_SIZE;
  }
  while ((count -= JavaConsts.BYTE_SIZE) >= 0)
   out.write(unsignedValue >>> count);
 }
}
 
Example 51
Project: AndroidRepeaterProject   File: UnsignedLong.java View source code 6 votes vote down vote up
/**
* Writes a group of bits to a given output stream.
**
* Negative <VAR>count</VAR> is treated as zero. Important notes: if
* <VAR>count</VAR> is greater than
* <CODE>JavaConsts LONG_SIZE</CODE> then the specified value
* (containing the bits to write) is zero-extended; <VAR>out</VAR>
* is a byte-oriented stream, so given bits are padded with zeros
* (on the most significant side); the bits are written starting
* from the most significant one.
**
* @param out
* the stream (must be non-<CODE>null</CODE>) to write to.
* @param unsignedValue
* the unsigned value, containing bits (in its lowest part) to be
* written.
* @param count
* the amount of bits to be written.
* @exception NullPointerException
* if <VAR>out</VAR> is <CODE>null</CODE>.
* @exception IOException
* if an I/O error occurs.
**
* @see #readBits(java.io.InputStream, int)
**
* @since 1.1
*/
public static final void writeBits(OutputStream out,
        long unsignedValue, int count)
 throws NullPointerException, IOException
{
 out.equals(out);
 if (count > 0)
 {
  int shift;
  if ((shift = count % JavaConsts.BYTE_SIZE) > 0)
   out.write((count -= shift) >= JavaConsts.LONG_SIZE ? 0 :
    (int)(unsignedValue >>> count) & ~(-1 << shift));
  while (count > JavaConsts.LONG_SIZE)
  {
   out.write(0);
   count -= JavaConsts.BYTE_SIZE;
  }
  while ((count -= JavaConsts.BYTE_SIZE) >= 0)
   out.write((int)(unsignedValue >>> count));
 }
}
 
Example 52
Project: fqrouter   File: UnsignedInt.java View source code 6 votes vote down vote up
/**
* Writes a group of bits to a given output stream.
**
* Negative <VAR>count</VAR> is treated as zero. Important notes: if
* <VAR>count</VAR> is greater than <CODE>JavaConsts INT_SIZE</CODE>
* then the specified value (containing the bits to write) is
* zero-extended; <VAR>out</VAR> is a byte-oriented stream, so given
* bits are padded with zeros (on the most significant side); the
* bits are written starting from the most significant one.
**
* @param out
* the stream (must be non-<CODE>null</CODE>) to write to.
* @param unsignedValue
* the unsigned value, containing bits (in its lowest part) to be
* written.
* @param count
* the amount of bits to be written.
* @exception NullPointerException
* if <VAR>out</VAR> is <CODE>null</CODE>.
* @exception IOException
* if an I/O error occurs.
**
* @see #readBits(java.io.InputStream, int)
* @see #readByte(java.io.InputStream)
**
* @since 1.1
*/
public static final void writeBits(OutputStream out,
        int unsignedValue, int count)
 throws NullPointerException, IOException
{
 out.equals(out);
 if (count > 0)
 {
  int shift;
  if ((shift = count % JavaConsts.BYTE_SIZE) > 0)
   out.write((count -= shift) >= JavaConsts.INT_SIZE ? 0 :
    (unsignedValue >>> count) & ~(-1 << shift));
  while (count > JavaConsts.INT_SIZE)
  {
   out.write(0);
   count -= JavaConsts.BYTE_SIZE;
  }
  while ((count -= JavaConsts.BYTE_SIZE) >= 0)
   out.write(unsignedValue >>> count);
 }
}
 
Example 53
Project: fqrouter   File: UnsignedLong.java View source code 6 votes vote down vote up
/**
* Writes a group of bits to a given output stream.
**
* Negative <VAR>count</VAR> is treated as zero. Important notes: if
* <VAR>count</VAR> is greater than
* <CODE>JavaConsts LONG_SIZE</CODE> then the specified value
* (containing the bits to write) is zero-extended; <VAR>out</VAR>
* is a byte-oriented stream, so given bits are padded with zeros
* (on the most significant side); the bits are written starting
* from the most significant one.
**
* @param out
* the stream (must be non-<CODE>null</CODE>) to write to.
* @param unsignedValue
* the unsigned value, containing bits (in its lowest part) to be
* written.
* @param count
* the amount of bits to be written.
* @exception NullPointerException
* if <VAR>out</VAR> is <CODE>null</CODE>.
* @exception IOException
* if an I/O error occurs.
**
* @see #readBits(java.io.InputStream, int)
**
* @since 1.1
*/
public static final void writeBits(OutputStream out,
        long unsignedValue, int count)
 throws NullPointerException, IOException
{
 out.equals(out);
 if (count > 0)
 {
  int shift;
  if ((shift = count % JavaConsts.BYTE_SIZE) > 0)
   out.write((count -= shift) >= JavaConsts.LONG_SIZE ? 0 :
    (int)(unsignedValue >>> count) & ~(-1 << shift));
  while (count > JavaConsts.LONG_SIZE)
  {
   out.write(0);
   count -= JavaConsts.BYTE_SIZE;
  }
  while ((count -= JavaConsts.BYTE_SIZE) >= 0)
   out.write((int)(unsignedValue >>> count));
 }
}
 
Example 54
Project: dlna   File: HttpServer.java View source code 5 votes vote down vote up
/**
 * Sends given response to the socket.
 */
private void sendResponse( String status, String mime, Properties header, InputStream data )
{
	try
	{
		if ( status == null )
			throw new Error( "sendResponse(): Status can't be null." );

		OutputStream out = mySocket.getOutputStream();
		PrintWriter pw = new PrintWriter( out );
		pw.print("HTTP/1.0 " + status + " \r\n");

		if ( mime != null )
			pw.print("Content-Type: " + mime + "\r\n");

		if ( header == null || header.getProperty( "Date" ) == null )
			pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

		if ( header != null )
		{
			Enumeration e = header.keys();
			while ( e.hasMoreElements())
			{
				String key = (String)e.nextElement();
				String value = header.getProperty( key );
				pw.print( key + ": " + value + "\r\n");
			}
		}

		pw.print("\r\n");
		pw.flush();

		if ( data != null )
		{
			int pending = data.available();	// This is to support partial sends, see serveFile()
			byte[] buff = new byte[2048];
			while (pending>0)
			{
				int read = data.read( buff, 0, ( (pending>2048) ?  2048 : pending ));
				if (read <= 0)	break;
				out.write( buff, 0, read );
				pending -= read;
			}
		}
		out.flush();
		out.close();
		if ( data != null )
			data.close();
	}
	catch( IOException ioe )
	{
		// Couldn't write? No can do.
		try { mySocket.close(); } catch( Throwable t ) {}
	}
}
 
Example 55
Project: FallUML2013   File: DisplayDiagram.java View source code 5 votes vote down vote up
public void downloadDiagram(String[] checked, HttpServletRequest request, HttpServletResponse response)
   throws ServletException, FileNotFoundException, IOException {

int id = Integer.parseInt(checked[0]) -1;
   ArrayList<domain.Diagram> diagrams = DiagramDAO.getDiagramList(2);
	
// the absolute path of folder where all diagrams store.
String filePath = diagrams.get(id).getFilePath();
String[] splitPath = filePath.split("/");
String targetPath = "/" + splitPath[0] + "/" + splitPath[1] + "/";
ServletContext context = getServletContext();
String targetRealPath = context.getRealPath(targetPath);
String reportRealPath = context.getRealPath("/reports/");
DownloadDirectory dirObj = new DownloadDirectory();
   DownloadZipfile zipObj = new DownloadZipfile();
   File tmpdir = dirObj.createDirectory(reportRealPath);
   
   String outputFile = splitPath[2] + ".zip";
   String downloadPath = dirObj.getDownloadPath();
   String output = "";
   if(OSDetails.getServerOS().equals("windows"))
   {
   	output = downloadPath + "\\" + outputFile;
   } else if(OSDetails.getServerOS().equals("mac") || 
   		OSDetails.getServerOS().equals("unix"))
   {
   	output = downloadPath + "/" + outputFile;
   }
   OutputStream ops = null;
   DataInputStream in = null;
try {
    zipObj.downloadZipfileProcessor(targetRealPath, output);
    ops = response.getOutputStream();
    byte bytes[] = new byte[1024];
    int length = 0;
	
    File fileLoad = new File(downloadPath, outputFile);
	
    String mimetype = context.getMimeType(outputFile);
    response.setHeader("Content-disposition", "attachment;filename=" + outputFile);
    response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
    response.setContentLength((int) fileLoad.length());
	
    in = new DataInputStream(new FileInputStream(fileLoad));
	
    while ((in != null) && ((length = in.read(bytes)) != -1)) {
    	ops.write(bytes, 0, length);
    }
    ops.flush();
    ops.close();
    in.close();
    dirObj.deleteDirectory(tmpdir);
    
} catch (IOException ex) {
	if(!ops.equals(null))
	{
		ops.close();
	}
	if(!in.equals(null))
	{
		in.close();
	}
	dirObj.deleteDirectory(tmpdir);
	System.out.println(ex);
}
  }