List of usage examples for java.io StringWriter write
public void write(String str, int off, int len)
From source file:business.security.control.OwmClient.java
private JSONObject doQuery(String subUrl) throws JSONException, IOException { String responseBody = null;// w ww .j av a2s .co m HttpGet httpget = new HttpGet(this.baseOwmUrl + subUrl); if (this.owmAPPID != null) { httpget.addHeader(OwmClient.APPID_HEADER, this.owmAPPID); } HttpResponse response = this.httpClient.execute(httpget); InputStream contentStream = null; try { StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { throw new IOException(String.format("Unable to get a response from OWM server")); } int statusCode = statusLine.getStatusCode(); if (statusCode < 200 && statusCode >= 300) { throw new IOException( String.format("OWM server responded with status code %d: %s", statusCode, statusLine)); } /* Read the response content */ HttpEntity responseEntity = response.getEntity(); contentStream = responseEntity.getContent(); Reader isReader = new InputStreamReader(contentStream); int contentSize = (int) responseEntity.getContentLength(); if (contentSize < 0) { contentSize = 8 * 1024; } StringWriter strWriter = new StringWriter(contentSize); char[] buffer = new char[8 * 1024]; int n = 0; while ((n = isReader.read(buffer)) != -1) { strWriter.write(buffer, 0, n); } responseBody = strWriter.toString(); contentStream.close(); } catch (IOException e) { throw e; } catch (RuntimeException re) { httpget.abort(); throw re; } finally { if (contentStream != null) { contentStream.close(); } } return new JSONObject(responseBody); }
From source file:translate.TRanslate.java
public void post(String input) throws IOException { String response = ""; BufferedReader br = null;//from w ww .jav a 2s. co m br = new BufferedReader(new FileReader("c:\\test.txt")); while ((input = br.readLine()) != null) { String body = "text=" + input + "&itc=te-t-i0-und&num=13"; input = input.replace(" ", "+"); input = input.replace(" ", "+"); input = input.replace(",", "+"); String starting = "\",[\""; String ending = "\"],[],{\""; PostMethod Postmethod = new PostMethod("https://inputtools.google.com/request"); Postmethod.addRequestHeader("Host", " inputtools.google.com"); Postmethod.addRequestHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"); Postmethod.addRequestHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5"); Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8"); Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch"); Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB"); Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive"); Postmethod.addRequestHeader("Referer", "http://www.google.com/intl/te/inputtools/try/"); Postmethod.addRequestHeader("Cookie", " GMAIL_RTT=732; HSID=AGUw587xCPSUIaDxj; SSID=AkkKuZaUGVqvz06y7; APISID=Ih-jSJ5j_auXMle3/A8M2u_3miTXEymzjb; SAPISID=ejtl9SxGbj105_1t/Ak0S2KFfQxDfzHxmH; SID=DQAAADcCAAA267hpyJDVmhZXfBKMci856rC5Bt20M4X52m9JnFgK_cqo-_tIsepRyfGNIxjXd5KnchoxbIojLNAegGge80QA3iIH7l6RgYRCFC0NUHGNwTge61j3ATgH7WopBDw_V7PDCSXDV82TzvuXc7s0_ryI7UyWCW9pVANyqNqcBPmFGZbFD4ES2s6VOYs6MW9rVsQyKxTgTnJjv9b0P6cUMvpwr1J-HBGX2mMFqup3wsylJ9Rp1sECSd_bdjunrLKoqcumaV_3XBayFBcn4BZhSYOj3PvA5om7YTL7zWXfYQZfC_i35gZ5VKnGVlSU-mfwZ1TJdztdkQWVAj4r6c2D2gBm6ZKl6P4WtZ9tt3UMq2F0Efh1I1tYGKEW-PCb7zSJI2zupoc63k5VNB4qI8eL-3OzAZoR9BitHnRRe2IKkXdpdaW8dUim-18qqaOeLjQYzFmBGAqxNw8cFEGtyuiUyZGZ6xKVHNAAoW1nFb4E9NGoJtlBo0nYf0kL4tg68g-kOc9GK5WD28pKQbHuFvlgieSRsvX1R3FftEZs-FMTU-KEZgniOssOeXLD7Qupnh37KbXRysPpkgNf72JdaIodIALUoM4k-6mHgUU-r0uLXNWYigGhvt72qVcuSH6uBHuoOUSee838n_k0E8-vg6bpPis_dg5A30Aq2wLGtFS5Q72Qw3hflukKGHvL64wW2vEvUZq3xtMS685Yx1_ZN72A8-YbB8lHEARnTLrm9ticp1q4X2Zsiz-wMtrq6qU4pRALEKE; OGP=-5061574:; OGPC=5061940-3:5061952-24:5061574-2:5061975-17:; NID=77=S4GVPPNrqG49rmLeZbOwlcNB_PTo1_UNBiv6k2q3RV1O_RY14vKc25tuRyt2IhIvd3ntYrgMgb1WpPUeonBk3CMik5PuqeEYUkjOH6C0Sdg2Xgbl_DxAja0Z0o-gJBolOvyKBMo1YM8MYDVSBJl4dPVRxVvTyg68tGAUmP6Ic6EwDk25g5nA6DMH8nhiyQOT7cG3Zz1Irt2GRhMvqo6jYugcIUTNnogFDBY2Cy-hw9MbLvM8PX1_KRWhwvgKpnR4SwwcqMhQXDYUAPeYjlRGJysIBsS1E0OIPw8xhcKOAGLmN7Jyuwa9FZsHZlEPBXY; S=grandcentral=bhpk116omdw5GfDWh1bWOQ:billing-ui-v3=-hfCJx7YhccZsFolsRi1KA:billing-ui-v3-efe=-hfCJx7YhccZsFolsRi1KA"); Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); Postmethod.setRequestBody(body); Postmethod.addRequestHeader("Content-Length", "" + body.length()); Postmethod.getFollowRedirects(); try { HttpClient client = new HttpClient(); client.executeMethod(Postmethod); Reader reader = null; StringWriter writer = null; String charset = "UTF-8"; // You should determine it based on response header. try { InputStream ungzippedResponse = null; ungzippedResponse = new GZIPInputStream(Postmethod.getResponseBodyAsStream()); reader = new InputStreamReader(ungzippedResponse, charset); writer = new StringWriter(); char[] buffer = new char[10240]; for (int length = 0; (length = reader.read(buffer)) > 0;) { writer.write(buffer, 0, length); } writer.close(); reader.close(); response = writer.toString(); } catch (Exception ex) { ex.printStackTrace(); } int pos = 0; int n1 = 0; int n2 = 0; while (n1 >= 0) { n1 = response.indexOf(starting, n2); n2 = response.indexOf(ending, n1); if (n1 > 0 && n2 > 0) System.out.println(response.substring(n1 + starting.length(), n2)); } } catch (Exception m) { m.printStackTrace(); } } }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);/* ww w .j a va 2 s . com*/ return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:de.wikilab.android.friendica01.TwAjax.java
public String convertStreamToString(InputStream is) throws IOException { /*/* w w w . j a v a 2 s. c om*/ * To convert the InputStream to String we use the * Reader.read(char[] buffer) method. We iterate until the * Reader return -1 which means there's no more data to * read. We use the StringWriter class to produce the string. */ if (is != null) { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } }
From source file:org.alfresco.filesys.FTPServerTest.java
/** * Test quality utility to read an input stream into a string. * @param is/* www . ja va2 s . c o m*/ * @return the content of the stream in a string. * @throws IOException */ private String inputStreamToString(InputStream is) throws IOException { if (is != null) { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } is.close(); return writer.getBuffer().toString(); } return ""; }
From source file:com.jakewharton.DiskLruCacheTest.java
private String readFile(File file) throws Exception { Reader reader = new FileReader(file); StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; int count;/* w ww . j ava2 s . c o m*/ while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } reader.close(); return writer.toString(); }
From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java
/** * This method takes a zip file and reads out the entries. * /* w w w .j a va2 s. c o m*/ * @param in * @throws TechnicalException * @throws NamingException * @throws SWORDContentTypeException */ public PubItemVO readZipFile(InputStream in, AccountUserVO user) throws ItemInvalidException, ContentStreamNotFoundException, Exception { String item = null; List<FileVO> attachements = new ArrayList<FileVO>(); // List<String> attachementsNames = new ArrayList< String>(); PubItemVO pubItem = null; final int bufLength = 1024; char[] buffer = new char[bufLength]; int readReturn; int count = 0; try { ZipEntry zipentry; ZipInputStream zipinputstream = new ZipInputStream(in); // ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((zipentry = zipinputstream.getNextEntry()) != null) { count++; this.logger.debug("Processing zip entry file: " + zipentry.getName()); String name = URLDecoder.decode(zipentry.getName(), "UTF-8"); name = name.replaceAll("/", "_slsh_"); this.filenames.add(name); boolean metadata = false; // check if the file is a metadata file for (int i = 0; i < this.fileEndings.length; i++) { String ending = this.fileEndings[i]; if (name.endsWith(ending)) { metadata = true; // Retrieve the metadata StringWriter sw = new StringWriter(); Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8")); while ((readReturn = reader.read(buffer)) != -1) { sw.write(buffer, 0, readReturn); } item = new String(sw.toString()); this.depositXml = item; this.depositXmlFileName = name; pubItem = createItem(item, user); // if not escidoc format, add as component if (!this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) { attachements.add(convertToFileAndAdd(new ByteArrayInputStream(item.getBytes("UTF-8")), name, user, zipentry)); } } } if (!metadata) { attachements.add(convertToFileAndAdd(zipinputstream, name, user, zipentry)); } zipinputstream.closeEntry(); } zipinputstream.close(); // Now add the components to the Pub Item (if they do not exist. If they exist, use the // existing component metadata and just change the content) for (FileVO newFile : attachements) { boolean existing = false; for (FileVO existingFile : pubItem.getFiles()) { if (existingFile.getName().replaceAll("/", "_slsh_").equals(newFile.getName())) { // file already exists, replace content existingFile.setContent(newFile.getContent()); existingFile.getDefaultMetadata().setSize(newFile.getDefaultMetadata().getSize()); existing = true; } } if (!existing) { pubItem.getFiles().add(newFile); } } // If peer format, add additional copyright information to component. They are read from the // TEI metadata. if (this.currentDeposit.getFormatNamespace().equals(this.mdFormatPeerTEI)) { // Copyright information are imported from metadata file InitialContext initialContext = new InitialContext(); XmlTransformingBean xmlTransforming = new XmlTransformingBean(); Transformation transformer = new TransformationBean(); Format teiFormat = new Format("peer_tei", "application/xml", "UTF-8"); Format escidocComponentFormat = new Format("eSciDoc-publication-component", "application/xml", "UTF-8"); String fileXml = new String(transformer.transform(this.depositXml.getBytes(), teiFormat, escidocComponentFormat, "escidoc"), "UTF-8"); try { FileVO transformdedFileVO = xmlTransforming.transformToFileVO(fileXml); for (FileVO pubItemFile : pubItem.getFiles()) { pubItemFile.getDefaultMetadata() .setRights(transformdedFileVO.getDefaultMetadata().getRights()); pubItemFile.getDefaultMetadata() .setCopyrightDate(transformdedFileVO.getDefaultMetadata().getCopyrightDate()); } } catch (TechnicalException e) { this.logger.error("File Xml could not be transformed into FileVO. ", e); } } } catch (Exception e) { throw new RuntimeException(e); } if (count == 0) { this.logger.info("No zip file was provided."); this.depositServlet.setError("No zip file was provided."); throw new SWORDContentTypeException(); } // pubItem = this.processFiles(item, attachements, attachementsNames, user); return pubItem; }
From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java
/** * This method takes a zip file and reads out the entries. * @param in/*from ww w .j a v a 2 s . c om*/ * @throws TechnicalException * @throws NamingException * @throws SWORDContentTypeException */ public PubItemVO readZipFile(InputStream in, AccountUserVO user) throws ItemInvalidException, ContentStreamNotFoundException, Exception { String item = null; List<FileVO> attachements = new ArrayList<FileVO>(); //List<String> attachementsNames = new ArrayList< String>(); PubItemVO pubItem = null; final int bufLength = 1024; char[] buffer = new char[bufLength]; int readReturn; int count = 0; try { ZipEntry zipentry; ZipInputStream zipinputstream = new ZipInputStream(in); //ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((zipentry = zipinputstream.getNextEntry()) != null) { count++; this.logger.debug("Processing zip entry file: " + zipentry.getName()); String name = URLDecoder.decode(zipentry.getName(), "UTF-8"); name = name.replaceAll("/", "_slsh_"); this.filenames.add(name); boolean metadata = false; //check if the file is a metadata file for (int i = 0; i < this.fileEndings.length; i++) { String ending = this.fileEndings[i]; if (name.endsWith(ending)) { metadata = true; //Retrieve the metadata StringWriter sw = new StringWriter(); Reader reader = new BufferedReader(new InputStreamReader(zipinputstream, "UTF-8")); while ((readReturn = reader.read(buffer)) != -1) { sw.write(buffer, 0, readReturn); } item = new String(sw.toString()); this.depositXml = item; this.depositXmlFileName = name; pubItem = createItem(item, user); //if not escidoc format, add as component if (!this.currentDeposit.getFormatNamespace().equals(this.mdFormatEscidoc)) { attachements.add(convertToFileAndAdd(new ByteArrayInputStream(item.getBytes("UTF-8")), name, user, zipentry)); } } } if (!metadata) { attachements.add(convertToFileAndAdd(zipinputstream, name, user, zipentry)); } zipinputstream.closeEntry(); } zipinputstream.close(); // Now add the components to the Pub Item (if they do not exist. If they exist, use the existing component metadata and just change the content) for (FileVO newFile : attachements) { boolean existing = false; for (FileVO existingFile : pubItem.getFiles()) { if (existingFile.getName().replaceAll("/", "_slsh_").equals(newFile.getName())) { //file already exists, replace content existingFile.setContent(newFile.getContent()); existingFile.getDefaultMetadata().setSize(newFile.getDefaultMetadata().getSize()); existing = true; } } if (!existing) { pubItem.getFiles().add(newFile); } } //If peer format, add additional copyright information to component. They are read from the TEI metadata. if (this.currentDeposit.getFormatNamespace().equals(this.mdFormatPeerTEI)) { //Copyright information are imported from metadata file InitialContext initialContext = new InitialContext(); XmlTransformingBean xmlTransforming = new XmlTransformingBean(); Transformation transformer = new TransformationBean(); Format teiFormat = new Format("peer_tei", "application/xml", "UTF-8"); Format escidocComponentFormat = new Format("eSciDoc-publication-component", "application/xml", "UTF-8"); String fileXml = new String(transformer.transform(this.depositXml.getBytes(), teiFormat, escidocComponentFormat, "escidoc"), "UTF-8"); try { FileVO transformdedFileVO = xmlTransforming.transformToFileVO(fileXml); for (FileVO pubItemFile : pubItem.getFiles()) { pubItemFile.getDefaultMetadata() .setRights(transformdedFileVO.getDefaultMetadata().getRights()); pubItemFile.getDefaultMetadata() .setCopyrightDate(transformdedFileVO.getDefaultMetadata().getCopyrightDate()); } } catch (TechnicalException e) { this.logger.error("File Xml could not be transformed into FileVO. ", e); } } } catch (Exception e) { throw new RuntimeException(e); } if (count == 0) { this.logger.info("No zip file was provided."); this.depositServlet.setError("No zip file was provided."); throw new SWORDContentTypeException(); } //pubItem = this.processFiles(item, attachements, attachementsNames, user); return pubItem; }
From source file:com.zenesis.qx.remote.RequestHandler.java
/** * Handles the callback from the client; expects either an object or an array of objects * @param request/*ww w . j av a 2 s . c o m*/ * @param response * @throws ServletException * @throws IOException */ public void processRequest(Reader request, Writer response) throws ServletException, IOException { s_currentHandler.set(this); ObjectMapper objectMapper = tracker.getObjectMapper(); try { if (log.isDebugEnabled()) { StringWriter sw = new StringWriter(); char[] buffer = new char[32 * 1024]; int length; while ((length = request.read(buffer)) > 0) { sw.write(buffer, 0, length); } log.debug("Received: " + sw.toString()); request = new StringReader(sw.toString()); } JsonParser jp = objectMapper.getJsonFactory().createJsonParser(request); if (jp.nextToken() == JsonToken.START_ARRAY) { while (jp.nextToken() != JsonToken.END_ARRAY) processCommand(jp); } else if (jp.getCurrentToken() == JsonToken.START_OBJECT) processCommand(jp); if (tracker.hasDataToFlush()) { Writer actualResponse = response; if (log.isDebugEnabled()) { final Writer tmp = response; actualResponse = new Writer() { @Override public void close() throws IOException { tmp.close(); } @Override public void flush() throws IOException { tmp.flush(); } @Override public void write(char[] arg0, int arg1, int arg2) throws IOException { System.out.print(new String(arg0, arg1, arg2)); tmp.write(arg0, arg1, arg2); } }; } objectMapper.writeValue(actualResponse, tracker.getQueue()); } } catch (ProxyTypeSerialisationException e) { log.fatal("Unable to serialise type information to client: " + e.getMessage(), e); } catch (ProxyException e) { handleException(response, objectMapper, e); } catch (Exception e) { log.error("Exception during callback: " + e.getMessage(), e); tracker.getQueue().queueCommand(CommandType.EXCEPTION, null, null, new ExceptionDetails(e.getClass().getName(), e.getMessage())); objectMapper.writeValue(response, tracker.getQueue()); } finally { s_currentHandler.set(null); } }
From source file:com.nextep.datadesigner.vcs.services.VCSFiles.java
private String getFileAsString(Connection conn, IRepositoryFile file) throws SQLException { PreparedStatement stmt = null; ResultSet rs = null;/* www. java 2 s . c o m*/ InputStream blobStream = null; InputStreamReader reader = null; StringWriter os = null; try { // Querying blob stmt = conn.prepareStatement("SELECT rf.file_content " //$NON-NLS-1$ + "FROM rep_files rf " //$NON-NLS-1$ + "WHERE rf.file_id = ? "); //$NON-NLS-1$ stmt.setLong(1, file.getUID().rawId()); rs = stmt.executeQuery(); if (rs.next()) { // Retrieving blob input stream blobStream = rs.getBinaryStream(1); if (blobStream == null) { return ""; //$NON-NLS-1$ } reader = new InputStreamReader(blobStream); // Opening output file os = new StringWriter(10240); // Large 10K buffer for efficient read char[] buffer = new char[10240]; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) >= 0) { os.write(buffer, 0, bytesRead); } return os.toString(); } else { throw new ErrorException(VCSMessages.getString("files.notFound")); //$NON-NLS-1$ } } catch (IOException e) { throw new ErrorException(VCSMessages.getString("files.readRepositoryProblem"), //$NON-NLS-1$ e); } finally { safeClose(os); safeClose(blobStream); safeClose(reader); if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } }