label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public String encryptStringWithKey(String to_be_encrypted, String aKey) { String encrypted_value = ""; char xdigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exc) { globalErrorDictionary.takeValueForKey(("Security package does not contain appropriate algorithm"), ("Security package does not contain appropriate algorithm")); log.error("Security package does not contain appropriate algorithm"); return encrypted_value; } if (to_be_encrypted != null) { byte digest[]; byte fudge_constant[]; try { fudge_constant = ("X#@!").getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudge_constant = ("X#@!").getBytes(); } byte fudgetoo_part[] = { (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)] }; int i = 0; if (aKey != null) { try { fudgetoo_part = aKey.getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudgetoo_part = aKey.getBytes(); } } messageDigest.update(fudge_constant); try { messageDigest.update(to_be_encrypted.getBytes("UTF8")); } catch (UnsupportedEncodingException uee) { messageDigest.update(to_be_encrypted.getBytes()); } messageDigest.update(fudgetoo_part); digest = messageDigest.digest(); encrypted_value = new String(fudgetoo_part); for (i = 0; i < digest.length; i++) { int mashed; char temp[] = new char[2]; if (digest[i] < 0) { mashed = 127 + (-1 * digest[i]); } else { mashed = digest[i]; } temp[0] = xdigit[mashed / 16]; temp[1] = xdigit[mashed % 16]; encrypted_value = encrypted_value + (new String(temp)); } } return encrypted_value; } Code Sample 2: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
11
Code Sample 1: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); } Code Sample 2: private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
00
Code Sample 1: HttpURLConnection getHttpURLConnection(String bizDocToExecute, boolean doom, boolean cmt) { StringBuffer servletURL = new StringBuffer(); servletURL.append(getBaseServletURL()); servletURL.append("?_BIZVIEW=").append(bizDocToExecute); if (doom) { servletURL.append("&_DOOM=TRUE"); } if (cmt) { servletURL.append("&_CMT=TRUE"); } Map<String, Object> inputParms = getInputParams(); if (inputParms != null) { Set<Entry<String, Object>> entrySet = inputParms.entrySet(); for (Entry<String, Object> entry : entrySet) { String name = entry.getKey(); String value = entry.getValue().toString(); servletURL.append("&").append(name).append("=").append(value); } } HttpURLConnection connection = null; try { URL url = new URL(servletURL.toString()); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { Assert.fail("Failed to connect to the test servlet: " + e); } return connection; } Code Sample 2: public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
11
Code Sample 1: public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } } Code Sample 2: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } }
11
Code Sample 1: public static String encryptStringWithSHA2(String input) { String output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(input.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } output = sb.toString(); return output; } Code Sample 2: private String md5Digest(String plain) throws Exception { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(plain.trim().getBytes()); byte pwdDigest[] = digest.digest(); StringBuilder md5buffer = new StringBuilder(); for (int i = 0; i < pwdDigest.length; i++) { int number = 0xFF & pwdDigest[i]; if (number <= 0xF) { md5buffer.append('0'); } md5buffer.append(Integer.toHexString(number)); } return md5buffer.toString(); }
00
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } }
11
Code Sample 1: public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
00
Code Sample 1: public void testHandler() throws MalformedURLException, IOException { assertTrue("This test can only be run once in a single JVM", imageHasNotBeenInstalledInThisJVM); URL url; Handler.installImageUrlHandler((ImageSource) new ClassPathXmlApplicationContext("org/springframework/richclient/image/application-context.xml").getBean("imageSource")); try { url = new URL("image:test"); imageHasNotBeenInstalledInThisJVM = false; } catch (MalformedURLException e) { fail("protocol was not installed"); } url = new URL("image:image.that.does.not.exist"); try { url.openConnection(); fail(); } catch (NoSuchImageResourceException e) { } url = new URL("image:test.image.key"); url.openConnection(); } Code Sample 2: private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
11
Code Sample 1: private static String computeSHA(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(input.getBytes("UTF-8")); byte[] code = md.digest(); return convertToHex(code); } catch (NoSuchAlgorithmException e) { log.error("Algorithm SHA-1 not found!", e); e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { log.error("Encoding problem: UTF-8 not supported!", e); e.printStackTrace(); return null; } } Code Sample 2: private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; }
11
Code Sample 1: public TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); } Code Sample 2: protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
00
Code Sample 1: public static void get_PK_data() { try { FileWriter file_writer = new FileWriter("xml_data/PK_data_dump.xml"); BufferedWriter file_buffered_writer = new BufferedWriter(file_writer); URL fdt = new URL("http://opendata.5t.torino.it/get_pk"); URLConnection url_connection = fdt.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(url_connection.getInputStream())); String input_line; int num_lines = 0; while ((input_line = in.readLine()) != null) { file_buffered_writer.write(input_line + "\n"); num_lines++; } System.out.println("Parking :: Writed " + num_lines + " lines."); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } Code Sample 2: public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } }
00
Code Sample 1: public void test_calculateLastModifiedSizeContent() { File file; String content = "Hello, world!"; String expected; FileETag etag; try { file = File.createTempFile("temp", "txt"); file.deleteOnExit(); FileOutputStream out = new FileOutputStream(file); out.write(content.getBytes()); out.flush(); out.close(); SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); long lastModified = date.parse("06/21/2007 11:19:36").getTime(); file.setLastModified(lastModified); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(content.getBytes()); StringBuffer buffer = new StringBuffer(); buffer.append(lastModified); buffer.append(content.length()); expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes()))); etag = new FileETag(); etag.setFlags(FileETag.FLAG_CONTENT | FileETag.FLAG_MTIME | FileETag.FLAG_SIZE); String value = etag.calculate(file); assertEquals("Unexpected value", expected, value); } catch (FileNotFoundException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IOException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (ParseException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); fail("Unexpected exception"); } } Code Sample 2: private void streamBinaryData(String urlstr, String format, ServletOutputStream outstr, HttpServletResponse resp) { String ErrorStr = null; try { resp.setContentType(getMimeType(format)); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL(urlstr); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); resp.setContentLength(length); InputStream in = urlc.getInputStream(); bis = new BufferedInputStream(in); bos = new BufferedOutputStream(outstr); byte[] buff = new byte[length]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); ErrorStr = "Error Streaming the Data"; outstr.print(ErrorStr); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (outstr != null) { outstr.flush(); outstr.close(); } } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: protected Properties load(URL url) { try { InputStream i = url.openStream(); Properties p = new Properties(); p.load(i); i.close(); return p; } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; } Code Sample 2: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } }
00
Code Sample 1: public void deleteMessageBuffer(String messageBufferName) throws AppFabricException { MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String messageBufferUri = msgBufferUtilObj.getCreateMessageBufferUri(messageBufferName); String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } try { messageBufferUri = messageBufferUri.replaceAll("http", "https"); URL urlConn = new URL(messageBufferUri); HttpURLConnection connection; if (httpWebProxy_ != null) connection = (HttpURLConnection) urlConn.openConnection(httpWebProxy_); else connection = (HttpURLConnection) urlConn.openConnection(); connection.setRequestMethod("DELETE"); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_ATOM_XML()); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.DeleteMessageBuffer_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if ((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_OK)) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); } else { throw new AppFabricException("MessageBuffer could not be deleted.Error...Response code: " + connection.getResponseCode()); } if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.DeleteMessageBuffer_RESPONSE); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } } Code Sample 2: public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
00
Code Sample 1: public String buscaSAIKU() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("SAIKU")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")) { miLinea = inputLine; log.debug(miLinea); miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build SAIKU: " + miLinea); return miLinea; } Code Sample 2: public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
11
Code Sample 1: public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; }
00
Code Sample 1: public void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } } Code Sample 2: private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); }
11
Code Sample 1: private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); } Code Sample 2: @Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { String pathInfo = httpServletRequest.getPathInfo(); log.info("PathInfo: " + pathInfo); if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo; log.info("FileName: " + fileName); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getDataSource().getConnection(); ps = con.prepareStatement("select file, size from files where name=?"); ps.setString(1, fileName); rs = ps.executeQuery(); if (rs.next()) { httpServletResponse.setContentType(getServletContext().getMimeType(fileName)); httpServletResponse.setContentLength(rs.getInt("size")); OutputStream os = httpServletResponse.getOutputStream(); org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os); os.flush(); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (SQLException e) { throw new ServletException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } if (con != null) try { con.close(); } catch (SQLException e) { } } } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
11
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
00
Code Sample 1: public void delete(String fileToDelete) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, Config.getFtpPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp delete server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.enterLocalPassiveMode(); log.debug("Deleted: " + ftp.deleteFile(fileToDelete)); ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } } Code Sample 2: private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; }
00
Code Sample 1: public static String MD5(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException { String text = convertToHex(data); MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String getRefCatastral(String pURL) { String result = new String(); String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); result = str.substring(ini, fin); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); result = result.concat(str.substring(ini, fin)); } } } in.close(); } catch (Exception e) { System.err.println(e); } return result; }
11
Code Sample 1: public GetMyDocuments() { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMyDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "mydocuments.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "mydocuments.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("document"); int num = nodelist.getLength(); myDocsData = new String[num][4]; myDocsToolTip = new String[num]; myDocumentImageName = new String[num]; myDocIds = new int[num]; for (int i = 0; i < num; i++) { myDocsData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename")); myDocsData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project")); myDocsData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "deadline")); myDocsData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "workingfolder")); myDocsToolTip[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "title")); myDocumentImageName[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename")); myDocIds[i] = (new Integer(new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")))).intValue(); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException ex) { } catch (Exception ex) { System.out.println(ex); } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
00
Code Sample 1: public static String encodeByMd5(String str) { try { if (str == null) { str = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes("utf-8")); byte[] b = md5.digest(); int i; StringBuffer buff = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buff.append("0"); } buff.append(Integer.toHexString(i)); } return buff.toString(); } catch (Exception e) { return str; } } Code Sample 2: public void doUpdateByIP() throws Exception { if (!isValidate()) { throw new CesSystemException("User_session.doUpdateByIP(): Illegal data values for update"); } Connection con = null; PreparedStatement ps = null; String strQuery = "UPDATE " + Common.USER_SESSION_TABLE + " SET " + "session_id = ?, user_id = ?, begin_date = ? , " + " mac_no = ?, login_id= ? " + "WHERE ip_address = ?"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); ps.setString(1, this.sessionID); ps.setInt(2, this.user.getUserID()); ps.setTimestamp(3, this.beginDate); ps.setString(4, this.macNO); ps.setString(5, this.loginID); ps.setString(6, this.ipAddress); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("User_session.doUpdateByIP(): ERROR updating data in T_SYS_USER_SESSION!! " + "resultCount = " + resultCount); } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("User_session.doUpdateByIP(): SQLException while updating user_session; " + "session_id = " + this.sessionID + " :\n\t" + se); } finally { con.setAutoCommit(true); closePreparedStatement(ps); closeConnection(dbo); } }
11
Code Sample 1: public void copyFile2(String src, String dest) throws IOException { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + MM.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(MM.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
11
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } Code Sample 2: public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); }
00
Code Sample 1: public static URL getComponentXmlFileWith(String name) throws Exception { List<URL> all = getComponentXmlFiles(); for (URL url : all) { InputStream stream = null; try { stream = url.openStream(); Element root = XML.getRootElement(stream); for (Element elem : (List<Element>) root.elements()) { String ns = elem.getNamespace().getURI(); if (name.equals(elem.attributeValue("name"))) { return url; } } } finally { Resources.closeStream(stream); } } return null; } Code Sample 2: private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } }
00
Code Sample 1: private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); } Code Sample 2: private static InputStream openFileOrURL(String url) throws IOException { if (url.startsWith("resource:")) { return DcmRcv.class.getClassLoader().getResourceAsStream(url.substring(9)); } try { return new URL(url).openStream(); } catch (MalformedURLException e) { return new FileInputStream(url); } }
11
Code Sample 1: private void convertFile() { final File fileToConvert = filePanel.getInputFile(); final File convertedFile = filePanel.getOutputFile(); if (fileToConvert == null || convertedFile == null) { Main.showMessage("Select valid files for both input and output"); return; } if (fileToConvert.getName().equals(convertedFile.getName())) { Main.showMessage("Input and Output files are same.. select different files"); return; } final int len = (int) fileToConvert.length(); progressBar.setMinimum(0); progressBar.setMaximum(len); progressBar.setValue(0); try { fileCopy(fileToConvert, fileToConvert.getAbsolutePath() + ".bakup"); } catch (IOException e) { Main.showMessage("Unable to Backup input file"); return; } final BufferedReader bufferedReader; try { bufferedReader = new BufferedReader(new FileReader(fileToConvert)); } catch (FileNotFoundException e) { Main.showMessage("Unable to create reader - file not found"); return; } final BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter(new FileWriter(convertedFile)); } catch (IOException e) { Main.showMessage("Unable to create writer for output file"); return; } String input; try { while ((input = bufferedReader.readLine()) != null) { if (stopRequested) { break; } bufferedWriter.write(parseLine(input)); bufferedWriter.newLine(); progressBar.setValue(progressBar.getValue() + input.length()); } } catch (IOException e) { Main.showMessage("Unable to convert " + e.getMessage()); return; } finally { try { bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { Main.showMessage("Unable to close reader/writer " + e.getMessage()); return; } } if (!stopRequested) { filePanel.readOutputFile(); progressBar.setValue(progressBar.getMaximum()); Main.setStatus("Transliterate Done."); } progressBar.setValue(progressBar.getMinimum()); } Code Sample 2: private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } }
00
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: @Override protected Object transform(Row inputs) throws FunctionException { StringBuffer buffer = new StringBuffer(); for (IColumn c : inputs.getColumns()) { buffer.append(c.getValueAsString() + "|"); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(buffer.toString().getBytes()); byte[] hash = digest.digest(); return getHex(hash); } catch (Exception e) { throw new FunctionException(e); } }
00
Code Sample 1: public static Image getPluginImage(final Object plugin, final String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public ForkJavaProject(String projectName, Class<?> activatorClass) { this.activatorClass = activatorClass; try { IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot(); this.prj = rootWorkspace.getProject(projectName); if (this.prj.exists()) { this.prj.delete(true, true, new NullProgressMonitor()); } this.prj.create(new NullProgressMonitor()); this.prj.open(new NullProgressMonitor()); IProjectDescription description = this.prj.getDescription(); description.setNatureIds(new String[] { "org.eclipse.jdt.core.javanature" }); this.prj.setDescription(description, new NullProgressMonitor()); createProjectDir(Constants.Dirs.DIR_MAIN_JAVA); createProjectDir(Constants.Dirs.DIR_CONFIG); createProjectDir(Constants.Dirs.DIR_MAIN_RESOURCES); createProjectDir(Constants.Dirs.DIR_MODELS); createProjectDir(Constants.Dirs.DIR_TESTS_JAVA); createProjectDir(Constants.Dirs.DIR_TESTS_RESOURCES); createProjectDir(Constants.Dirs.DIR_CLASSES); createProjectDir(Constants.Dirs.DIR_LIB); this.prj.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); this.javaProject = JavaCore.create(this.prj); if (this.javaProject.exists() && !this.javaProject.isOpen()) { this.javaProject.open(new NullProgressMonitor()); } File javaHome = new File(System.getProperty("java.home")); IPath jreLibPath = new Path(javaHome.getPath()).append("lib").append("rt.jar"); this.javaProject.setOutputLocation(prj.getFolder(Constants.Dirs.DIR_CLASSES).getFullPath(), new NullProgressMonitor()); JavaCore.setClasspathVariable("JRE_LIB", jreLibPath, new NullProgressMonitor()); this.javaProject.setRawClasspath(getProjectClassPath(), new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID, "An exception has been thrown while creating Project", e)); } } Code Sample 2: private RemoteObject createRemoteObject(final VideoEntry videoEntry, final RemoteContainer container) throws RemoteException { MessageDigest instance; try { instance = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RemoteException(StatusCreator.newStatus("Error creating MD5", e)); } StringWriter sw = new StringWriter(); YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup(); if (mediaGroup != null) { if (mediaGroup.getDescription() != null) { sw.append(mediaGroup.getDescription().getPlainTextContent()); } List<MediaCategory> keywordsGroup = mediaGroup.getCategories(); StringBuilder sb = new StringBuilder(); if (keywordsGroup != null) { for (MediaCategory mediaCategory : keywordsGroup) { sb.append(mediaCategory.getContent()); } } } instance.update(sw.toString().getBytes()); RemoteObject remoteVideo = InfomngmntFactory.eINSTANCE.createRemoteObject(); remoteVideo.setHash(asHex(instance.digest())); remoteVideo.setId(SiteInspector.getId(videoEntry.getHtmlLink().getHref())); remoteVideo.setName(videoEntry.getTitle().getPlainText()); remoteVideo.setRepositoryTypeObjectId(KEY_VIDEO); remoteVideo.setWrappedObject(videoEntry); setInternalUrl(remoteVideo, container); return remoteVideo; }
00
Code Sample 1: public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void createSaveServiceProps() throws MojoExecutionException { saveServiceProps = new File(workDir, "saveservice.properties"); try { FileWriter out = new FileWriter(saveServiceProps); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("saveservice.properties"), out); out.flush(); out.close(); System.setProperty("saveservice_properties", File.separator + "target" + File.separator + "jmeter" + File.separator + "saveservice.properties"); } catch (IOException e) { throw new MojoExecutionException("Could not create temporary saveservice.properties", e); } } Code Sample 2: private static String makeTempTraceFile(String base) throws IOException { File temp = File.createTempFile(base, ".trace"); temp.deleteOnExit(); FileChannel dstChannel = new FileOutputStream(temp).getChannel(); FileChannel srcChannel = new FileInputStream(base + ".key").getChannel(); long size = dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = new FileInputStream(base + ".data").getChannel(); dstChannel.transferFrom(srcChannel, size, srcChannel.size()); srcChannel.close(); dstChannel.close(); return temp.getPath(); }
11
Code Sample 1: public void add(String user, String pass, boolean admin, boolean developer) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql; if (contains(stmt, user) == true) { sql = "update Principals set Password = '" + pass + "' " + " where PrincipalId = '" + user + "'"; } else { sql = "insert into Principals (PrincipalId, Password) " + " values ('" + user + "', '" + pass + "')"; } stmt.executeUpdate(sql); updateRoles(stmt, user, admin, developer); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public void deletePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; } Code Sample 2: public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); }
00
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) { Statement stmt = query.getStatement(); String fileDeclaration = stmt.getFile(); boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration); if (hasFileDeclaration) { try { URL url = sqlDeclarations.get(stmt.getFile()); if (url != null) { URLConnection conn = url.openConnection(); InputStream input = conn.getInputStream(); String sqlDeclaration = StreamUtils.obtainStreamContents(input); stmt.setValue(sqlDeclaration); input.close(); } } catch (Exception e) { } } }
11
Code Sample 1: public static void copyFiles(String strPath, String trgPath) { File src = new File(strPath); File trg = new File(trgPath); if (src.isDirectory()) { if (trg.exists() != true) trg.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i]; String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i]; copyFiles(strPath_1, trgPath_1); } } else { try { FileChannel srcChannel = new FileInputStream(strPath).getChannel(); FileChannel dstChannel = new FileOutputStream(trgPath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { System.out.println("[Error] File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("[Error] " + e.getMessage()); } } } Code Sample 2: private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public Main(String[] args) { boolean encrypt = false; if (args[0].compareTo("-e") == 0) { encrypt = true; } else if (args[0].compareTo("-d") == 0) { encrypt = false; } else { System.out.println("first argument is invalid"); System.exit(-2); } char[] password = new char[args[2].length()]; for (int i = 0; i < args[2].length(); i++) { password[i] = (char) args[2].getBytes()[i]; } try { InitializeCipher(encrypt, password); } catch (Exception e) { System.out.println("error initializing cipher"); System.exit(-3); } try { InputStream is = new FileInputStream(args[1]); OutputStream os; int read, max = 10; byte[] buffer = new byte[max]; if (encrypt) { os = new FileOutputStream(args[1] + ".enc"); os = new CipherOutputStream(os, cipher); } else { os = new FileOutputStream(args[1] + ".dec"); is = new CipherInputStream(is, cipher); } read = is.read(buffer); while (read != -1) { os.write(buffer, 0, read); read = is.read(buffer); } while (read == max) ; os.close(); is.close(); System.out.println(new String(buffer)); } catch (Exception e) { System.out.println("error encrypting/decrypting message:"); e.printStackTrace(); System.exit(-4); } System.out.println("done"); } Code Sample 2: public static String readFromUrl(String url) { URL url_ = null; URLConnection uc = null; BufferedReader in = null; StringBuilder str = new StringBuilder(); try { url_ = new URL(url); uc = url_.openConnection(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) str.append(inputLine); in.close(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); }
00
Code Sample 1: public static void createZipFromDataset(String localResourceId, File dataset, File metadata) { CommunicationLogger.warning("System entered ZipFactory"); try { String tmpDir = System.getProperty("java.io.tmpdir"); String outFilename = tmpDir + "/" + localResourceId + ".zip"; CommunicationLogger.warning("File name: " + outFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(dataset); out.putNextEntry(new ZipEntry(dataset.getName())); int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in = new FileInputStream(metadata); out.putNextEntry(new ZipEntry(metadata.getName())); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.closeEntry(); in.close(); out.close(); } catch (IOException e) { System.out.println("IO EXCEPTION: " + e.getMessage()); } } Code Sample 2: protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
00
Code Sample 1: public static String convertStringToMD5(String toEnc) { try { MessageDigest mdEnc = MessageDigest.getInstance("MD5"); mdEnc.update(toEnc.getBytes(), 0, toEnc.length()); return new BigInteger(1, mdEnc.digest()).toString(16); } catch (Exception e) { return null; } } Code Sample 2: public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
11
Code Sample 1: public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean copy(long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { PojoParser parser = PojoParser.getInstances(); conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getClass().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; } Code Sample 2: private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
00
Code Sample 1: public void actionPerformed(ActionEvent event) { System.out.println("STARTING on" + getQueryField().getText()); try { URL url = new URL(getQueryField().getText()); getResponseField().setText("opening URL"); DataInputStream inputStream = new DataInputStream(url.openStream()); getResponseField().setText("collating response"); String line = inputStream.readLine(); String totalString = ""; while (line != null) { totalString += line + "\n"; line = inputStream.readLine(); } System.out.println("FINISHING"); getResponseField().setText(totalString); System.out.println("FINISHED"); } catch (Exception exception) { getResponseField().setText(exception.getMessage() + "\n"); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } } Code Sample 2: public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
00
Code Sample 1: public static synchronized void loadConfig(String configFile) { if (properties != null) { return; } URL url = null; InputStream is = null; try { String configProperty = null; try { configProperty = System.getProperty("dspace.configuration"); } catch (SecurityException se) { log.warn("Unable to access system properties, ignoring.", se); } if (loadedFile != null) { log.info("Reloading current config file: " + loadedFile.getAbsolutePath()); url = loadedFile.toURI().toURL(); } else if (configFile != null) { log.info("Loading provided config file: " + configFile); loadedFile = new File(configFile); url = loadedFile.toURI().toURL(); } else if (configProperty != null) { log.info("Loading system provided config property (-Ddspace.configuration): " + configProperty); loadedFile = new File(configProperty); url = loadedFile.toURI().toURL(); } else { url = ConfigurationManager.class.getResource("/dspace.cfg"); if (url != null) { log.info("Loading from classloader: " + url); loadedFile = new File(url.getPath()); } } if (url == null) { log.fatal("Cannot find dspace.cfg"); throw new IllegalStateException("Cannot find dspace.cfg"); } else { properties = new Properties(); moduleProps = new HashMap<String, Properties>(); is = url.openStream(); properties.load(is); for (Enumeration<?> pe = properties.propertyNames(); pe.hasMoreElements(); ) { String key = (String) pe.nextElement(); String value = interpolate(key, properties.getProperty(key), 1); if (value != null) { properties.setProperty(key, value); } } } } catch (IOException e) { log.fatal("Can't load configuration: " + url, e); throw new IllegalStateException("Cannot load configuration: " + url, e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } } File licenseFile = new File(getProperty("dspace.dir") + File.separator + "config" + File.separator + "default.license"); FileInputStream fir = null; InputStreamReader ir = null; BufferedReader br = null; try { fir = new FileInputStream(licenseFile); ir = new InputStreamReader(fir, "UTF-8"); br = new BufferedReader(ir); String lineIn; license = ""; while ((lineIn = br.readLine()) != null) { license = license + lineIn + '\n'; } br.close(); } catch (IOException e) { log.fatal("Can't load license: " + licenseFile.toString(), e); throw new IllegalStateException("Cannot load license: " + licenseFile.toString(), e); } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { } } if (ir != null) { try { ir.close(); } catch (IOException ioe) { } } if (fir != null) { try { fir.close(); } catch (IOException ioe) { } } } } Code Sample 2: public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
11
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public void load() throws ResourceInstantiationException { if (null == url) { throw new ResourceInstantiationException("URL not set (null)."); } try { BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING); String line; LinearNode node; while (null != (line = defReader.readLine())) { node = new LinearNode(line); try { this.add(node); } catch (GateRuntimeException ex) { throw new ResourceInstantiationException(ex); } } defReader.close(); isModified = false; } catch (Exception x) { throw new ResourceInstantiationException(x); } }
00
Code Sample 1: public static void bubble_sort(int[] objects, int len) { for (int i = len; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j + 1] < objects[j]) { int tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } } Code Sample 2: @Test public void pk() throws Exception { Connection conn = s.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into t_test(t_name,t_cname,t_data,t_date,t_double) values(?,?,?,?,?)"); for (int i = 10; i < 20; ++i) { ps.setString(1, "name-" + i); ps.setString(2, "cname-" + i); ps.setBlob(3, null); ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); ps.setNull(5, java.sql.Types.DOUBLE); ps.executeUpdate(); } conn.rollback(); conn.setAutoCommit(true); ps.close(); conn.close(); }
11
Code Sample 1: public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
11
Code Sample 1: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); } Code Sample 2: @Test public void testRegister() { try { String username = "muchu"; String password = "123"; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); LogService logServiceMock = EasyMock.createMock(LogService.class); DbService dbServiceMock = EasyMock.createMock(DbService.class); userServ.setDbServ(dbServiceMock); userServ.setLogger(logServiceMock); IFeelerUser user = new FeelerUserImpl(); user.setUsername(username); user.setPassword(passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(null); dbServiceMock.addFeelerUser(username, passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(user); EasyMock.replay(dbServiceMock, logServiceMock); Assert.assertTrue(userServ.register(username, password)); EasyMock.verify(dbServiceMock, logServiceMock); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
11
Code Sample 1: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; } Code Sample 2: protected void copyFile(final String sourceFileName, final File path) throws IOException { final File source = new File(sourceFileName); final File destination = new File(path, source.getName()); FileChannel srcChannel = null; FileChannel dstChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); srcChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destination); dstChannel = fileOutputStream.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { if (dstChannel != null) { dstChannel.close(); } } catch (Exception exception) { } try { if (srcChannel != null) { srcChannel.close(); } } catch (Exception exception) { } try { fileInputStream.close(); } catch (Exception exception) { } try { fileOutputStream.close(); } catch (Exception exception) { } } }
11
Code Sample 1: private static void copy(String srcFilename, String dstFilename, boolean override) throws IOException, XPathFactoryConfigurationException, SAXException, ParserConfigurationException, XPathExpressionException { File fileToCopy = new File(rootDir + "test-output/" + srcFilename); if (fileToCopy.exists()) { File newFile = new File(rootDir + "test-output/" + dstFilename); if (!newFile.exists() || override) { try { FileChannel srcChannel = new FileInputStream(rootDir + "test-output/" + srcFilename).getChannel(); FileChannel dstChannel = new FileOutputStream(rootDir + "test-output/" + dstFilename).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private void writeMessage(ChannelBuffer buffer, File dst) throws IOException { ChannelBufferInputStream is = new ChannelBufferInputStream(buffer); OutputStream os = null; try { os = new FileOutputStream(dst); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); } } Code Sample 2: public void run() { try { Debug.log("Integrity test", "Getting MD5 instance"); MessageDigest m = MessageDigest.getInstance("MD5"); Debug.log("Integrity test", "Creating URL " + target); URL url = new URL(this.target); Debug.log("Integrity test", "Setting up connection"); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; Debug.log("Integrity test", "Reading file"); while ((numRead = in.read(buffer)) != -1) { m.update(buffer, 0, numRead); fileSize += numRead; } in.close(); Debug.log("Integrity test", "File read: " + fileSize + " bytes"); Debug.log("Integrity test", "calculating Hash"); String fileHash = new BigInteger(1, m.digest()).toString(16); if (fileHash.equals(this.hash)) { Debug.log("Integrity test", "Test OK"); this.result.put("Integrity", "OK"); } else { Debug.log("Integrity test", "Test failed: different hashes (" + fileHash + " but expected " + hash + ")"); this.result.put("Integrity", "FAIL"); } } catch (Exception e) { Debug.log("Integrity test", "Test failed"); this.result.put("Integrity", "FAIL"); } }
00
Code Sample 1: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; } Code Sample 2: public static Properties load(URL url) { if (url == null) { return new Properties(); } InputStream in = null; try { in = url.openStream(); Properties ret = new Properties(); ret.load(in); return ret; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error("Error closing", e); } } } }
00
Code Sample 1: protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } } Code Sample 2: public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
00
Code Sample 1: private String encryptUserPassword(int userId, String password) { password = password.trim(); if (password.length() == 0) { return ""; } else { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new BoardRuntimeException(ex); } md.update(String.valueOf(userId).getBytes()); md.update(password.getBytes()); byte b[] = md.digest(); StringBuffer sb = new StringBuffer(1 + b.length * 2); for (int i = 0; i < b.length; i++) { int ii = b[i]; if (ii < 0) { ii = 256 + ii; } sb.append(getHexadecimalValue2(ii)); } return sb.toString(); } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(sourceFile); os = new FileOutputStream(destFile); IOUtils.copy(is, os); } finally { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
11
Code Sample 1: public void createMd5Hash() { try { String vcardObject = new ContactToVcard(TimeZone.getTimeZone("UTC"), "UTF-8").convert(this); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(vcardObject.getBytes()); this.md5Hash = new BigInteger(m.digest()).toString(); if (log.isTraceEnabled()) { log.trace("Hash is:" + this.md5Hash); } } catch (ConverterException ex) { log.error("Error creating hash:" + ex.getMessage()); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { log.error("Error creating hash:" + noSuchAlgorithmException.getMessage()); } } Code Sample 2: public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
11
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.connect(ftpHost); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return null; } if (!ftp.login(ftpUsername, ftpPassword)) { return null; } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; } Code Sample 2: private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); }
00
Code Sample 1: public PollSetMessage(String username, String question, String title, String[] choices) { this.username = username; MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } String id = username + String.valueOf(System.nanoTime()); m.update(id.getBytes(), 0, id.length()); voteId = new BigInteger(1, m.digest()).toString(16); this.question = question; this.title = title; this.choices = choices; } Code Sample 2: public static List<ReactomeBean> getUrlData(URL url) throws IOException { List<ReactomeBean> beans = new ArrayList<ReactomeBean>(256); log.debug("Retreiving content for: " + url); StringBuffer content = new StringBuffer(4096); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("#")) { continue; } StringTokenizer stringTokenizer = new StringTokenizer(str, "\t"); String InteractionAc = stringTokenizer.nextToken(); String reactomeId = stringTokenizer.nextToken(); ReactomeBean reactomeBean = new ReactomeBean(); reactomeBean.setReactomeID(reactomeId); reactomeBean.setInteractionAC(InteractionAc); beans.add(reactomeBean); } in.close(); return beans; }
00
Code Sample 1: public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } }
00
Code Sample 1: public String loadGeneratorXML() { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.getFolienKonvertierungsServer().getUrl()); System.out.println("Connected to " + this.getFolienKonvertierungsServer().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return null; } if (!ftp.login(this.getFolienKonvertierungsServer().getFtpBenutzer(), this.getFolienKonvertierungsServer().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String path; if (this.getFolienKonvertierungsServer().getDefaultPath().length() > 0) { path = "/" + this.getFolienKonvertierungsServer().getDefaultPath() + "/" + this.getId() + "/"; } else { path = "/" + this.getId() + "/"; } if (!ftp.changeWorkingDirectory(path)) System.err.println("Konnte Verzeichnis nicht wechseln: " + path); System.err.println("Arbeitsverzeichnis: " + ftp.printWorkingDirectory()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); InputStream inStream = ftp.retrieveFileStream("generator.xml"); if (inStream == null) { System.err.println("Job " + this.getId() + ": Datei generator.xml wurde nicht gefunden"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(inStream)); generatorXML = ""; String zeile = ""; while ((zeile = in.readLine()) != null) { generatorXML += zeile + "\n"; } in.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei generator.xml konnte nicht vom Webserver kopiert werden."); e.printStackTrace(); } catch (Exception e) { System.err.println("Job " + this.getId() + ": Datei generator.xml konnte nicht vom Webserver kopiert werden."); e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } if (generatorXML != null && generatorXML.length() == 0) { generatorXML = null; } return generatorXML; } Code Sample 2: public static void downloadURLNow(URL url, File to, SHA1Sum sha1, boolean force) throws Exception { { String sep = System.getProperty("file.separator"); String folders = to.getPath(); String path = ""; for (int i = 0; i < folders.length(); i++) { path += folders.charAt(i); if (path.endsWith(sep)) { File f = new File(path); if (!f.exists()) f.mkdir(); if (!f.isDirectory()) { Out.error(URLDownloader.class, path + " is not a directory!"); return; } } } } Out.info(URLDownloader.class, "Downloading " + url.toExternalForm()); URLConnection uc = url.openConnection(); DataInputStream is = new DataInputStream(new BufferedInputStream(uc.getInputStream())); FileOutputStream os = new FileOutputStream(to); byte[] b = new byte[1024]; int fileLength = uc.getHeaderFieldInt("Content-Length", 0) / b.length; Task task = null; if (fileLength > 0) task = TaskManager.createTask(url.toExternalForm(), fileLength, "kB"); do { int c = is.read(b); if (c == -1) break; os.write(b, 0, c); if (task != null) task.advanceProgress(); } while (true); if (task != null) task.complete(); os.close(); is.close(); }
11
Code Sample 1: public void testGetOldVersion() throws ServiceException, IOException, SAXException, ParserConfigurationException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Read again at:" + secondSource.getSourceRevision()); InputStream expected = emptySource.getInputStream(); InputStream actual = secondSource.getInputStream(); assertTrue(isXmlEqual(expected, actual)); } Code Sample 2: public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); }
11
Code Sample 1: public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private void executeRequest(OperationContext context) throws java.lang.Throwable { long t1 = System.currentTimeMillis(); DirectoryParams params = context.getRequestOptions().getDirectoryOptions(); try { String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.directory"); HashMap<String, String> poiProperties = params.getPoiProperties(); Set<String> keys = poiProperties.keySet(); Iterator<String> iter = keys.iterator(); StringBuffer filter = new StringBuffer(); while (iter.hasNext()) { String key = iter.next(); QueryFilter queryFilter = new QueryFilter(key, poiProperties.get(key)); filter.append(makePOIRequest(queryFilter)); } String sUrl = srvCfg + "/query?" + filter.toString(); LOGGER.info("REQUEST=\n" + sUrl); URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); url = null; parsePOIResponse(sResponse, params); } catch (Exception p_e) { LOGGER.severe("Throwing exception" + p_e.getMessage()); throw p_e; } finally { long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } }
00
Code Sample 1: public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: public ArrayList parseFile(File newfile) throws IOException { String s; String firstName; String header; String name = null; Integer PVLoggerID = new Integer(0); String[] tokens; int nvalues = 0; double num1, num2, num3; double xoffset = 1.0; double xdelta = 1.0; double yoffset = 1.0; double ydelta = 1.0; double zoffset = 1.0; double zdelta = 1.0; boolean readfit = false; boolean readraw = false; boolean zerodata = false; boolean baddata = false; boolean harpdata = false; ArrayList fitparams = new ArrayList(); ArrayList xraw = new ArrayList(); ArrayList yraw = new ArrayList(); ArrayList zraw = new ArrayList(); ArrayList sraw = new ArrayList(); ArrayList sxraw = new ArrayList(); ArrayList syraw = new ArrayList(); ArrayList szraw = new ArrayList(); URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; firstName = (String) tokens[0]; if (((String) tokens[0]).length() == 0) { readraw = false; readfit = false; continue; } if ((nvalues == 4) && (!firstName.startsWith("---"))) { if ((Double.parseDouble(tokens[1]) == 0.) && (Double.parseDouble(tokens[2]) == 0.) && (Double.parseDouble(tokens[3]) == 0.)) { zerodata = true; } else { zerodata = false; } if (tokens[1].equals("NaN") || tokens[2].equals("NaN") || tokens[3].equals("NaN")) { baddata = true; } else { baddata = false; } } if (firstName.startsWith("start")) { header = s; } if (firstName.indexOf("WS") > 0) { if (name != null) { dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); } name = tokens[0]; readraw = false; readfit = false; zerodata = false; baddata = false; harpdata = false; fitparams.clear(); xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); } if (firstName.startsWith("Area")) ; if (firstName.startsWith("Ampl")) ; if (firstName.startsWith("Mean")) ; if (firstName.startsWith("Sigma")) { fitparams.add(new Double(Double.parseDouble(tokens[3]))); fitparams.add(new Double(Double.parseDouble(tokens[1]))); fitparams.add(new Double(Double.parseDouble(tokens[5]))); } if (firstName.startsWith("Offset")) ; if (firstName.startsWith("Slope")) ; if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Raw"))) { readraw = true; continue; } if ((firstName.equals("Position")) && (((String) tokens[2]).equals("Fit"))) { readfit = true; continue; } if ((firstName.contains("Harp"))) { xraw.clear(); yraw.clear(); zraw.clear(); sraw.clear(); sxraw.clear(); syraw.clear(); szraw.clear(); harpdata = true; readraw = true; name = tokens[0]; continue; } if (firstName.startsWith("---")) continue; if (harpdata == true) { if (((String) tokens[0]).length() != 0) { if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } else { sxraw.add(new Double(Double.parseDouble(tokens[0]))); xraw.add(new Double(Double.parseDouble(tokens[1]))); syraw.add(new Double(Double.parseDouble(tokens[2]))); yraw.add(new Double(Double.parseDouble(tokens[3]))); szraw.add(new Double(Double.parseDouble(tokens[4]))); zraw.add(new Double(Double.parseDouble(tokens[5]))); } } continue; } if (readraw && (!zerodata) && (!baddata)) { sraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); sxraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); syraw.add(new Double(Double.parseDouble(tokens[0]) / Math.sqrt(2.0))); szraw.add(new Double(Double.parseDouble(tokens[0]))); yraw.add(new Double(Double.parseDouble(tokens[1]))); zraw.add(new Double(Double.parseDouble(tokens[2]))); xraw.add(new Double(Double.parseDouble(tokens[3]))); } if (firstName.startsWith("PVLogger")) { try { PVLoggerID = new Integer(Integer.parseInt(tokens[2])); } catch (NumberFormatException e) { } } } dumpData(name, fitparams, sraw, sxraw, syraw, szraw, yraw, zraw, xraw); wiredata.add((Integer) PVLoggerID); return wiredata; }
00
Code Sample 1: public static void main(String args[]) { if (args.length < 1) { printUsage(); } URL url; BufferedReader in = null; try { url = new URL(args[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode == 200) { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = in.readLine()) != null) { System.out.println(line); } } else { System.out.println("Response code " + responseCode + " means there was an error reading url " + args[0]); } } catch (IOException e) { System.err.println("IOException attempting to read url " + args[0]); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception ignore) { } } } } Code Sample 2: public void readContents() throws IOException { fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_START, 0.0f, "loading file")); URLConnection conn = url.openConnection(); conn.connect(); filesize = conn.getContentLength(); logger.finest("filesize: " + filesize); InputStreamReader in = new InputStreamReader(conn.getInputStream()); readFirstLine(in); readHeaderLines(in); readData(in); fireProgressEvent(new ProgressEvent(this, ProgressEvent.PROGRESS_FINISH, 1.0f, "loading file")); }
11
Code Sample 1: public void exe2(String[] args) { Connection con = null; Connection con2 = null; Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = getConnection("mis030dv"); con2 = getConnection("mis030db"); con2.setAutoCommit(false); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM MIS.MAP_PUR0101 WHERE NOT EXISTS (SELECT 1 FROM MIS.RSCMGOOD@MIS030DB@DEVU01 WHERE GOODCD = PUM_CODE OR GOODCD = NEW_PUM_CODE)"); pstmt = con2.prepareStatement("INSERT INTO MIS.RSCMGOOD ( GOODCD,GOODFLAG,GOODNM,GOODHNGNM,GOODENGNM,GOODSPEC,GOODMODEL,ASETFLAG,LRGCD,MDLCD,SMLCD,EDICD,PRODCMPYCD,CMT,FSTRGSTRID,FSTRGSTDT,LASTUPDTRID,LASTUPDTDT,APPINSTDATA,MNGTFLAG) " + "VALUES ( ?,SUBSTR(?,1,1),?,?,?,?,NULL,'1',substr(?,2,2),substr(?,4,3),NULL,NULL,NULL,'OCS �����빰ǰ','MISASIS',TO_DATE('20111231','YYYYMMDD'),'MISASIS',TO_DATE('20111231','YYYYMMDD'),NULL,'N')"); int count = 0; String goodcd = null; String goodnm = null; while (rs.next()) { count++; goodcd = rs.getString("PUM_CODE").toUpperCase(); goodnm = rs.getString("PUM_HNAME"); StringUtils.trimWhitespace(goodnm); if (goodnm == null || goodnm.equals("")) goodnm = "-"; pstmt.setString(1, goodcd); pstmt.setString(2, goodcd); pstmt.setString(3, goodnm); pstmt.setString(4, goodnm); pstmt.setString(5, rs.getString("PUM_ENAME")); pstmt.setString(6, rs.getString("KYUKYEOK")); pstmt.setString(7, goodcd); pstmt.setString(8, goodcd); pstmt.executeUpdate(); if (count % 100 == 0) System.out.println("Copy Row : " + count); } System.out.println("Commit Copy Rows : " + count); con2.commit(); } catch (Exception e) { try { con2.rollback(); } catch (Exception ee) { ee.printStackTrace(); } e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); if (con2 != null) con2.close(); } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: protected void doBackupOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "(version_no,parent_organize_type,child_organize_type) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strSelQuery); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setInt(1, this.versionNO); ps.setString(2, result.getString("parent_organize_type")); ps.setString(3, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION_B INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doBackupOrganizeTypeRelation(): SQLException while committing or rollback"); } }
00
Code Sample 1: public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException { File file = new File(folder, key.toString()); LOGGER.debug("Writing file: " + file.getAbsolutePath()); Writer writer = null; Writer encodedWriter = null; try { encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset()); IOUtils.copy(stream, encodedWriter, getDecodeCharset()); LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset()); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } finally { try { encodedWriter.close(); } catch (IOException e) { throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e); } } }
00
Code Sample 1: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } } Code Sample 2: public void updateSuccessStatus(ArrayList<THLEventStatus> succeededEvents, ArrayList<THLEventStatus> skippedEvents) throws THLException { Statement stmt = null; PreparedStatement pstmt = null; try { conn.setAutoCommit(false); if (succeededEvents != null && succeededEvents.size() > 0) { stmt = conn.createStatement(); String seqnoList = buildCommaSeparatedList(succeededEvents); stmt.executeUpdate("UPDATE " + history + " SET status = " + THLEvent.COMPLETED + ", processed_tstamp = " + conn.getNowFunction() + " WHERE seqno in " + seqnoList); } if (skippedEvents != null && skippedEvents.size() > 0) { pstmt = conn.prepareStatement("UPDATE " + history + " SET status = ?, comments = ?," + " processed_tstamp = ? WHERE seqno = ?"); Timestamp now = new Timestamp(System.currentTimeMillis()); for (THLEventStatus event : skippedEvents) { pstmt.setShort(1, THLEvent.SKIPPED); pstmt.setString(2, truncate(event.getException() != null ? event.getException().getMessage() : "Unknown event failure", commentLength)); pstmt.setTimestamp(3, now); pstmt.setLong(4, event.getSeqno()); pstmt.addBatch(); } pstmt.executeBatch(); pstmt.close(); } conn.commit(); } catch (SQLException e) { THLException exception = new THLException("Failed to update events status"); exception.initCause(e); try { conn.rollback(); } catch (SQLException e1) { THLException exception2 = new THLException("Failed to rollback after failure while updating events status"); e1.initCause(exception); exception2.initCause(e1); exception = exception2; } throw exception; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException ignore) { } } try { conn.setAutoCommit(true); } catch (SQLException ignore) { } } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: protected static void writeFileToStream(FileWrapper file, String filename, ZipOutputStream zipStream) throws CausedIOException, IOException { InputStream in; try { in = file.getInputStream(); } catch (Exception e) { throw new CausedIOException("Could not obtain InputStream for " + filename, e); } try { IOUtils.copy(in, zipStream); } finally { IOUtils.closeQuietly(in); } }
00
Code Sample 1: private String md5(String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } Code Sample 2: public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) { try { Class.forName("org.sqlite.JDBC"); String fileName = pictogramsPath + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { int idL = 0, idT = 0; G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\""); while (rs.next()) { idL = rs.getInt("id"); } rs.close(); stat.close(); stat = G.conn.createStatement(); rs = stat.executeQuery("select id from type where name=\"" + type + "\""); while (rs.next()) { idT = rs.getInt("id"); } rs.close(); stat.close(); String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length()); String idOrig = id; String pathSrc = pictogramToAddPath; String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, word.toLowerCase()); stmt.setInt(2, idL); stmt.setInt(3, idT); stmt.setString(4, id); stmt.setString(5, idOrig); stmt.executeUpdate(); stmt.close(); G.conn.close(); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private static String doGetForSessionKey(String authCode) throws Exception { String sessionKey = ""; HttpClient hc = new DefaultHttpClient(); HttpGet hg = new HttpGet(Common.TEST_SESSION_HOST + Common.TEST_SESSION_PARAM + authCode); HttpResponse hr = hc.execute(hg); BufferedReader br = new BufferedReader(new InputStreamReader(hr.getEntity().getContent())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } String result = sb.toString(); Log.i("sessionKeyMessages", result); Map<String, String> map = Util.handleURLParameters(result); sessionKey = map.get(Common.TOP_SESSION); String topParameters = map.get(Common.TOP_PARAMETERS); String decTopParameters = Util.decodeBase64(topParameters); Log.i("base64", decTopParameters); map = Util.handleURLParameters(decTopParameters); Log.i("nick", map.get(Common.VISITOR_NICK)); CachePool.put(Common.VISITOR_NICK, map.get(Common.VISITOR_NICK)); return sessionKey; } Code Sample 2: private String fetchURL(String url) { StringBuilder content = new StringBuilder(); String line; BufferedReader input = null; try { URL urlToFetch = new URL(url); input = new BufferedReader(new InputStreamReader(urlToFetch.openStream())); while ((line = input.readLine()) != null) { content.append(line); } input.close(); return content.toString(); } catch (java.io.IOException ex) { return null; } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
00
Code Sample 1: public static void main(String[] args) throws IOException { System.out.println("start"); URL url = new URL("https://spreadsheets.google.com/feeds/list/" + "0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/" + "od7/public/basic"); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { String[] mass = line.split("<entry>"); for (String m : mass) { System.out.println(m); } } } Code Sample 2: public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
00
Code Sample 1: @Test public void testValidLogConfiguration() throws IOException, IllegalArgumentException { URL url = ClassLoader.getSystemResource(PROPERTIES_FILE_NAME); if (url == null) { throw new IOException("Could not find configuration file " + PROPERTIES_FILE_NAME + " in class path"); } Properties properties = new Properties(); properties.load(url.openStream()); LogLevel logLevel = LogLevel.valueOf((String) properties.get(PROPERTY_KEY_LOGLEVEL)); if (logLevel == null) { throw new IOException("Invalid configuration file " + PROPERTIES_FILE_NAME + ": no entry for " + PROPERTY_KEY_LOGLEVEL); } String loggerIdentifier = "Test logger"; Logger logger = LoggerFactory.getLogger(loggerIdentifier); assertEquals("Logger has wrong log level", logLevel, logger.getLogLevel()); } Code Sample 2: public static String encrypt32(String plainText) { String str = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } str = buf.toString(); System.out.println("result: " + buf.toString()); System.out.println("result: " + buf.toString().substring(8, 24)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return str; } return str; }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getServerCertificates", args = { }) public final void test_getServerCertificates() throws Exception { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getServerCertificates(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); try { Certificate[] cert = con.getServerCertificates(); fail("SSLPeerUnverifiedException wasn't thrown"); } catch (SSLPeerUnverifiedException e) { } con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); try { Certificate[] cert = con.getServerCertificates(); assertNotNull(cert); assertEquals(1, cert.length); } catch (Exception e) { fail("Unexpected exception " + e); } }
11
Code Sample 1: private void convertFile() { final File fileToConvert = filePanel.getInputFile(); final File convertedFile = filePanel.getOutputFile(); if (fileToConvert == null || convertedFile == null) { Main.showMessage("Select valid files for both input and output"); return; } if (fileToConvert.getName().equals(convertedFile.getName())) { Main.showMessage("Input and Output files are same.. select different files"); return; } final int len = (int) fileToConvert.length(); progressBar.setMinimum(0); progressBar.setMaximum(len); progressBar.setValue(0); try { fileCopy(fileToConvert, fileToConvert.getAbsolutePath() + ".bakup"); } catch (IOException e) { Main.showMessage("Unable to Backup input file"); return; } final BufferedReader bufferedReader; try { bufferedReader = new BufferedReader(new FileReader(fileToConvert)); } catch (FileNotFoundException e) { Main.showMessage("Unable to create reader - file not found"); return; } final BufferedWriter bufferedWriter; try { bufferedWriter = new BufferedWriter(new FileWriter(convertedFile)); } catch (IOException e) { Main.showMessage("Unable to create writer for output file"); return; } String input; try { while ((input = bufferedReader.readLine()) != null) { if (stopRequested) { break; } bufferedWriter.write(parseLine(input)); bufferedWriter.newLine(); progressBar.setValue(progressBar.getValue() + input.length()); } } catch (IOException e) { Main.showMessage("Unable to convert " + e.getMessage()); return; } finally { try { bufferedReader.close(); bufferedWriter.close(); } catch (IOException e) { Main.showMessage("Unable to close reader/writer " + e.getMessage()); return; } } if (!stopRequested) { filePanel.readOutputFile(); progressBar.setValue(progressBar.getMaximum()); Main.setStatus("Transliterate Done."); } progressBar.setValue(progressBar.getMinimum()); } Code Sample 2: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
11
Code Sample 1: public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } Code Sample 2: private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
00
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new ScalableRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getEditorInput().getAdapter(ScannedMap.class)); return viewer; }
11
Code Sample 1: public void executeUpdate(Native nativeResource) throws Exception { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; try { HrRecord hr = getRepository(); ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); String sql = ""; boolean isUpdate = false; String sUuid = ""; boolean finableBeforeUpdate = false; if (UuidUtil.isUuid(hr.getUuid())) { sUuid = hr.getUuid(); finableBeforeUpdate = queryFindable(con); sql = createUpdateSQL(); st = con.prepareStatement(sql); isUpdate = true; } else { sUuid = UuidUtil.makeUuid(true); finableBeforeUpdate = hr.getFindable(); sql = createInsertSQL(); st = con.prepareStatement(sql); } if (hr.getOwnerId() < 0) { hr.setOwnerId(getOwner().getLocalID()); } int n = 1; st.setInt(n++, hr.getOwnerId()); st.setTimestamp(n++, makeTimestamp(hr.getInputDate())); st.setTimestamp(n++, makeTimestamp(hr.getUpdateDate())); st.setString(n++, hr.getName()); st.setString(n++, hr.getHostUrl()); st.setString(n++, hr.getHarvestFrequency().toString()); st.setString(n++, Boolean.toString(hr.getSendNotification())); st.setString(n++, hr.getProtocol().getKind().toLowerCase()); st.setString(n++, ProtocolSerializer.toXmlString(hr.getProtocol())); st.setString(n++, PublicationMethod.registration.name()); if (!isUpdate) { if (getRequestContext().getApplicationConfiguration().getHarvesterConfiguration().getResourceAutoApprove()) { st.setString(n++, ApprovalStatus.approved.name()); } else { st.setString(n++, ApprovalStatus.posted.name()); } } st.setString(n++, Boolean.toString(hr.getSearchable())); st.setString(n++, Boolean.toString(hr.getSynchronizable())); st.setString(n++, sUuid); logExpression(sql); int nRowCount = st.executeUpdate(); getActionResult().setNumberOfRecordsModified(nRowCount); if (!isUpdate && nRowCount == 1) { closeStatement(st); st = con.prepareStatement("SELECT ID FROM " + getHarvestingTableName() + " WHERE UPPER(DOCUUID)=?"); st.setString(1, sUuid.toUpperCase()); ResultSet genKeys = st.executeQuery(); genKeys.next(); int nLocalId = genKeys.getInt(1); hr.setLocalId(nLocalId); hr.setUuid(sUuid); closeResultSet(genKeys); } con.commit(); if (nativeResource != null || (isUpdate && finableBeforeUpdate != hr.getFindable())) { try { if (nativeResource == null && isUpdate) { nativeResource = queryNative(con); } if (nativeResource != null) { String content = nativeResource.getContent(); String sourceUri = nativeResource.getSourceUri().asString(); Publisher publisher = createPublisherOfRepository(); PublicationRequest publicationRequest = createPublicationRequest(publisher, content, sourceUri); publicationRequest.publish(); } } catch (Exception ex) { LOGGER.log(Level.INFO, "Unable to create resource definition.", ex); } } Harvester harvestEngine = getRequestContext().getApplicationContext().getHarvestingEngine(); if (_repository.getIsHarvestDue()) { harvestEngine.submit(getRequestContext(), _repository, null, _repository.getLastSyncDate()); } harvestEngine.reselect(); } catch (Exception ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } } Code Sample 2: public int getDBVersion() throws MigrationException { int dbVersion; PreparedStatement ps; try { Connection conn = getConnection(); ps = conn.prepareStatement("SELECT version FROM " + getTablename()); try { ResultSet rs = ps.executeQuery(); try { if (rs.next()) { dbVersion = rs.getInt(1); if (rs.next()) { throw new MigrationException("Too many version in table: " + getTablename()); } } else { ps.close(); ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)"); ps.setInt(1, 1); try { ps.executeUpdate(); } finally { ps.close(); } dbVersion = 1; } } finally { rs.close(); } } finally { ps.close(); } } catch (SQLException e) { logger.log(Level.WARNING, "Could not access " + tablename + ": " + e); dbVersion = 0; Connection conn = getConnection(); try { if (!conn.getAutoCommit()) { conn.rollback(); } conn.setAutoCommit(false); } catch (SQLException e1) { throw new MigrationException("Could not reset transaction state", e1); } } return dbVersion; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void main(String[] args) { if (args.length < 1) { System.out.println("Parameters: method arg1 arg2 arg3 etc"); System.out.println(""); System.out.println("Methods:"); System.out.println(" reloadpolicies"); System.out.println(" migratedatastreamcontrolgroup"); System.exit(0); } String method = args[0].toLowerCase(); if (method.equals("reloadpolicies")) { if (args.length == 4) { try { reloadPolicies(args[1], args[2], args[3]); System.out.println("SUCCESS: Policies have been reloaded"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: Reloading policies failed; see above"); System.exit(1); } } else { System.err.println("ERROR: Three arguments required: " + "http|https username password"); System.exit(1); } } else if (method.equals("migratedatastreamcontrolgroup")) { if (args.length > 10) { System.err.println("ERROR: too many arguments provided"); System.exit(1); } if (args.length < 7) { System.err.println("ERROR: insufficient arguments provided. Arguments are: "); System.err.println(" protocol [http|https]"); System.err.println(" user"); System.err.println(" password"); System.err.println(" pid - either"); System.err.println(" a single pid, eg demo:object"); System.err.println(" list of pids separated by commas, eg demo:object1,demo:object2"); System.err.println(" name of file containing pids, eg file:///path/to/file"); System.err.println(" dsid - either"); System.err.println(" a single datastream id, eg DC"); System.err.println(" list of ids separated by commas, eg DC,RELS-EXT"); System.err.println(" controlGroup - target control group (note only M is implemented)"); System.err.println(" addXMLHeader - add an XML header to the datastream [true|false, default false]"); System.err.println(" reformat - reformat the XML [true|false, default false]"); System.err.println(" setMIMETypeCharset - add charset=UTF-8 to the MIMEType [true|false, default false]"); System.exit(1); } try { boolean addXMLHeader = getArgBoolean(args, 7, false); boolean reformat = getArgBoolean(args, 8, false); boolean setMIMETypeCharset = getArgBoolean(args, 9, false); ; InputStream is = modifyDatastreamControlGroup(args[1], args[2], args[3], args[4], args[5], args[6], addXMLHeader, reformat, setMIMETypeCharset); IOUtils.copy(is, System.out); is.close(); System.out.println("SUCCESS: Datastreams modified"); System.exit(0); } catch (Throwable th) { th.printStackTrace(); System.err.println("ERROR: migrating datastream control group failed; see above"); System.exit(1); } } else { System.err.println("ERROR: unrecognised method " + method); System.exit(1); } }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void postProcess() throws StopWriterVisitorException { dbfWriter.postProcess(); try { short originalEncoding = dbf.getDbaseHeader().getLanguageID(); File dbfFile = fTemp; FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(file).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); close(); RandomAccessFile fo = new RandomAccessFile(file, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); open(file); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (CloseDriverException e) { throw new StopWriterVisitorException(getName(), e); } catch (OpenDriverException e) { throw new StopWriterVisitorException(getName(), e); } }
11
Code Sample 1: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); } Code Sample 2: public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public boolean addMeFile(File f) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(directory + f.getName()))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); if (!PatchManager.mute) System.out.println("added : " + directory + f.getName()); } catch (IOException e) { System.out.println("copy directory : " + e); return false; } return true; }
00
Code Sample 1: private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; } Code Sample 2: public void run() { try { if (sync == SyncType.SyncSpaced || sync == SyncType.Spaced) { Thread.sleep(spaceMillis); } URL url = new URL(surl + "&requestId=" + runnumber); long t0 = System.currentTimeMillis(); InputStream in = url.openStream(); transfer(in, new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); BufferedImage image = ImageIO.read(new File(outputFolder, "" + runnumber + ".png")); status.score(runnumber, System.currentTimeMillis() - t0); ImageIO.write(image, "png", new FileOutputStream(new File(outputFolder, "" + runnumber + ".png"))); if (false) { int whiteCount = 0; for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { whiteCount += image.getRGB(i, j) == -1 ? 1 : 0; } } System.err.println("##" + runnumber + "#: " + whiteCount); if (whiteCount < 227564) { System.err.println("whiteCount fails!!!!"); System.err.println("whiteCount fails!!!!"); System.exit(0); } } } catch (Exception ex) { System.err.println("##" + runnumber + "#: Exception!!! ###"); ex.printStackTrace(); status.score(runnumber, -999); } }
00
Code Sample 1: static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } } Code Sample 2: protected BufferedImage handleRaremapsException() { if (params.uri.startsWith("http://www.raremaps.com/cgi-bin/gallery.pl/detail/")) try { params.uri = params.uri.replace("cgi-bin/gallery.pl/detail", "maps/medium"); URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static File copyFile(String path) { File src = new File(path); File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
00
Code Sample 1: public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; } Code Sample 2: public InputStream getResourceAsStream(String name) { try { URL url = getResource(name); System.out.println("Loading \"" + url + "\"..."); URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); System.out.println(httpURLConnection.getResponseMessage() + ", " + httpURLConnection.getContentLength() + " bytes" + ", " + new Date(httpURLConnection.getDate()) + ", " + new Date(httpURLConnection.getLastModified())); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } } return urlConnection.getInputStream(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private void logoutUser(String session) { try { String data = URLEncoder.encode("SESSION", "UTF-8") + "=" + URLEncoder.encode("" + session, "UTF-8"); if (_log != null) _log.error("Voice: logoutUser = " + m_strUrl + "LogoutUserServlet&" + data); URL url = new URL(m_strUrl + "LogoutUserServlet"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); wr.close(); rd.close(); } catch (Exception e) { if (_log != null) _log.error("Voice error : " + e); } }
11
Code Sample 1: public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static void redirect(String strRequest, PrintWriter sortie) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.GFI"); URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); DataInputStream buffin = new DataInputStream(new BufferedInputStream(conn.getInputStream())); String strLine = null; while ((strLine = buffin.readLine()) != null) { sortie.println(strLine); } buffin.close(); } Code Sample 2: public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
11
Code Sample 1: public static AddUserResponse napiUserAdd(String user, String pass, String email) throws TimeoutException, InterruptedException, IOException { if (user.matches("^[a-zA-Z0-9]{2,20}$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_LOGIN; } if (pass.equals("")) { return AddUserResponse.NAPI_ADD_USER_BAD_PASS; } if (email.matches("^[a-zA-Z0-9\\-\\_]{1,30}@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_EMAIL; } URLConnection conn = null; ClientHttpRequest httpPost = null; InputStreamReader responseStream = null; URL url = new URL("http://www.napiprojekt.pl/users_add.php"); conn = url.openConnection(Global.getProxy()); httpPost = new ClientHttpRequest(conn); httpPost.setParameter("login", user); httpPost.setParameter("haslo", pass); httpPost.setParameter("mail", email); httpPost.setParameter("z_programu", "true"); responseStream = new InputStreamReader(httpPost.post(), "Cp1250"); BufferedReader responseReader = new BufferedReader(responseStream); String response = responseReader.readLine(); if (response.indexOf("login już istnieje") != -1) { return AddUserResponse.NAPI_ADD_USER_LOGIN_EXISTS; } if (response.indexOf("na podany e-mail") != -1) { return AddUserResponse.NAPI_ADD_USER_EMAIL_EXISTS; } if (response.indexOf("NPc0") == 0) { return AddUserResponse.NAPI_ADD_USER_OK; } return AddUserResponse.NAPI_ADD_USER_BAD_UNKNOWN; } Code Sample 2: public String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
11
Code Sample 1: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; } Code Sample 2: public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }