Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

In this page you can find the example usage for java.io BufferedReader read.

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:org.clever.HostManager.HyperVisorPlugins.Libvirt.pollEventThread.java

public String xmlToString(String path) throws IOException {
    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = new BufferedReader(new FileReader(path));
    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);/*from   w w w  .j a v  a2  s  . co m*/
        buf = new char[1024];
    }
    reader.close();
    return fileData.toString();
}

From source file:org.m2x.rssreader.service.FetcherService.java

private int refreshFeed(String feedId) {
    RssAtomParser handler = null;//from   ww w. j a v a 2 s .co  m

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);

    if (!cursor.moveToFirst()) {
        cursor.close();
        return 0;
    }

    int urlPosition = cursor.getColumnIndex(FeedColumns.URL);
    int titlePosition = cursor.getColumnIndex(FeedColumns.NAME);
    int fetchmodePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE);
    int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE);
    int iconPosition = cursor.getColumnIndex(FeedColumns.ICON);
    int retrieveFullTextPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT);

    HttpURLConnection connection = null;
    try {
        String feedUrl = cursor.getString(urlPosition);
        connection = NetworkUtils.setupConnection(feedUrl);
        String contentType = connection.getContentType();
        int fetchMode = cursor.getInt(fetchmodePosition);

        handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), feedId,
                cursor.getString(titlePosition), feedUrl, cursor.getInt(retrieveFullTextPosition) == 1);
        handler.setFetchImages(PrefUtils.getBoolean(PrefUtils.FETCH_PICTURES, true));

        if (fetchMode == 0) {
            if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                String line;
                int posStart = -1;

                while ((line = reader.readLine()) != null) {
                    if (line.contains(HTML_BODY)) {
                        break;
                    } else {
                        Matcher matcher = FEED_LINK_PATTERN.matcher(line);

                        if (matcher.find()) { // not "while" as only one link is needed
                            line = matcher.group();
                            posStart = line.indexOf(HREF);

                            if (posStart > -1) {
                                String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10))
                                        .replace("&amp", "&");

                                ContentValues values = new ContentValues();

                                if (url.startsWith("/")) {
                                    int index = feedUrl.indexOf('/', 8);

                                    if (index > -1) {
                                        url = feedUrl.substring(0, index) + url;
                                    } else {
                                        url = feedUrl + url;
                                    }
                                } else if (!url.startsWith(Constants.HTTP_SCHEME)
                                        && !url.startsWith(Constants.HTTPS_SCHEME)) {
                                    url = feedUrl + '/' + url;
                                }
                                values.put(FeedColumns.URL, url);
                                cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
                                connection.disconnect();
                                connection = NetworkUtils.setupConnection(url);
                                contentType = connection.getContentType();
                                break;
                            }
                        }
                    }
                }
                // this indicates a badly configured feed
                if (posStart == -1) {
                    connection.disconnect();
                    connection = NetworkUtils.setupConnection(feedUrl);
                    contentType = connection.getContentType();
                }
            }

            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                if (index > -1) {
                    int index2 = contentType.indexOf(';', index);

                    try {
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    fetchMode = FETCHMODE_REENCODE;
                }

            } else {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(NetworkUtils.getConnectionInputStream(connection)));

                char[] chars = new char[20];

                int length = bufferedReader.read(chars);

                String xmlDescription = new String(chars, 0, length);

                connection.disconnect();
                connection = NetworkUtils.setupConnection(connection.getURL());

                int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1;

                if (start > -1) {
                    try {
                        Xml.findEncodingByName(
                                xmlDescription.substring(start + 10, xmlDescription.indexOf('"', start + 11)));
                        fetchMode = FETCHMODE_DIRECT;
                    } catch (UnsupportedEncodingException usee) {
                        fetchMode = FETCHMODE_REENCODE;
                    }
                } else {
                    // absolutely no encoding information found
                    fetchMode = FETCHMODE_DIRECT;
                }
            }

            ContentValues values = new ContentValues();
            values.put(FeedColumns.FETCH_MODE, fetchMode);
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }

        switch (fetchMode) {
        default:
        case FETCHMODE_DIRECT: {
            if (contentType != null) {
                int index = contentType.indexOf(CHARSET);

                int index2 = contentType.indexOf(';', index);

                InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);
                Xml.parse(inputStream,
                        Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                : contentType.substring(index + 8)),
                        handler);
            } else {
                InputStreamReader reader = new InputStreamReader(
                        NetworkUtils.getConnectionInputStream(connection));
                Xml.parse(reader, handler);
            }
            break;
        }
        case FETCHMODE_REENCODE: {
            ByteArrayOutputStream ouputStream = new ByteArrayOutputStream();
            InputStream inputStream = NetworkUtils.getConnectionInputStream(connection);

            byte[] byteBuffer = new byte[4096];

            int n;
            while ((n = inputStream.read(byteBuffer)) > 0) {
                ouputStream.write(byteBuffer, 0, n);
            }

            String xmlText = ouputStream.toString();

            int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;

            if (start > -1) {
                Xml.parse(new StringReader(new String(ouputStream.toByteArray(),
                        xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler);
            } else {
                // use content type
                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);

                    if (index > -1) {
                        int index2 = contentType.indexOf(';', index);

                        try {
                            StringReader reader = new StringReader(new String(ouputStream.toByteArray(),
                                    index2 > -1 ? contentType.substring(index + 8, index2)
                                            : contentType.substring(index + 8)));
                            Xml.parse(reader, handler);
                        } catch (Exception ignored) {
                        }
                    } else {
                        StringReader reader = new StringReader(new String(ouputStream.toByteArray()));
                        Xml.parse(reader, handler);
                    }
                }
            }
            break;
        }
        }

        connection.disconnect();
    } catch (FileNotFoundException e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR, getString(R.string.error_feed_error));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } catch (Throwable e) {
        if (handler == null || (handler != null && !handler.isDone() && !handler.isCancelled())) {
            ContentValues values = new ContentValues();

            // resets the fetchmode to determine it again later
            values.put(FeedColumns.FETCH_MODE, 0);

            values.put(FeedColumns.ERROR,
                    e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process));
            cr.update(FeedColumns.CONTENT_URI(feedId), values, null, null);
        }
    } finally {

        /* check and optionally find favicon */
        try {
            if (handler != null && cursor.getBlob(iconPosition) == null) {
                String feedLink = handler.getFeedLink();
                if (feedLink != null) {
                    NetworkUtils.retrieveFavicon(this, new URL(feedLink), feedId);
                } else {
                    NetworkUtils.retrieveFavicon(this, connection.getURL(), feedId);
                }
            }
        } catch (Throwable ignored) {
        }

        if (connection != null) {
            connection.disconnect();
        }
    }

    cursor.close();

    return handler != null ? handler.getNewCount() : 0;
}

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Feed HTML into received over a {@link java.net.URLConnection} to an
 * HTML parser./*from   w w  w .j  av  a  2s .co  m*/
 * @param in input stream
 * @param contentType preferred content type
 * @param response servlet response
 * @throws java.io.IOException if an I/O error occurs
 */
private void rewriteHtml(InputStream in, String contentType, HttpServletResponse response) throws IOException {

    // Determine encoding if not specified
    String encoding = "8859_1";
    int charsetIndex = contentType.indexOf("charset=");
    if (charsetIndex != -1) {
        encoding = contentType.substring(charsetIndex + "charset=".length()).trim();
    } else {
        byte[] buf = new byte[2048];
        int len = fillBuffer(in, buf);

        String scanned = EncodingScanner.scan(buf, 0, len);
        if (scanned != null) {
            encoding = scanned;
            contentType += "; charset=" + encoding;
        }
        PushbackInputStream pb = new PushbackInputStream(in, buf.length);
        pb.unread(buf, 0, len);
        in = pb;
    }

    // Set appropriate content type and get writer
    response.setContentType(contentType);
    PrintWriter writer = response.getWriter();
    setWriter(writer);

    // Define tags that should be inspected
    HashSet<String> inclusionSet = new HashSet<String>();
    inclusionSet.add("A");
    inclusionSet.add("AREA");
    inclusionSet.add("BASE");
    inclusionSet.add("FORM");
    inclusionSet.add("FRAME");
    inclusionSet.add("IFRAME");
    inclusionSet.add("IMG");
    inclusionSet.add("INPUT");
    inclusionSet.add("LINK");
    inclusionSet.add("SCRIPT");
    inclusionSet.add("TABLE");
    inclusionSet.add("TD");
    inclusionSet.add("TR");
    inclusionSet.add("NOREWRITE");

    HtmlParser parser = new HtmlParser();
    parser.setTagInclusionSet(inclusionSet);
    parser.setDocumentHandler(this);

    BufferedReader reader = null;

    try {
        reader = new BufferedReader(new InputStreamReader(in, encoding));

        char buf[] = new char[2048];
        int len;

        while ((len = reader.read(buf)) != -1) {
            parser.update(buf, 0, len);
        }
        parser.finished();

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public String loadTouchOscXML(String zipTouchoscFilePath) {
    List<String> touchoscFilePathList = new ArrayList<String>();
    IPath path = new Path(zipTouchoscFilePath);
    String xml = "";
    try {//from   w  ww  . jav  a 2 s .c o  m
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);
        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.flip();

            xml = charBuffer.toString();

        }

        fileIS.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    return xml;
}

From source file:org.getobjects.foundation.UString.java

public static String readFromStream(final InputStream in, String _enc) {
    if (_enc == null)
        _enc = "UTF-8";
    BufferedReader reader = null;
    InputStreamReader fr = null;//from   w ww. jav  a2 s  .c o  m
    try {
        /* Note: FileReader uses MacRoman as the encoding on MacOS 10.4 */
        fr = new InputStreamReader(in, _enc);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding for document: " + in);
        return null;
    }

    // TBD: do we need a buffer?! probably not!
    if ((reader = new BufferedReader(fr)) == null)
        return null;

    StringBuilder sb = new StringBuilder(4096);
    try {
        char buf[] = new char[4096];
        int len;

        while ((len = reader.read(buf)) != -1)
            sb.append(buf, 0, len);
    } catch (IOException e) {
        log.error("error loading content: " + in, e);
        sb = null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.error("could not close reader for file: " + in);
            }
        }
    }

    return sb != null ? sb.toString() : null;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .touchosc file
 * /*from  w  ww.ja  va2 s .c o  m*/
 * @param zipTouchoscFilePath a .touchosc file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        URL url = TouchOSCUtils.class.getClassLoader().getResource(".");

        FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            }
            FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .jzml file
 * //from  ww w  .  j av  a 2 s . com
 * @param zipTouchoscFilePath a .jzml file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    IPath path = new Path(zipTouchoscFilePath);

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<touchosc>", "");
            content = content.replace("</touchosc>", "");
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:com.akop.bach.parser.Parser.java

protected String getResponse(HttpUriRequest request, List<NameValuePair> inputs)
        throws IOException, ParserException {
    if (!request.containsHeader("Accept"))
        request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    if (!request.containsHeader("Accept-Charset"))
        request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    if (App.getConfig().logToConsole())
        App.logv("Parser: Fetching %s", request.getURI());

    long started = System.currentTimeMillis();

    initRequest(request);/*from  w  w  w  . ja  v a2s . co m*/

    try {
        synchronized (mHttpClient) {
            HttpContext context = new BasicHttpContext();

            StringBuilder log = null;

            if (App.getConfig().logHttp()) {
                log = new StringBuilder();

                log.append(String.format("URL: %s\n", request.getURI()));

                log.append("Headers: \n");
                for (Header h : request.getAllHeaders())
                    log.append(String.format("  '%s': '%s'\n", h.getName(), h.getValue()));

                log.append("Cookies: \n");
                for (Cookie c : mHttpClient.getCookieStore().getCookies())
                    log.append(String.format("  '%s': '%s'\n", c.getName(), c.getValue()));

                log.append("Query Elements: \n");

                if (inputs != null) {
                    for (NameValuePair p : inputs)
                        log.append(String.format("  '%s': '%s'\n", p.getName(), p.getValue()));
                } else {
                    log.append("  [empty]\n");
                }
            }

            try {
                mLastResponse = mHttpClient.execute(request, context);
            } catch (SocketTimeoutException e) {
                throw new ParserException(mContext, R.string.error_timed_out);
            }

            try {
                if (mLastResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(ExecutionContext.HTTP_REQUEST);
                    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                    this.mLastUrl = currentHost.toURI() + currentReq.getURI();
                }
            } catch (Exception e) {
                if (App.getConfig().logToConsole()) {
                    App.logv("Unable to get last URL - see stack:");
                    e.printStackTrace();
                }

                this.mLastUrl = null;
            }

            HttpEntity entity = mLastResponse.getEntity();

            if (entity == null)
                return null;

            InputStream stream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 10000);
            StringBuilder builder = new StringBuilder(10000);

            try {
                int read;
                char[] buffer = new char[1000];

                while ((read = reader.read(buffer)) >= 0)
                    builder.append(buffer, 0, read);
            } catch (OutOfMemoryError e) {
                return null;
            }

            stream.close();
            entity.consumeContent();

            String response;

            try {
                response = builder.toString();
            } catch (OutOfMemoryError e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();

                return null;
            }

            if (App.getConfig().logHttp()) {
                log.append(String.format("\nResponse: \n%s\n", response));

                writeToFile(
                        generateDatedFilename(
                                "http-log-" + request.getURI().toString().replaceAll("[^A-Za-z0-9]", "_")),
                        log.toString());
            }

            return preparseResponse(response);
        }
    } finally {
        if (App.getConfig().logToConsole())
            displayTimeTaken("Parser: Fetch took", started);
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public void dumpTouchOsc(TOP top, String destDirname, String destFilename) {

    reverseZOrders(top);/*from   w w  w  . j a va  2  s. com*/
    //
    // Get tests for TouchOSC legacy compliances : need precise version info
    //
    //applyBase64Transformation(top);

    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    String dirname;
    if (destDirname == null) {
        dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString();

        if (Platform.inDebugMode()) {
            System.out.println("creating " + dirname + " directory");
        }

        new File(dirname).mkdir();
    } else {
        dirname = destDirname;
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml");

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.createResource(touchoscURI);

    resource.getContents().add(top);

    try {
        Map<Object, Object> options = new HashMap<Object, Object>();
        options.put(XMLResource.OPTION_ENCODING, "UTF-8");
        resource.save(options);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">";
    String TOUCHOSC_FOOTER = "</touchosc:TOP>";

    String path = touchoscURI.path().toString();
    String outputZipFile = dirname + "/" + destFilename + ".touchosc";

    try {
        FileInputStream touchoscFile = new FileInputStream(path);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(touchoscFile, Charset.forName("ASCII")));
        CharBuffer charBuffer = CharBuffer.allocate(65535);
        while (reader.read(charBuffer) != -1)

            charBuffer.flip();

        String content = charBuffer.toString();
        content = content.replace(TOUCHOSC_HEADER, "<touchosc>");
        content = content.replace(TOUCHOSC_FOOTER, "</touchosc>");
        content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode()
                + "\" orientation=\"" + top.getLayout().getOrientation() + "\">");
        content = content.replace("numberX=", "number_x=");
        content = content.replace("numberY=", "number_y=");
        content = content.replace("invertedX=", "inverted_x=");
        content = content.replace("invertedY=", "inverted_y=");
        content = content.replace("localOff=", "local_off=");
        content = content.replace("oscCs=", "osc_cs=");
        content = content.replace("xypad", "xy");

        touchoscFile.close();

        FileOutputStream os = new FileOutputStream(path);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));

        writer.write(content);
        writer.flush();

        os.flush();
        os.close();

        FileOutputStream fos = new FileOutputStream(outputZipFile);
        ZipOutputStream fileOS = new ZipOutputStream(fos);

        ZipEntry ze = new ZipEntry("index.xml");
        fileOS.putNextEntry(ze);
        fileOS.write(content.getBytes(Charset.forName("UTF-8")));
        fileOS.flush();
        fileOS.close();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        File f = new File(path);
        if (f.exists() && f.canWrite()) {
            if (!f.delete()) {
                throw new IllegalArgumentException(path + " deletion failed");
            }
        }
    }
}

From source file:com.jaspersoft.jasperserver.util.test.BaseServiceSetupTestNG.java

protected String loadFile(String fileName) throws IOException {
    InputStream is = getClass().getResourceAsStream(fileName);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuffer sb = new StringBuffer();
    char[] cbuf = new char[1024];
    int k = 0;/*from  w  w  w . j a va2s. c om*/
    while ((k = br.read(cbuf)) != -1) {
        sb.append(cbuf, 0, k);
    }
    br.close();
    return sb.toString();
}