label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } Code Sample 2: public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
11
Code Sample 1: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
00
Code Sample 1: private void getPage(final String path, final String dataToSend, final GetPageCallback callback) { runner.add(new Runnable() { @Override public void run() { String url = "http://" + resources.getString(R.string.host) + path; HttpUriRequest req; if (dataToSend == null) { req = new HttpGet(url); } else { req = new HttpPost(url); try { ((HttpPost) req).setEntity(new StringEntity(dataToSend)); } catch (UnsupportedEncodingException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "Unsupported encoding.", e); } } req.addHeader("Cookie", getAuthCookie(false)); try { HttpResponse response = httpclient.execute(req); Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Response status is '" + response.getStatusLine() + "'."); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader in = new BufferedReader(new InputStreamReader(instream)); StringBuilder b = new StringBuilder(); String line; boolean first = true; while ((line = in.readLine()) != null) { b.append(line); if (first) { first = false; } else { b.append("\r\n"); } } in.close(); callback.success(b.toString()); return; } catch (RuntimeException ex) { throw ex; } finally { instream.close(); } } } catch (ClientProtocolException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "HTTP protocol violated.", e); } catch (IOException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.WARNING, "Could not load '" + path + "'.", e); } Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Calling error from JSBridge.getPage because of previous errors."); callback.error(); } }); } Code Sample 2: public ValidationReport validate(OriginalDeployUnitDescription unit) throws UnitValidationException { ValidationReport vr = new DefaultValidationReport(); errorHandler = new SimpleErrorHandler(vr); vr.setFileUri(unit.getAbsolutePath()); SAXParser parser; SAXReader reader = null; try { parser = factory.newSAXParser(); reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(this.errorHandler); } catch (ParserConfigurationException e) { throw new UnitValidationException("The configuration of parser is illegal.", e); } catch (SAXException e) { String m = "Something is wrong when register schema"; logger.error(m, e); throw new UnitValidationException(m, e); } ZipInputStream zipInputStream; InputStream tempInput = null; try { tempInput = new FileInputStream(unit.getAbsolutePath()); } catch (FileNotFoundException e1) { String m = String.format("The file [%s] don't exist.", unit.getAbsolutePath()); logger.error(m, e1); throw new UnitValidationException(m, e1); } zipInputStream = new ZipInputStream(tempInput); ZipEntry zipEntry = null; try { zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { String m = String.format("Error when get zipEntry. Maybe the [%s] is not zip file!", unit.getAbsolutePath()); logger.error(m); throw new UnitValidationException(m); } while (zipEntry != null) { if (configFiles.contains(zipEntry.getName())) { byte[] extra = new byte[(int) zipEntry.getSize()]; zipInputStream.read(extra); File file = File.createTempFile("temp", "extra"); file.deleteOnExit(); logger.info("[TempFile:]" + file.getAbsoluteFile()); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(extra); FileOutputStream tempFileOutputStream = new FileOutputStream(file); IOUtils.copy(byteInputStream, tempFileOutputStream); tempFileOutputStream.flush(); IOUtils.closeQuietly(tempFileOutputStream); InputStream inputStream = new FileInputStream(file); reader.read(inputStream, unit.getAbsolutePath() + ":" + zipEntry.getName()); IOUtils.closeQuietly(inputStream); } zipEntry = zipInputStream.getNextEntry(); } } catch (IOException e) { ValidationMessage vm = new XMLValidationMessage("IOError", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } catch (DocumentException e) { ValidationMessage vm = new XMLValidationMessage("Document Error.", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } finally { IOUtils.closeQuietly(tempInput); IOUtils.closeQuietly(zipInputStream); } return vr; }
11
Code Sample 1: public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } } Code Sample 2: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: @Test public void testFromFile() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor_float.net"), new FileOutputStream(temp)); Fann fann = new Fann(temp.getPath()); assertEquals(2, fann.getNumInputNeurons()); assertEquals(1, fann.getNumOutputNeurons()); assertEquals(-1f, fann.run(new float[] { -1, -1 })[0], .2f); assertEquals(1f, fann.run(new float[] { -1, 1 })[0], .2f); assertEquals(1f, fann.run(new float[] { 1, -1 })[0], .2f); assertEquals(-1f, fann.run(new float[] { 1, 1 })[0], .2f); fann.close(); } Code Sample 2: 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; }
11
Code Sample 1: public static boolean copyFile(String source, String destination, boolean replace) { File sourceFile = new File(source); File destinationFile = new File(destination); if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false; if (destinationFile.isFile() && !replace) return false; if (!sourceFile.isFile()) return false; if (replace) destinationFile.delete(); try { File dir = destinationFile.getParentFile(); while (dir != null && !dir.exists()) { dir.mkdir(); } DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240)); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240)); try { while (inStream.available() > 0) { outStream.write(inStream.readUnsignedByte()); } } catch (EOFException eof) { } inStream.close(); outStream.close(); } catch (IOException ex) { throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath()); } return true; } Code Sample 2: private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
11
Code Sample 1: public static synchronized String encrypt(String plaintext) throws SinaduraCoreException { MessageDigest md = null; String hash = null; try { md = MessageDigest.getInstance("SHA"); try { md.update(plaintext.getBytes(CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { throw new SinaduraCoreException(e.getMessage(), e); } byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException e) { throw new SinaduraCoreException(e.getMessage(), e); } return hash; } Code Sample 2: public static String digest(String password) { try { byte[] digest; synchronized (__md5Lock) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.warn(e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { Log.warn(e); return null; } }
00
Code Sample 1: public void insertRight(final String right) throws IOException { try { Connection conn = null; boolean autoCommit = false; try { conn = pool.getConnection(); autoCommit = conn.getAutoCommit(); conn.setAutoCommit(true); final PreparedStatement insert = conn.prepareStatement("insert into rights (name) values (?)"); insert.setString(1, right); insert.executeUpdate(); } catch (Throwable t) { if (conn != null) conn.rollback(); throw new SQLException(t.toString()); } finally { if (conn != null) { conn.setAutoCommit(autoCommit); conn.close(); } } } catch (final SQLException sqle) { log.log(Level.SEVERE, sqle.toString(), sqle); throw new IOException(sqle.toString()); } } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
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: private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } }
11
Code Sample 1: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } } Code Sample 2: public void modifyDecisionInstruction(int id, int condition, String frameSlot, String linkName, int objectId, String attribute, int positive, int negative) throws FidoDatabaseException, ObjectNotFoundException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { if ((condition == ConditionalOperatorTable.CONTAINS_LINK) || (condition == ConditionalOperatorTable.NOT_CONTAINS_LINK)) { ObjectTable ot = new ObjectTable(); if (ot.contains(objectId) == false) throw new ObjectNotFoundException(objectId); } conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, positive) == false) throw new InstructionNotFoundException(positive); if (contains(stmt, negative) == false) throw new InstructionNotFoundException(negative); String sql = "update Instructions set Operator = " + condition + ", " + " FrameSlot = '" + frameSlot + "', " + " LinkName = '" + linkName + "', " + " ObjectId = " + objectId + ", " + " AttributeName = '" + attribute + "' " + "where InstructionId = " + id; stmt.executeUpdate(sql); InstructionGroupTable groupTable = new InstructionGroupTable(); groupTable.deleteInstruction(stmt, id); if (positive != -1) groupTable.addInstructionAt(stmt, id, 1, positive); if (negative != -1) groupTable.addInstructionAt(stmt, id, 2, negative); 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); } }
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: @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; boolean checkPassword1 = false; boolean checkPassword2 = false; sql = "select password from Usuarios where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { Tree tree1 = CreateTree(password, 0); Tree tree2 = CreateTree(password, 1); tree1.enumerateTree(tree1.root); tree2.enumerateTree(tree2.root); for (int i = 0; i < tree1.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree1.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword1 = true; break; } else checkPassword1 = false; } for (int i = 0; i < tree2.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree2.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword2 = true; break; } else checkPassword2 = false; } if (checkPassword1 == true || checkPassword2 == true) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); setTries(0); setVisible(false); Error.log(3003, "Senha pessoal verificada positivamente."); Error.log(3002, "Autentica��o etapa 2 encerrada."); PasswordTableWindow ptw = new PasswordTableWindow(login); ptw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); Error.log(3004, "Senha pessoal verificada negativamente."); int tries = getTries(); if (tries == 0) { Error.log(3005, "Primeiro erro da senha pessoal contabilizado."); } else if (tries == 1) { Error.log(3006, "Segundo erro da senha pessoal contabilizado."); } else if (tries == 2) { Error.log(3007, "Terceiro erro da senha pessoal contabilizado."); Error.log(3008, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 2."); Error.log(3002, "Autentica��o etapa 2 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } if (e.getSource() == btnClear) { passwordField.setText(""); } }
00
Code Sample 1: @Override protected IProject createProject(String projectName, IProgressMonitor monitor) throws CoreException { monitor.beginTask(CheatSheetsPlugin.INSTANCE.getString("_UI_CreateJavaProject_message", new String[] { projectName }), 5); IProject project = super.createProject(projectName, new SubProgressMonitor(monitor, 1)); if (project != null) { IProjectDescription description = project.getDescription(); if (!description.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (javaProject != null) { String[] natures = description.getNatureIds(); String[] javaNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, javaNatures, 0, natures.length); javaNatures[natures.length] = JavaCore.NATURE_ID; description.setNatureIds(javaNatures); project.setDescription(description, new SubProgressMonitor(monitor, 1)); IFolder sourceFolder = project.getFolder(SOURCE_FOLDER); if (!sourceFolder.exists()) { sourceFolder.create(true, true, new SubProgressMonitor(monitor, 1)); } javaProject.setOutputLocation(project.getFolder(OUTPUT_FOLDER).getFullPath(), new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(sourceFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")) }; javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); } } } monitor.done(); return project; } Code Sample 2: 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); } }
11
Code Sample 1: public static void copyFile(FileInputStream source, FileOutputStream target) throws Exception { FileChannel inChannel = source.getChannel(); FileChannel outChannel = target.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 static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
00
Code Sample 1: public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } } Code Sample 2: 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(); }
11
Code Sample 1: public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } } Code Sample 2: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
00
Code Sample 1: public static final String computeHash(String stringToCompile) { String retVal = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(stringToCompile.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } retVal = hexString.toString(); if (log.isDebugEnabled()) log.debug("MD5 hash for \"" + stringToCompile + "\" is: " + retVal); } catch (Exception exe) { log.error(exe.getMessage(), exe); } return retVal; } Code Sample 2: 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; }
11
Code Sample 1: private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
00
Code Sample 1: protected URLConnection openConnection(URL url) throws IOException { if (url == null) return null; if (!url.getProtocol().equals("nntp")) return null; if (m_connection != null) { if (m_connection.getURL().getHost().equals(url.getHost()) && (m_connection.getURL().getPort() == url.getPort()) && (m_connection.getURL().getUserInfo().equals(url.getUserInfo()))) { return m_connection; } } m_connection = new NNTPConnection(url); return m_connection; } Code Sample 2: public Object mapRow(ResultSet rs, int i) throws SQLException { try { BLOB blob = (BLOB) rs.getBlob(1); OutputStream outputStream = blob.setBinaryStream(0L); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (Exception e) { throw new SQLException(e.getMessage()); } return null; }
00
Code Sample 1: private void recvMessage(String from, String to) throws Exception { ConnectionFactoryImpl factory = new ConnectionFactoryImpl(); Receiver receiver = null; ProviderConnection connection = factory.createConnection(from, to); Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql = ""; try { receiver = Receiver.createReceiver(connection); receiver.open(); EXTSSPMessage message = (EXTSSPMessage) receiver.receiveEX(); if (message == null) { System.out.println("no message"); } else { conn.setAutoCommit(false); EXTSSPHeader header = message.getEXHeader(); UUIDHexGenerator u = new UUIDHexGenerator(); String id = u.generate().toString(); pstmt = conn.prepareStatement(drawOutRecvSql(header, id)); pstmt.executeUpdate(); String xml = ""; TSSPBody body = message.getBody(); xml = body.getDomAsString(); xml = xml.replaceAll("ns1:", ""); saveClobMessage(pstmt, conn, rs, xml, id); String notify_id = ""; Iterator iter = message.getAttachments(); while (iter.hasNext()) { AttachmentPart a = (AttachmentPart) iter.next(); String contentId = a.getContentId(); if (contentId.startsWith(Constant.PREFIX_PERSON)) { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); byte[] temp = FileCopyUtils.copyToByteArray(is); String content = new String(temp); RecvDto recv = (RecvDto) XStreamConvert.xmlToBean(content); if (recv == null) throw new Exception("接收方信息对象转换错误!请检查存入的信息对象xml字符串是否正确:" + content); if (notify_id.equals("")) { notify_id = u.generate().toString(); header.setType(Constant.MESSAGETYPE_NOTIFY); pstmt = conn.prepareStatement(drawOutRecvSql(header, notify_id)); pstmt.executeUpdate(); String notify_content = header.getNotifyContent(); if (notify_content == null) notify_content = "接收到新的esb消息,但未定义通知消息内容!"; saveClobMessage(pstmt, conn, rs, notify_content, notify_id); } savePersonInfo(pstmt, conn, recv, notify_id); } else { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); String attid = u.generate().toString(); sql = "insert into message_recv_attachment(ATTACHMENTID," + "VERSION,MRECVID,BUSS_ID,ATTACHMENT) values('" + attid + "',0,'" + id + "','" + contentId + "',empty_blob())"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); sql = "select attachment from message_recv_attachment" + " where attachmentid = '" + attid + "' for update"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); rs.next(); Blob blob = rs.getBlob(1); OutputStream blobOutputStream = ((oracle.sql.BLOB) blob).getBinaryOutputStream(); FileCopyUtils.copy(is, blobOutputStream); is.close(); blobOutputStream.close(); } } conn.commit(); conn.setAutoCommit(true); } receiver.commit(); } catch (Exception e) { e.printStackTrace(); try { System.out.println("received message, rollback"); if (receiver != null) { receiver.rollback(); } } catch (JAXMException e1) { e1.printStackTrace(); } } finally { DBUtil.close(rs, pstmt, conn); if (receiver != null) { try { receiver.close(); } catch (JAXMException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JAXMException e) { e.printStackTrace(); } } } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public void addPropertyColumns(WCAChannel destination, Set<Property> properties) throws SQLException { Session session = HibernateUtil.getSessionFactory().openSession(); Connection con = session.connection(); try { createPropertyTable(destination); extendPropertyList(destination, properties); Statement statement = con.createStatement(); for (Property property : properties) { String propertyName = removeBadChars(property.getName()); statement.executeUpdate(alterTable.format(new Object[] { getTableName(destination), propertyName, property.getDBColumnType() })); } con.commit(); con.close(); session.close(); } catch (SQLException e) { con.rollback(); session.close(); throw e; } } Code Sample 2: public URLConnection getConnection() throws IOException { URLConnection con = url.openConnection(); con.setConnectTimeout(30 * 1000); if (username == null || "".equals(username) || password == null || "".equals(password)) return con; if (wsseMode) { con.setRequestProperty("X-WSSE", getWsseHeaderValue()); return con; } Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { PasswordAuthentication auth = null; if (username != null && password != null) { auth = new PasswordAuthentication(username, password.toCharArray()); } return auth; } }); return con; }
11
Code Sample 1: private String copy(PluginVersionDetail usePluginVersion, File runtimeRepository) { try { File tmpFile = null; try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); tmpFile.deleteOnExit(); URL url = new URL(usePluginVersion.getUri()); String destFilename = new File(url.getFile()).getName(); File destFile = new File(runtimeRepository, destFilename); InputStream in = null; FileOutputStream out = null; int bytesDownload = 0; long startTime = 0; long endTime = 0; try { URLConnection urlConnection = url.openConnection(); bytesDownload = urlConnection.getContentLength(); in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); startTime = System.currentTimeMillis(); IOUtils.copy(in, out); endTime = System.currentTimeMillis(); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } String downloadSpeedInfo = null; long downloadSpeed = 0; if ((endTime - startTime) > 0) { downloadSpeed = 1000L * bytesDownload / (endTime - startTime); } if (downloadSpeed == 0) { downloadSpeedInfo = "? B/s"; } else if (downloadSpeed < 1000) { downloadSpeedInfo = downloadSpeed + " B/s"; } else if (downloadSpeed < 1000000) { downloadSpeedInfo = downloadSpeed / 1000 + " KB/s"; } else if (downloadSpeed < 1000000000) { downloadSpeedInfo = downloadSpeed / 1000000 + " MB/s"; } else { downloadSpeedInfo = downloadSpeed / 1000000000 + " GB/s"; } String tmpFileMessageDigest = getMessageDigest(tmpFile.toURI().toURL()).getValue(); if (!tmpFileMessageDigest.equals(usePluginVersion.getMessageDigest().getValue())) { throw new RuntimeException("Downloaded file: " + usePluginVersion.getUri() + " does not have required message digest: " + usePluginVersion.getMessageDigest().getValue()); } if (!isNoop()) { FileUtils.copyFile(tmpFile, destFile); } return bytesDownload + " Bytes " + downloadSpeedInfo; } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download " + usePluginVersion.getUri() + " to " + runtimeRepository, ex); } } Code Sample 2: public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException { InputStream in; if (infile != null) in = new FileInputStream(infile); else in = System.in; OutputStream out; outfile.createNewFile(); if (outfile != null) out = new FileOutputStream(outfile); else out = System.out; if (from == null) from = System.getProperty("file.encoding"); if (to == null) to = "Unicode"; Reader r = new BufferedReader(new InputStreamReader(in, from)); Writer w = new BufferedWriter(new OutputStreamWriter(out, to)); char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); r.close(); w.close(); }
11
Code Sample 1: public static synchronized String encrypt(String plaintext) throws SinaduraCoreException { MessageDigest md = null; String hash = null; try { md = MessageDigest.getInstance("SHA"); try { md.update(plaintext.getBytes(CHARSET_UTF8)); } catch (UnsupportedEncodingException e) { throw new SinaduraCoreException(e.getMessage(), e); } byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException e) { throw new SinaduraCoreException(e.getMessage(), e); } return hash; } Code Sample 2: public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception ex) { throw new RuntimeException(ex); } }
11
Code Sample 1: private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
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 copyFromHDFSMerge(String hdfsDir, String local) throws IOException { rmr(local); File f = new File(local); f.getAbsoluteFile().getParentFile().mkdirs(); HDFSDirInputStream inp = new HDFSDirInputStream(hdfsDir); FileOutputStream oup = new FileOutputStream(local); IOUtils.copyBytes(inp, oup, 65 * 1024 * 1024, true); }
11
Code Sample 1: protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } } Code Sample 2: public String getMD5Str(String str) { MessageDigest messageDigest = null; String mdStr = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } mdStr = md5StrBuff.toString(); return mdStr; }
11
Code Sample 1: private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } } Code Sample 2: private static String fetchFile(String urlLocation) { try { URL url = new URL(urlLocation); URLConnection conn = url.openConnection(); File tempFile = File.createTempFile("marla", ".jar"); OutputStream os = new FileOutputStream(tempFile); IOUtils.copy(conn.getInputStream(), os); return tempFile.getAbsolutePath(); } catch (IOException ex) { throw new MarlaException("Unable to fetch file '" + urlLocation + "' from server", ex); } }
00
Code Sample 1: public static void doHttpPost(String urlName, byte[] data, String contentType, String cookieData) throws InteropException { URL url = getAccessURL(urlName); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookieData); connection.setRequestProperty("Content-type", contentType); connection.setRequestProperty("Content-length", "" + data.length); OutputStream stream = connection.getOutputStream(); stream.write(data); stream.flush(); stream.close(); connection.connect(); InputStream inputStream = connection.getInputStream(); inputStream.close(); } catch (IOException ex) { throw new InteropException("Error POSTing to " + urlName, ex); } } Code Sample 2: public static void downloadXrefTask(String url, String file) { int n, progressi, progressn; if (debug) System.err.println("Downloading " + url + " into " + file); Progress progress = Progress.crNew(null, "Downloading xref task"); FileOutputStream oo = null; InputStream ii = null; try { URLConnection con = new URL(url).openConnection(); ii = con.getInputStream(); File of = new File(file); if (!of.getParentFile().exists()) { of.getParentFile().mkdir(); } oo = new FileOutputStream(of); byte buffer[] = new byte[XREF_DOWNLOAD_BUFFER_SIZE]; progressi = 0; progressn = con.getContentLength(); n = 1; while (n >= 0) { n = ii.read(buffer, 0, XREF_DOWNLOAD_BUFFER_SIZE); if (n > 0) { oo.write(buffer, 0, n); progressi += n; } if (!progress.setProgress(progressi * 100 / progressn)) { n = -2; } } ii.close(); oo.close(); fileSetExecPermission(file); if (n == -2) { of.delete(); } } catch (Exception e) { try { if (oo != null) { oo.close(); new File(file).delete(); } if (ii != null) ii.close(); } catch (Exception ee) { } progress.setVisible(false); JOptionPane.showMessageDialog(null, e.toString() + "\nWhile downloading " + url + ".\nMaybe wrong proxy configuration?", "Xrefactory Error", JOptionPane.ERROR_MESSAGE); } progress.setVisible(false); }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; }
00
Code Sample 1: public Document parse(InputSource is) throws SAXException, IOException { LSInput input = ls.createLSInput(); String systemId = is.getSystemId(); InputStream in = is.getByteStream(); if (in != null) { input.setByteStream(in); } else { Reader reader = is.getCharacterStream(); if (reader != null) { input.setCharacterStream(reader); } else { URL url = new URL(systemId); input.setByteStream(url.openStream()); } } input.setPublicId(is.getPublicId()); input.setSystemId(systemId); input.setEncoding(is.getEncoding()); return parser.parse(input); } Code Sample 2: public DataSet(String name, String type, URL docBase, String plotDir) { sitename = name.toUpperCase(); data = new Vector[3]; data[0] = new Vector(); data[1] = new Vector(); data[2] = new Vector(); if (type == null) return; plottype = type.toLowerCase(); String filename; filename = plotDir + sitename + "_" + plottype + ".plt.gz"; try { double total = 0; URL dataurl = new URL(docBase, filename); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String myline = readme.readLine(); if (myline == null) break; myline = myline.toLowerCase(); if (myline.startsWith("fit:")) { if (haveFit) { continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); fit = new Double[5]; String bye = (String) st.nextToken(); fit[0] = new Double((String) st.nextToken()); fit[1] = new Double((String) st.nextToken()); fit[2] = new Double((String) st.nextToken()); fit[3] = new Double((String) st.nextToken()); fit[4] = new Double((String) st.nextToken()); haveFit = true; continue; } if (myline.startsWith("decyear:")) { StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); String bye = (String) st.nextToken(); decYear = new Double((String) st.nextToken()); haveDate = true; continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); boolean ok = true; String tmp; Double[] mydbl = new Double[3]; for (int i = 0; i < 3 && ok; i++) { if (st.hasMoreTokens()) { tmp = (String) st.nextToken(); if (tmp.startsWith("X") || tmp.startsWith("x")) { ok = false; break; } else { mydbl[i] = new Double(tmp); } } else { mydbl[i] = new Double(0.0); } } if (ok) { if (mydbl[2].doubleValue() > 100) continue; total = mydbl[1].doubleValue() + total; for (int i = 0; i < 3; i++) { data[i].addElement(mydbl[i]); } } } average = total / length(); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } }
11
Code Sample 1: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; } Code Sample 2: public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options) throws Exception { log.debug("Determining zip file organization..."); BosVisitor visitor = new DxpFileOrganizingBosVisitor(); visitor.visit(mapBos); if (!options.isQuiet()) log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"..."); OutputStream outStream = new FileOutputStream(outputZipFile); ZipOutputStream zipOutStream = new ZipOutputStream(outStream); ZipEntry entry = null; URI rootMapUri = mapBos.getRoot().getEffectiveUri(); URI baseUri = null; try { baseUri = AddressingUtil.getParent(rootMapUri); } catch (URISyntaxException e) { throw new BosException("URI syntax exception getting parent URI: " + e.getMessage()); } Set<String> dirs = new HashSet<String>(); if (!options.isQuiet()) log.info("Constructing DXP package..."); for (BosMember member : mapBos.getMembers()) { if (!options.isQuiet()) log.info("Adding member " + member + " to zip..."); URI relativeUri = baseUri.relativize(member.getEffectiveUri()); File temp = new File(relativeUri.getPath()); String parentPath = temp.getParent(); if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) { parentPath += "/"; } log.debug("parentPath=\"" + parentPath + "\""); if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) { entry = new ZipEntry(parentPath); zipOutStream.putNextEntry(entry); zipOutStream.closeEntry(); dirs.add(parentPath); } entry = new ZipEntry(relativeUri.getPath()); zipOutStream.putNextEntry(entry); IOUtils.copy(member.getInputStream(), zipOutStream); zipOutStream.closeEntry(); } zipOutStream.close(); if (!options.isQuiet()) log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created."); }
11
Code Sample 1: public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } } Code Sample 2: public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
11
Code Sample 1: public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), false); fileInputStream.close(); fileOutputStream.close(); destination.setLastModified(source.lastModified()); } catch (Exception e) { e.printStackTrace(); } } 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()); } }
11
Code Sample 1: public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
Code Sample 1: public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } } Code Sample 2: public static byte[] readFile(String filePath) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); FileInputStream is = new FileInputStream(filePath); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
11
Code Sample 1: public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; } 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); } }
00
Code Sample 1: public void testMemberSeek() throws IOException { GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz)); gzin.setEofEachMember(true); gzin.compressedSeek(noise1k_gz.length + noise32k_gz.length); int count2 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 1-byte member count", 1, count2); assertEquals("wrong Member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int count3 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 5-byte member count", 5, count3); assertEquals("wrong Member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int countEnd = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong eof count", 0, countEnd); } Code Sample 2: public FTPClient getFTP(final Credentials credentials, final String remoteFile) throws NumberFormatException, SocketException, IOException, AccessDeniedException { String fileName = extractFilename(remoteFile); String fileDirectory = getPathName(remoteFile).substring(0, getPathName(remoteFile).indexOf(fileName)); FTPClient ftp; ftp = new FTPClient(); loadConfig(); logger.info("FTP connection to: " + extractHostname(remoteFile)); logger.info("FTP PORT: " + prop.getProperty("port")); ftp.connect(extractHostname(remoteFile), Integer.parseInt(prop.getProperty("port"))); int reply = ftp.getReplyCode(); if (!(FTPReply.isPositiveCompletion(reply))) { return null; } ftp.setFileTransferMode(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!ftp.login(credentials.getUserName(), credentials.getPassword())) { throw new AccessDeniedException(prop.getProperty("login_message")); } if (fileDirectory != null) { ftp.changeWorkingDirectory(fileDirectory); } return ftp; }
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: @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
00
Code Sample 1: public static byte[] readFile(String filePath) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); FileInputStream is = new FileInputStream(filePath); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } } Code Sample 2: public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
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 byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
00
Code Sample 1: private void storeFieldMap(Content c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (java.util.Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } } Code Sample 2: public GGPhotoInfo getPhotoInfo(String photoId, String language) throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.getInfo")); qparams.add(new BasicNameValuePair("key", this.key)); qparams.add(new BasicNameValuePair("photo_id", photoId)); if (null != language) { qparams.add(new BasicNameValuePair("language", language)); } String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGPhotoInfo photo = JAXB.unmarshal(content, GGPhotoInfo.class); return photo; }
11
Code Sample 1: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); } Code Sample 2: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
00
Code Sample 1: public static String MD5(String text) throws ProducteevSignatureException { try { MessageDigest md; md = MessageDigest.getInstance(ALGORITHM); byte[] md5hash; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nsae) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, nsae); } catch (UnsupportedEncodingException e) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, e); } } Code Sample 2: public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
00
Code Sample 1: public static long writeInputStreamToOutputStream(final InputStream in, final OutputStream out) { long size = 0; try { size = IOUtils.copyLarge(in, out); } catch (IOException e1) { e1.printStackTrace(); } return size; } Code Sample 2: @Override public int updateStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); return statement.executeUpdate(sql); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); return 0; } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
00
Code Sample 1: protected URL[][] getImageLinks(final URL url) { Lexer lexer; URL[][] ret; if (null != url) { try { lexer = new Lexer(url.openConnection()); ret = extractImageLinks(lexer, url); } catch (Throwable t) { System.out.println(t.getMessage()); ret = NONE; } } else ret = NONE; return (ret); } Code Sample 2: 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(); } }
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 static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } } Code Sample 2: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } }
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: protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } } Code Sample 2: public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE); SecureRandom random; try { random = new SecureRandom(); md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex); throw new IOException(ex.toString()); } StringBuffer result = new StringBuffer(); uri = "smtp/" + host; String nc = "00000001"; String qop = "auth"; byte[] bytes = new byte[32]; int resp; if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ..."); Hashtable map = tokenize(serverChallenge); if (realm == null) { String text = (String) map.get("realm"); realm = text != null ? new StringTokenizer(text, ",").nextToken() : host; } String nonce = (String) map.get("nonce"); random.nextBytes(bytes); b64os.write(bytes); b64os.flush(); String cnonce = bos.toString(); bos.reset(); md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd))); md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce)); clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":"; md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri)); md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest()))); result.append("username=\"" + user + "\""); result.append(",realm=\"" + realm + "\""); result.append(",qop=" + qop); result.append(",nc=" + nc); result.append(",nonce=\"" + nonce + "\""); result.append(",cnonce=\"" + cnonce + "\""); result.append(",digest-uri=\"" + uri + "\""); result.append(",response=" + toHex(md5.digest())); if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString()); b64os.write(ASCIIUtility.getBytes(result.toString())); b64os.flush(); return bos.toByteArray(); }
00
Code Sample 1: public void test_UseCache_HttpURLConnection_NoCached_GetOutputStream() throws Exception { ResponseCache.setDefault(new MockNonCachedResponseCache()); uc = (HttpURLConnection) url.openConnection(); uc.setChunkedStreamingMode(10); uc.setDoOutput(true); uc.getOutputStream(); assertTrue(isGetCalled); assertFalse(isPutCalled); assertFalse(isAbortCalled); uc.disconnect(); } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getallpersons"); 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)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); } catch (Exception e) { e.printStackTrace(); } Toast.makeText(this, theString + "\n", Toast.LENGTH_LONG).show(); }
11
Code Sample 1: public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } } Code Sample 2: public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
00
Code Sample 1: public static String toMD5(String seed) { MessageDigest md5 = null; StringBuffer temp_sb = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(seed.getBytes()); byte[] array = md5.digest(); temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } return temp_sb.toString(); } Code Sample 2: private String sendImpl(String from, String destNumber, String text) throws IOException { final QueryStringBuilder query = new QueryStringBuilder(); query.append("user", username); query.append("password", password); query.append("api_id", apiId); query.append("to", destNumber); if (from != null) { query.append("from", from); } query.append("text", text); final URL url = new URL(CLICKATELL_GATEWAY_URL + "sendmsg" + query.toString()); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); try { return br.readLine(); } finally { br.close(); } }
11
Code Sample 1: public static void gunzip(File gzippedFile, File destinationFile) throws IOException { int buffer = 2048; FileInputStream in = new FileInputStream(gzippedFile); GZIPInputStream zipin = new GZIPInputStream(in); byte[] data = new byte[buffer]; FileOutputStream out = new FileOutputStream(destinationFile); int length; while ((length = zipin.read(data, 0, buffer)) != -1) out.write(data, 0, length); out.close(); zipin.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(); } }
11
Code Sample 1: public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: private int mergeFiles(Merge merge) throws MojoExecutionException { String encoding = DEFAULT_ENCODING; if (merge.getEncoding() != null && merge.getEncoding().length() > 0) { encoding = merge.getEncoding(); } int numMergedFiles = 0; Writer ostream = null; FileOutputStream fos = null; try { fos = new FileOutputStream(merge.getTargetFile(), true); ostream = new OutputStreamWriter(fos, encoding); BufferedWriter output = new BufferedWriter(ostream); for (String orderingName : this.orderingNames) { List<File> files = this.orderedFiles.get(orderingName); if (files != null) { getLog().info("Appending: " + files.size() + " files that matched the name: " + orderingName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); for (File file : files) { String fileName = file.getName(); getLog().info("Appending file: " + fileName + " to the target file: " + merge.getTargetFile().getAbsolutePath() + "..."); InputStream input = null; try { input = new FileInputStream(file); if (merge.getSeparator() != null && merge.getSeparator().trim().length() > 0) { String replaced = merge.getSeparator().trim(); replaced = replaced.replace("\n", ""); replaced = replaced.replace("\t", ""); replaced = replaced.replace("#{file.name}", fileName); replaced = replaced.replace("#{parent.name}", file.getParentFile() != null ? file.getParentFile().getName() : ""); replaced = replaced.replace("\\n", "\n"); replaced = replaced.replace("\\t", "\t"); getLog().debug("Appending separator: " + replaced); IOUtils.copy(new StringReader(replaced), output); } IOUtils.copy(input, output, encoding); } catch (IOException ioe) { throw new MojoExecutionException("Failed to append file: " + fileName + " to output file", ioe); } finally { IOUtils.closeQuietly(input); } numMergedFiles++; } } } output.flush(); } catch (IOException ioe) { throw new MojoExecutionException("Failed to open stream file to output file: " + merge.getTargetFile().getAbsolutePath(), ioe); } finally { if (fos != null) { IOUtils.closeQuietly(fos); } if (ostream != null) { IOUtils.closeQuietly(ostream); } } return numMergedFiles; }
11
Code Sample 1: public void run() { LOG.debug(this); String[] parts = createCmdArray(getCommand()); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(parts); if (isBlocking()) { process.waitFor(); StringWriter out = new StringWriter(); IOUtils.copy(process.getInputStream(), out); String stdout = out.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stdout)) { LOG.info("Process stdout:\n" + stdout); } StringWriter err = new StringWriter(); IOUtils.copy(process.getErrorStream(), err); String stderr = err.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stderr)) { LOG.error("Process stderr:\n" + stderr); } } } catch (IOException ioe) { LOG.error(String.format("Could not exec [%s]", getCommand()), ioe); } catch (InterruptedException ie) { LOG.error(String.format("Interrupted [%s]", getCommand()), ie); } } Code Sample 2: 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!"); }
00
Code Sample 1: public static String SHA1(String password) throws BusinessException { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(password.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); return hash.toString(16); } catch (java.security.NoSuchAlgorithmException e) { throw new BusinessException(); } } Code Sample 2: protected byte[] retrieveImageData() throws IOException { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int fileSize = connection.getContentLength(); Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")"); BufferedInputStream istream = new BufferedInputStream(connection.getInputStream()); try { if (fileSize <= 0) { Log.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of " + defaultBufferSize + " bytes"); ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize); byte[] buffer = new byte[defaultBufferSize]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = istream.read(buffer, 0, defaultBufferSize); if (bytesRead > 0) buf.write(buffer, 0, bytesRead); } return buf.toByteArray(); } else { byte[] imageData = new byte[fileSize]; int bytesRead = 0; int offset = 0; while (bytesRead != -1 && offset < fileSize) { bytesRead = istream.read(imageData, offset, fileSize - offset); offset += bytesRead; } return imageData; } } finally { try { istream.close(); connection.disconnect(); } catch (Exception ignore) { } } }
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: 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()); } }
11
Code Sample 1: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } } Code Sample 2: public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } }
00
Code Sample 1: public static String loadResource(String resource) { URL url = ClassLoader.getSystemResource("resources/" + resource); StringBuffer buffer = new StringBuffer(); if (url == null) { ErrorMessage.handle(new NullPointerException("URL for resources/" + resource + " not found")); } else { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } } return buffer.toString(); } Code Sample 2: @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
00
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } Code Sample 2: public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream stream = url.openStream(); AudioFileFormat format; try { format = getAudioFileFormat(new BufferedInputStream(stream)); } finally { stream.close(); } return format; }
00
Code Sample 1: private Store openConnection(String url) throws MessagingException { URLName urlName = new URLName(url); log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost()); Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(urlName); store.connect(); return store; } Code Sample 2: public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
00
Code Sample 1: public String getHtml(String path) throws Exception { URL url = new URL(path); URLConnection conn = url.openConnection(); conn.setDoOutput(true); InputStream inputStream = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8"); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(isr); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } String result = sb.toString(); return result; } Code Sample 2: public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } }
11
Code Sample 1: public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { log.error("Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { log.error("Error trying to generate unique Id" + e.getMessage()); } return digest; }
11
Code Sample 1: String digest(final UserAccountEntity account) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(account.getUserId().getBytes("UTF-8")); digest.update(account.getLastLogin().toString().getBytes("UTF-8")); digest.update(account.getPerson().getGivenName().getBytes("UTF-8")); digest.update(account.getPerson().getSurname().getBytes("UTF-8")); digest.update(account.getPerson().getEmail().getBytes("UTF-8")); digest.update(m_random); return new String(Base64.altEncode(digest.digest())); } catch (final Exception e) { LOG.error("Exception", e); throw new RuntimeException(e); } } Code Sample 2: private String digest(String message) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(message.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String hpassword = hash.toString(16); return hpassword; } catch (Exception e) { } return null; }
00
Code Sample 1: void sort(int a[]) throws Exception { for (int i = a.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (stopRequested) { return; } if (a[j] > a[j + 1]) { int T = a[j]; a[j] = a[j + 1]; a[j + 1] = T; flipped = true; } pause(i, j); } if (!flipped) { return; } } } Code Sample 2: private boolean loadSymbol(QuoteCache quoteCache, Symbol symbol, TradingDate startDate, TradingDate endDate) { boolean success = true; String URLString = constructURL(symbol, startDate, endDate); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url; url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; while ((line = bufferedInput.readLine()) != null) { Class cl = null; Constructor cnst = null; QuoteFilter filter = null; try { cl = Class.forName("org.mov.quote." + name + "QuoteFilter"); try { cnst = cl.getConstructor(new Class[] { Symbol.class }); } catch (SecurityException e2) { e2.printStackTrace(); } catch (NoSuchMethodException e2) { e2.printStackTrace(); } try { filter = (QuoteFilter) cnst.newInstance(new Object[] { symbol }); } catch (IllegalArgumentException e3) { e3.printStackTrace(); } catch (InstantiationException e3) { e3.printStackTrace(); } catch (IllegalAccessException e3) { e3.printStackTrace(); } catch (InvocationTargetException e3) { e3.printStackTrace(); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } Quote quote = filter.toQuote(line); if (quote != null) quoteCache.load(quote); } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); success = false; } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); success = false; } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); success = false; } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); success = false; } catch (FileNotFoundException e) { } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); success = false; } return success; }
11
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: public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
11
Code Sample 1: protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); 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 GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public String saveFile(URL url) { String newUrlToReturn = url.toString(); try { String directory = Util.appendDirPath(targetDirectory, OBJ_REPOSITORY); String category = url.openConnection().getContentType(); category = category.substring(0, category.indexOf("/")); String fileUrl = Util.transformUrlToPath(url.toString()); directory = Util.appendDirPath(directory, category); directory = Util.appendDirPath(directory, fileUrl); String objectFileName = url.toString().substring(url.toString().lastIndexOf('/') + 1); BufferedInputStream in = new java.io.BufferedInputStream(url.openStream()); File dir = new File(directory); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Util.appendDirPath(dir.getPath(), objectFileName)); FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { bout.write(data, 0, count); } bout.close(); fos.close(); in.close(); newUrlToReturn = Util.getRelativePath(file.getAbsolutePath(), targetDirectory); } catch (IOException e) { return newUrlToReturn; } return newUrlToReturn; } Code Sample 2: @Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
00
Code Sample 1: public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
11
Code Sample 1: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); } Code Sample 2: protected void doProxyInternally(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpRequestBase proxyReq = buildProxyRequest(req); URI reqUri = proxyReq.getURI(); String cookieDomain = reqUri.getHost(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute("org.atricorel.idbus.kernel.main.binding.http.HttpServletRequest", req); int intIdx = 0; for (int i = 0; i < httpClient.getRequestInterceptorCount(); i++) { if (httpClient.getRequestInterceptor(i) instanceof RequestAddCookies) { intIdx = i; break; } } IDBusRequestAddCookies interceptor = new IDBusRequestAddCookies(cookieDomain); httpClient.removeRequestInterceptorByClass(RequestAddCookies.class); httpClient.addRequestInterceptor(interceptor, intIdx); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (logger.isTraceEnabled()) logger.trace("Staring to follow redirects for " + req.getPathInfo()); HttpResponse proxyRes = null; List<Header> storedHeaders = new ArrayList<Header>(40); boolean followTargetUrl = true; byte[] buff = new byte[1024]; while (followTargetUrl) { if (logger.isTraceEnabled()) logger.trace("Sending internal request " + proxyReq); proxyRes = httpClient.execute(proxyReq, httpContext); String targetUrl = null; Header[] headers = proxyRes.getAllHeaders(); for (Header header : headers) { if (header.getName().equals("Server")) continue; if (header.getName().equals("Transfer-Encoding")) continue; if (header.getName().equals("Location")) continue; if (header.getName().equals("Expires")) continue; if (header.getName().equals("Content-Length")) continue; if (header.getName().equals("Content-Type")) continue; storedHeaders.add(header); } if (logger.isTraceEnabled()) logger.trace("HTTP/STATUS:" + proxyRes.getStatusLine().getStatusCode() + "[" + proxyReq + "]"); switch(proxyRes.getStatusLine().getStatusCode()) { case 200: followTargetUrl = false; break; case 404: followTargetUrl = false; break; case 500: followTargetUrl = false; break; case 302: Header location = proxyRes.getFirstHeader("Location"); targetUrl = location.getValue(); if (!internalProcessingPolicy.match(req, targetUrl)) { if (logger.isTraceEnabled()) logger.trace("Do not follow HTTP 302 to [" + location.getValue() + "]"); Collections.addAll(storedHeaders, proxyRes.getHeaders("Location")); followTargetUrl = false; } else { if (logger.isTraceEnabled()) logger.trace("Do follow HTTP 302 to [" + location.getValue() + "]"); followTargetUrl = true; } break; default: followTargetUrl = false; break; } HttpEntity entity = proxyRes.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (!followTargetUrl) { for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } IOUtils.copy(instream, res.getOutputStream()); res.getOutputStream().flush(); } else { int r = instream.read(buff); int total = r; while (r > 0) { r = instream.read(buff); total += r; } if (total > 0) logger.warn("Ignoring response content size : " + total); } } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { proxyReq.abort(); throw ex; } finally { try { instream.close(); } catch (Exception ignore) { } } } else { if (!followTargetUrl) { res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } } } if (followTargetUrl) { proxyReq = buildProxyRequest(targetUrl); httpContext = null; } } if (logger.isTraceEnabled()) logger.trace("Ended following redirects for " + req.getPathInfo()); }
11
Code Sample 1: public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; } Code Sample 2: @Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
11
Code Sample 1: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnClear) { passwordField.setText(""); } for (int i = 0; i < 10; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; sql = "select password from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'" + " and key=" + key + " "; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } setVisible(false); setTries(0); Error.log(4003, "Senha de uso �nico verificada positivamente."); Error.log(4002, "Autentica��o etapa 3 encerrada."); ManagerWindow mw = new ManagerWindow(login); mw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); int tries = getTries(); if (tries == 0) { Error.log(4004, "Primeiro erro da senha de uso �nico contabilizado."); } else if (tries == 1) { Error.log(4005, "Segundo erro da senha de uso �nico contabilizado."); } else if (tries == 2) { Error.log(4006, "Terceiro erro da senha de uso �nico contabilizado."); Error.log(4007, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 3."); Error.log(4002, "Autentica��o etapa 3 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } } Code Sample 2: private String generaHashMD5(String plainText) throws Exception { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes(FirmaUtil.CHARSET)); byte[] digest = mdAlgorithm.digest(); return toHex(digest); }
00
Code Sample 1: protected BufferedImage handleNLIBException() { if (params.uri.startsWith("http://digar.nlib.ee/otsing/") || params.uri.startsWith("http://digar.nlib.ee/show")) try { String url = "http://digar.nlib.ee/gmap/nd" + params.uri.substring(params.uri.indexOf(":") + 1, params.uri.lastIndexOf("&")) + "-tiles/z0x0y0.jpeg"; URLConnection connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e) { try { if (params.uri.startsWith("http://digar.nlib.ee/show")) params.uri = "http://digar.nlib.ee/otsing/?pid=" + params.uri.substring(params.uri.lastIndexOf("/") + 1) + "&show"; URLConnection connection = new URL(params.uri).openConnection(); String url = params.uri; if (url.endsWith("&show")) url = url.substring(0, url.length() - 5); int index = url.lastIndexOf("?"); url = "stream" + url.substring(index); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String aux = null; while ((aux = reader.readLine()) != null) { index = aux.indexOf(url); if (index != -1) { url = "http://digar.nlib.ee/otsing/" + aux.substring(index); index = url.indexOf('>'); if (index == -1) index = url.indexOf("\""); url = url.substring(0, index); break; } } connection = new URL(url).openConnection(); return processNewUri(connection); } catch (Exception e2) { } } return null; } Code Sample 2: private long getRecordedSessionLength() { long lRet = -1; String strLength = this.applet.getParameter(Constants.PLAYBACK_MEETING_LENGTH_PARAM); if (null != strLength) { lRet = (new Long(strLength)).longValue(); } else { Properties recProps = new Properties(); try { URL urlProps = new URL(applet.getDocumentBase(), Constants.RECORDED_SESSION_INFO_PROPERTIES); recProps.load(urlProps.openStream()); lRet = (new Long(recProps.getProperty(Constants.PLAYBACK_MEETING_LENGTH_PARAM))).longValue(); } catch (Exception e) { e.printStackTrace(); } } return lRet; }
11
Code Sample 1: public String process(URL url) throws IOException { String line, results = ""; InputStream is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); while ((line = dis.readLine()) != null) { results += line + "\n"; } System.out.println(results); return results; } Code Sample 2: private static String sendGetRequest(String endpoint, String requestParameters) throws Exception { String result = null; if (endpoint.startsWith("http://")) { StringBuffer data = new StringBuffer(); String urlStr = prepareUrl(endpoint, requestParameters); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } return result; }
11
Code Sample 1: public static void initStaticStuff() { Enumeration<URL> urls = null; try { urls = Play.class.getClassLoader().getResources("play.static"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { try { Class.forName(line); } catch (Exception e) { System.out.println("! Cannot init static : " + line); } } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } } Code Sample 2: protected BufferedReader getDataReader() { BufferedReader in = null; PrintWriter out = null; try { String line; URL url = new URL(this.catalog.getCatalogURL()); Debug.output("Catalog URL:" + url.toString()); in = new BufferedReader(new InputStreamReader(url.openStream())); File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir"); File temp = new File(dir, TEMP); Debug.output("Temp file:" + temp.toString()); out = new PrintWriter(new BufferedWriter(new FileWriter(temp))); while ((line = in.readLine()) != null) { out.println(line); } Debug.output("Temp file size:" + temp.length()); return new BufferedReader(new FileReader(temp)); } catch (IOException e) { throw new SeismoException(e); } finally { Util.close(in); Util.close(out); } }
00
Code Sample 1: public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); } Code Sample 2: public static boolean copyFile(String sourceFileName, String destFileName) { FileChannel ic = null; FileChannel oc = null; try { ic = new FileInputStream(sourceFileName).getChannel(); oc = new FileOutputStream(destFileName).getChannel(); ic.transferTo(0, ic.size(), oc); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { ic.close(); } catch (IOException e) { e.printStackTrace(); } try { oc.close(); } catch (IOException e) { e.printStackTrace(); } } return false; }
11
Code Sample 1: public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } } Code Sample 2: 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!"); }
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: public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
11
Code Sample 1: public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (jmsTemplate == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj); return eventDoc.getEvent().getEventId(); } Code Sample 2: public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } }
11
Code Sample 1: public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
11
Code Sample 1: public static void exportGestureSet(List<GestureSet> sets, File file) { try { FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(exportGestureSetsAsStream(sets), outputStream); outputStream.close(); } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets. Export File not found.", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e); } } Code Sample 2: public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; } Code Sample 2: private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } }
00
Code Sample 1: public static String crypt(String senha) { String md5 = null; MessageDigest md; try { md = MessageDigest.getInstance(CRYPT_ALGORITHM); md.update(senha.getBytes()); Hex hex = new Hex(); md5 = new String(hex.encode(md.digest())); } catch (NoSuchAlgorithmException e) { logger.error(ResourceUtil.getLOGMessage("_nls.mensagem.geral.log.crypt.no.such.algorithm", CRYPT_ALGORITHM)); } return md5; } Code Sample 2: public void sendRequest(String method) { try { url = new URL(urlStr); httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod(method); httpURLConnection.setDoOutput(true); httpURLConnection.getOutputStream().flush(); httpURLConnection.getOutputStream().close(); System.out.println(httpURLConnection.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
00
Code Sample 1: public void generateListOfSubscriptions() { try { java.net.URL url = new java.net.URL(NewGenLibDesktopRoot.getInstance().getURLRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); System.out.println(NewGenLibDesktopRoot.getRoot() + "/NEWGEN_JR/ListOfSubscriptions.xml"); net.sf.jasperreports.engine.design.JasperDesign jd = net.sf.jasperreports.engine.xml.JRXmlLoader.load(url.openStream()); System.out.println("in generate Report 30" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperReport jr = net.sf.jasperreports.engine.JasperCompileManager.compileReport(jd); System.out.println("in generate Report 32" + dtm.getRowCount()); java.util.Map param = new java.util.HashMap(); param.put("ReportTitle", "List of subscriptions"); Class.forName("org.postgresql.Driver"); System.out.println("in generate Report 37" + dtm.getRowCount()); net.sf.jasperreports.engine.JasperPrint jp = net.sf.jasperreports.engine.JasperFillManager.fillReport(jr, param, new net.sf.jasperreports.engine.data.JRTableModelDataSource(dtm)); System.out.println("in generate Report 39" + dtm.getRowCount()); java.sql.Timestamp currentTime = new java.sql.Timestamp(java.util.Calendar.getInstance().getTimeInMillis()); if (jp.getPages().size() != 0) net.sf.jasperreports.view.JasperViewer.viewReport(jp, false); else javax.swing.JOptionPane.showMessageDialog(reports.DeskTopFrame.getInstance(), "There are no records in the selected report option."); System.out.println("in generate Report 43" + dtm.getRowCount()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; }
11
Code Sample 1: boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; } Code Sample 2: @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
11
Code Sample 1: public void execute(File sourceFile, File destinationFile, Properties htmlCleanerConfig) { FileReader reader = null; Writer writer = null; try { reader = new FileReader(sourceFile); logger.info("Using source file: " + trimPath(userDir, sourceFile)); if (!destinationFile.getParentFile().exists()) { createDirectory(destinationFile.getParentFile()); } writer = new FileWriter(destinationFile); logger.info("Destination file: " + trimPath(userDir, destinationFile)); execute(reader, writer, htmlCleanerConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
11
Code Sample 1: private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); } Code Sample 2: public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); 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())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
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: @Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
00
Code Sample 1: 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; } Code Sample 2: public void setUp() throws Exception { logger.finer("******************** set up ********************"); Properties props; if (XMLDBTestSuite.propertiesFileName == null) { String defaultPropsFileLocation = "test/xmldb/XMLDBTestSuite.properties"; URL url = this.getClass().getClassLoader().getResource(defaultPropsFileLocation); if (url == null) { throw new Exception("failed to find default props file at " + defaultPropsFileLocation); } props = loadProps(url.openConnection().getInputStream()); } else { props = loadProps(XMLDBTestSuite.propertiesFileName); } String driver = props.getProperty("driverName"); String collectionURI = props.getProperty("URI"); Database database = (Database) Class.forName(driver).newInstance(); collectionStorageHelper = new CollectionStorageHelper(collectionURI); rootCollectionName = collectionStorageHelper.getCollectionName(); Collection root = database.getCollection(collectionURI, null, null); CollectionManagementService service = (CollectionManagementService) root.getService(CollectionManagementService.SERVICE_NAME, "1.0"); String childCollection = "child"; removeChildCollection(root, childCollection, service); col = service.createCollection(childCollection); assertNotNull("XMLDBTestCase.setUp() - Collection could not be created", col); logger.info("created child collection '" + col.getName() + "' parent is '" + col.getParentCollection().getName() + "'"); assertEquals("Root collection name should match childs parent name", rootCollectionName, col.getParentCollection().getName()); document = createXMLFile(xmlFileName); assertNotNull("XMLDBTestCase.setUp() - failed to create XML file", document); }
00
Code Sample 1: private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } } Code Sample 2: public static HttpURLConnection create(URL url, String id, String action, HTTPRequestInfo info) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); if (id != null) { connection.setRequestProperty("id", id); } connection.setRequestProperty("action", action); connection.setUseCaches(false); if (info.getProxyUser() != null && info.getProxyPassword() != null) { String pwd = info.getProxyUser() + ":" + info.getProxyPassword(); String encoded = new String(Base64.encodeBase64(pwd.getBytes())); connection.setRequestProperty("Proxy-Authorization", "Basic " + encoded); } return connection; }
11
Code Sample 1: @Override public void render(IContentNode contentNode, Request req, Response resp, Application app, ServerInfo serverInfo) { Node fileNode = contentNode.getNode(); try { Node res = fileNode.getNode("jcr:content"); if (checkLastModified(res, req.getServletRequset(), resp.getServletResponse())) { return; } Property data = res.getProperty("jcr:data"); InputStream is = data.getBinary().getStream(); int contentLength = (int) data.getBinary().getSize(); String mime; if (res.hasProperty("jcr:mimeType")) { mime = res.getProperty("jcr:mimeType").getString(); } else { mime = serverInfo.getSerlvetContext().getMimeType(fileNode.getName()); } if (mime != null && mime.startsWith("image")) { int w = req.getInt("w", 0); int h = req.getInt("h", 0); String fmt = req.get("fmt"); if (w != 0 || h != 0 || fmt != null) { Resource imgRes = ImageResource.create(is, mime.substring(6), w, h, req.getInt("cut", 0), fmt); imgRes.process(serverInfo); return; } } resp.getServletResponse().setContentType(mime); resp.getServletResponse().setContentLength(contentLength); OutputStream os = resp.getServletResponse().getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; } Code Sample 2: private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; }
00
Code Sample 1: public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } } Code Sample 2: private void getRdfResponse(StringBuilder sb, String url) { try { String inputLine = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((inputLine = reader.readLine()) != null) { sb.append(inputLine); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
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: void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
00
Code Sample 1: 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; } Code Sample 2: private InputStream getConnection() throws BaseException { OutputStreamWriter wr = null; try { StringBuilder sb = new StringBuilder(); sb.append(getBaseString()); sb.append(AND); sb.append(encode(ACTION, ENCODING)); sb.append(EQUAL); sb.append(encode(ACTION_GET_ALL, ENCODING)); URL url = new URL(SERVER_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sb.toString()); wr.flush(); return conn.getInputStream(); } catch (Exception e) { throw getException(e, context); } finally { closeSafely(wr); } }
00
Code Sample 1: public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public String getChallengers() { InputStream is = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return "none"; } else return result; } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return "none"; }
00
Code Sample 1: public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; } Code Sample 2: void startzm() { URL myzzurl; InputStream myzstream; byte zmemimage[]; boolean joined; zmemimage = null; try { System.err.println(zcodefile); myzzurl = new URL(zcodefile); myzstream = myzzurl.openStream(); zmemimage = suckstream(myzstream); } catch (MalformedURLException booga) { try { myzstream = new FileInputStream(zcodefile); zmemimage = suckstream(myzstream); } catch (IOException booga2) { add("North", new Label("Malformed URL")); failed = true; } } catch (IOException booga) { add("North", new Label("I/O Error")); } if (zmemimage != null) { switch(zmemimage[0]) { case 3: zm = new ZMachine3(screen, status_line, zmemimage); break; case 5: remove(status_line); zm = new ZMachine5(screen, zmemimage); break; case 8: remove(status_line); zm = new ZMachine8(screen, zmemimage); break; default: add("North", new Label("Not a valid V3,V5, or V8 story file")); } if (zm != null) zm.start(); } joined = false; if (zmemimage != null) { while (!joined) { try { zm.join(); joined = true; } catch (InterruptedException booga) { } } } System.exit(0); }
00
Code Sample 1: public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; } Code Sample 2: public Document createDocument(String uri) throws IOException { ParsedURL purl = new ParsedURL(uri); InputStream is = purl.openStream(MimeTypeConstants.MIME_TYPES_SVG); InputSource isrc = new InputSource(is); String contentType = purl.getContentType(); int cindex = -1; if (contentType != null) { contentType = contentType.toLowerCase(); cindex = contentType.indexOf(HTTP_CHARSET); } if (cindex != -1) { int i = cindex + HTTP_CHARSET.length(); int eqIdx = contentType.indexOf('=', i); if (eqIdx != -1) { eqIdx++; String charset; int idx = contentType.indexOf(',', eqIdx); int semiIdx = contentType.indexOf(';', eqIdx); if ((semiIdx != -1) && ((semiIdx < idx) || (idx == -1))) idx = semiIdx; if (idx != -1) charset = contentType.substring(eqIdx, idx); else charset = contentType.substring(eqIdx); isrc.setEncoding(charset.trim()); } } isrc.setSystemId(uri); Document doc = super.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, isrc); try { ((SVGOMDocument) doc).setURLObject(new URL(purl.toString())); } catch (MalformedURLException mue) { throw new IOException("Malformed URL: " + uri); } return doc; }
11
Code Sample 1: public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; } Code Sample 2: public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; int sec = 0; try { URL url = rep.getResource(request, resource); if (url == null) { return "Documento " + rep.dir + "/" + resource + " no encontrado"; } br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding)); String line = br.readLine(); while (line != null) { int pos = line.indexOf("KAttach("); if (pos > -1) { sb.append(attach(request, ++sec, line, pos, template)); } else { line = line.replaceAll("%20", "-"); sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n"); } line = br.readLine(); } } finally { if (br != null) br.close(); } return sb.toString(); }
11
Code Sample 1: private void upgradeSchema() throws IOException { Statement stmt = null; try { int i = getSchema(); if (i < SCHEMA_VERSION) { conn.setAutoCommit(false); stmt = conn.createStatement(); while (i < SCHEMA_VERSION) { String qry; switch(i) { case 1: qry = "CREATE TABLE log (id INTEGER PRIMARY KEY, context VARCHAR(16) NOT NULL, level VARCHAR(16) NOT NULL, time LONG INT NOT NULL, msg LONG VARCHAR NOT NULL, parent INT)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '2' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 2: qry = "CREATE TABLE monitor (id INTEGER PRIMARY KEY NOT NULL, status INTEGER NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '3' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 3: qry = "CREATE TABLE favs (id INTEGER PRIMARY KEY NOT NULL)"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '4' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 4: qry = "DROP TABLE log"; stmt.executeUpdate(qry); qry = "UPDATE settings SET val = '5' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; case 5: qry = "UPDATE settings SET val = '120000' WHERE var = 'SleepTime'"; stmt.executeUpdate(qry); qry = "UPDATE settings set val = '6' WHERE var = 'schema'"; stmt.executeUpdate(qry); break; } i++; } conn.commit(); } } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { LOG.trace(SQL_ERROR, e2); LOG.error(e2); } LOG.trace(SQL_ERROR, e); LOG.fatal(e); throw new IOException("Error upgrading data store", e); } finally { try { if (stmt != null) { stmt.close(); } conn.setAutoCommit(true); } catch (SQLException e) { LOG.trace(SQL_ERROR, e); throw new IOException("Unable to cleanup SQL resources", e); } } } Code Sample 2: @Override public void saveStructure(long userId, TreeStructureInfo info, List<TreeStructureNode> structure) throws DatabaseException { if (info == null) throw new NullPointerException("info"); if (structure == null) throw new NullPointerException("structure"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement insertInfoSt = null, insSt = null; try { insertInfoSt = getConnection().prepareStatement(INSERT_INFO); insertInfoSt.setLong(1, userId); insertInfoSt.setString(2, info.getDescription() != null ? info.getDescription() : ""); insertInfoSt.setString(3, info.getBarcode()); insertInfoSt.setString(4, info.getName()); insertInfoSt.setString(5, info.getInputPath()); insertInfoSt.setString(6, info.getModel()); insertInfoSt.executeUpdate(); PreparedStatement seqSt = getConnection().prepareStatement(INFO_VALUE); ResultSet rs = seqSt.executeQuery(); int key = -1; while (rs.next()) { key = rs.getInt(1); } if (key == -1) { getConnection().rollback(); throw new DatabaseException("Unable to obtain new id from DB when executing query: " + insertInfoSt); } int total = 0; for (TreeStructureNode node : structure) { insSt = getConnection().prepareStatement(INSERT_NODE); insSt.setLong(1, key); insSt.setString(2, node.getPropId()); insSt.setString(3, node.getPropParent()); insSt.setString(4, node.getPropName()); insSt.setString(5, node.getPropPicture()); insSt.setString(6, node.getPropType()); insSt.setString(7, node.getPropTypeId()); insSt.setString(8, node.getPropPageType()); insSt.setString(9, node.getPropDateIssued()); insSt.setString(10, node.getPropAltoPath()); insSt.setString(11, node.getPropOcrPath()); insSt.setBoolean(12, node.getPropExist()); total += insSt.executeUpdate(); } if (total != structure.size()) { getConnection().rollback(); throw new DatabaseException("Unable to insert _ALL_ nodes: " + total + " nodes were inserted of " + structure.size()); } getConnection().commit(); } catch (SQLException e) { LOGGER.error("Queries: \"" + insertInfoSt + "\" and \"" + insSt + "\"", e); } finally { closeConnection(); } }