label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: protected void zipFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(to)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); }
11
Code Sample 1: private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } } Code Sample 2: public String insertBuilding() { homeMap = homeMapDao.getHomeMapById(homeMap.getId()); homeBuilding.setHomeMap(homeMap); Integer id = homeBuildingDao.saveHomeBuilding(homeBuilding); String dir = "E:\\ganymede_workspace\\training01\\web\\user_buildings\\"; FileOutputStream fos; try { fos = new FileOutputStream(dir + id); IOUtils.copy(new FileInputStream(imageFile), fos); IOUtils.closeQuietly(fos); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return execute(); }
11
Code Sample 1: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; } Code Sample 2: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); } Code Sample 2: public String postFileRequest(String fileName, String internalFileName) throws Exception { status = STATUS_INIT; String responseString = null; String requestStringPostFix = new String(""); if (isThreadStopped) { return ""; } status = STATUS_UPLOADING; if (isThreadStopped) { return ""; } String requestString = new String(""); int contentLength = 0, c = 0, counter = 0; try { for (java.util.Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) { java.util.Map.Entry e = (java.util.Map.Entry) i.next(); requestString = requestString + "-----------------------------7d338a374003ea\n" + "Content-Disposition: form-data; name=\"" + (String) e.getKey() + "\"\n\n" + (String) e.getValue() + "\n\n"; } URL url = new URL(urlString); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; requestString = requestString + "-----------------------------7d338a374003ea\n" + "Content-Disposition: form-data; name=\"" + internalFileName + "\"; filename=\"" + fileName + "\"\n" + "Content-Type: text/plain\n\n"; requestStringPostFix = requestStringPostFix + "\n\n" + "-----------------------------7d338a374003ea\n" + "\n"; FileInputStream fis = null; String str = null; try { fis = new FileInputStream(fileName); int fileSize = fis.available(); contentLength = requestString.length() + requestStringPostFix.length() + fileSize; httpConn.setRequestProperty("Content-Length", String.valueOf(contentLength)); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------7d338a374003ea"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); try { connection.connect(); } catch (ConnectException ec2) { error = true; finished = true; errorStr = "Cannot connect to: " + urlString; System.out.println("Cannot connect to:" + urlString); } catch (java.io.InterruptedIOException e) { error = true; finished = true; errorStr = "Connection to Portal lost: communication is timeouted."; parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh(); } catch (IllegalStateException ei) { error = true; finished = true; errorStr = "IllegalStateException: " + ei.getMessage(); } OutputStream out = httpConn.getOutputStream(); byte[] toTransfer = requestString.getBytes("UTF-8"); for (int i = 0; i < toTransfer.length; i++) { out.write(toTransfer[i]); } int count; int zBUFFER = 8 * 1024; setUploadProgress(fileSize, counter); byte data[] = new byte[zBUFFER]; GZIPOutputStream zos = new GZIPOutputStream(out); while ((count = fis.read(data, 0, zBUFFER)) != -1) { if (isThreadStopped) { return ""; } zos.write(data, 0, count); setUploadProgress(fileSize, counter); counter += count; } zos.flush(); zos.finish(); setUploadProgress(fileSize, counter); toTransfer = requestStringPostFix.getBytes("UTF-8"); for (int i = 0; i < toTransfer.length; i++) { out.write(toTransfer[i]); } out.close(); } catch (IOException e) { finished = true; error = true; errorStr = "Error in Uploading file: " + fileName; } finally { try { fis.close(); } catch (IOException e2) { } } InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader br = new BufferedReader(isr); String temp; String tempResponse = ""; while ((temp = br.readLine()) != null) { if (isThreadStopped) { return ""; } tempResponse = tempResponse + temp + "\n"; setDecompressStatusAtUpload(temp); } responseString = tempResponse; isr.close(); } catch (ConnectException ec) { error = true; finished = true; errorStr = "Cannot connect to: " + urlString + "\nServer is not responding."; } catch (java.io.InterruptedIOException e) { error = true; finished = true; errorStr = "Connection to Portal lost: communication is timeouted."; parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh(); } catch (IOException e2) { finished = true; error = true; errorStr = "IOError in postFileRequest: " + e2.getMessage(); } catch (Exception e4) { finished = true; error = true; errorStr = "Error while trying to communicate the server: " + e4.getMessage(); } return responseString; }
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: private void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
11
Code Sample 1: public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
00
Code Sample 1: public boolean delwuliao(String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("delete from addwuliao where pid=?"); pm.setString(1, pid); int x = pm.executeUpdate(); if (x == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: private static String makeMD5(String str) { byte[] bytes = new byte[32]; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("iso-8859-1"), 0, str.length()); bytes = md.digest(); } catch (Exception e) { return null; } return convertToHex(bytes); }
11
Code Sample 1: @Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } } Code Sample 2: public void save(String oid, String key, Serializable obj) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _data_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to save object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); } Code Sample 2: public static byte[] post(String path, Map<String, String> params, String encode) throws Exception { StringBuilder parambuilder = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { parambuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } parambuilder.deleteCharAt(parambuilder.length() - 1); } byte[] data = parambuilder.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Connection", "Keep-Alive"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { return StreamTool.readInputStream(conn.getInputStream()); } return null; }
11
Code Sample 1: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } 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!"); }
11
Code Sample 1: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new OutputStream() { @Override public void write(byte[] b, int off, int len) { } @Override public void write(int b) { } @Override public void write(byte[] b) throws IOException { } }); } finally { IOUtils.closeQuietly(in); } return checksum; } Code Sample 2: public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
00
Code Sample 1: static InputStream getFileAsStream(Class clazz, HandlerChain chain) { URL url = clazz.getResource(chain.file()); if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(chain.file()); } if (url == null) { String tmp = clazz.getPackage().getName(); tmp = tmp.replace('.', '/'); tmp += "/" + chain.file(); url = Thread.currentThread().getContextClassLoader().getResource(tmp); } if (url == null) { throw new UtilException("util.failed.to.find.handlerchain.file", clazz.getName(), chain.file()); } try { return url.openStream(); } catch (IOException e) { throw new UtilException("util.failed.to.parse.handlerchain.file", clazz.getName(), chain.file()); } } Code Sample 2: @Override public HttpResponse execute() throws IOException { if (this.method == HttpMethod.GET) { String url = this.toString(); if (url.length() > this.cutoff) { if (log.isLoggable(Level.FINER)) log.finer("URL length " + url.length() + " too long, converting GET to POST: " + url); String rebase = this.baseURL + "?method=GET"; return this.execute(HttpMethod.POST, rebase); } } return super.execute(); }
11
Code Sample 1: private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } Code Sample 2: public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
11
Code Sample 1: void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); }
00
Code Sample 1: public void read(Model m, String url) throws JenaException { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url); } catch (FileNotFoundException e) { throw new DoesNotExistException(url); } catch (IOException e) { throw new JenaException(e); } } Code Sample 2: private void getLocationAddressByGoogleMapAsync(Location location) { if (location == null) { return; } AsyncTask<Location, Void, String> task = new AsyncTask<Location, Void, String>() { @Override protected String doInBackground(Location... params) { if (params == null || params.length == 0 || params[0] == null) { return null; } Location location = params[0]; String address = ""; String cachedAddress = DataService.GetInstance(mContext).getAddressFormLocationCache(location.getLatitude(), location.getLongitude()); if (!TextUtils.isEmpty(cachedAddress)) { address = cachedAddress; } else { StringBuilder jsonText = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = String.format(GoogleMapAPITemplate, location.getLatitude(), location.getLongitude()); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { jsonText.append(line); } JSONObject result = new JSONObject(jsonText.toString()); String status = result.getString(GoogleMapStatusSchema.status); if (GoogleMapStatusCodes.OK.equals(status)) { JSONArray addresses = result.getJSONArray(GoogleMapStatusSchema.results); if (addresses.length() > 0) { address = addresses.getJSONObject(0).getString(GoogleMapStatusSchema.formatted_address); if (!TextUtils.isEmpty(currentBestLocationAddress)) { DataService.GetInstance(mContext).updateAddressToLocationCache(location.getLatitude(), location.getLongitude(), currentBestLocationAddress); } } } } else { Log.e("Error", "Failed to get address via google map API."); } } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } } return address; } @Override protected void onPostExecute(String result) { setCurrentBestLocationAddress(currentBestLocation, result); } }; task.execute(currentBestLocation); }
00
Code Sample 1: public void init() { this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); try { if (memeId < 0) { } else { conurl = new URL(ServerURL + "?meme_id=" + memeId); java.io.InputStream xmlstr = conurl.openStream(); this.removeAllWorkSheets(); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT); this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE); this.setDupeStringMode(WorkBookHandle.SHAREDUPES); ExtenXLS.parseNBind(this, xmlstr); this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS); } } catch (Exception ex) { throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR); } } Code Sample 2: public boolean send(String number, String message) throws IOException { init(); message = message.substring(0, Math.min(MAX_PAYLOAD, message.length())); message = message.replace('\r', ' '); message = message.replace('\n', ' '); ActualFormParameters params = new ActualFormParameters(); String strippedNumber = strip(number); ActualFormParameter number1Param; ActualFormParameter number2Param; if (strippedNumber.startsWith("00")) strippedNumber = "+" + strippedNumber.substring(2); else if (strippedNumber.startsWith("0")) strippedNumber = "+49" + strippedNumber.substring(1); number1Param = new ActualFormParameter(number1InputElement.getName(), strippedNumber.substring(0, 6)); number2Param = new ActualFormParameter(number2InputElement.getName(), strippedNumber.substring(6)); params.add(number1Param); params.add(number2Param); ActualFormParameter messageParam = new ActualFormParameter(messageInputElement.getName(), message); params.add(messageParam); ActualFormParameter letterCountParam = new ActualFormParameter(letterCountInputElement.getName(), "" + (MAX_PAYLOAD - message.length())); params.add(letterCountParam); form.addDefaultParametersTo(params); Reader r = form.submitForm(params, form.getNetscapeRequestProperties()); String result = getStringFromReader(r); String pattern = "<meta http-equiv = \"refresh\" content=\"1; url="; int patternIndex = result.indexOf(pattern); if (patternIndex < 0) return false; int end = result.lastIndexOf("\">"); if (end < 0) return false; String url = result.substring(patternIndex + pattern.length(), end); result = getStringFromReader(new InputStreamReader(new URL(url).openStream())); return result.indexOf("wurde erfolgreich verschickt") >= 0; }
11
Code Sample 1: public static File[] splitFile(FileValidator validator, File source, long target_length, File todir, String prefix) { if (target_length == 0) return null; if (todir == null) { todir = new File(System.getProperty("java.io.tmpdir")); } if (prefix == null || prefix.equals("")) { prefix = source.getName(); } Vector result = new Vector(); FileOutputStream fos = null; FileInputStream fis = null; try { fis = new FileInputStream(source); byte[] bytes = new byte[CACHE_SIZE]; long current_target_size = 0; int current_target_nb = 1; int nbread = -1; try { File f = new File(todir, prefix + i18n.getString("targetname_suffix") + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); while ((nbread = fis.read(bytes)) > -1) { if ((current_target_size + nbread) > target_length) { int limit = (int) (target_length - current_target_size); fos.write(bytes, 0, limit); fos.close(); current_target_nb++; current_target_size = 0; f = new File(todir, prefix + "_" + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); fos.write(bytes, limit, nbread - limit); current_target_size += nbread - limit; } else { fos.write(bytes, 0, nbread); current_target_size += nbread; } } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (fis != null) fis.close(); } catch (IOException e) { } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } File[] fresult = null; if (result.size() > 0) { fresult = new File[result.size()]; fresult = (File[]) result.toArray(fresult); } return fresult; } Code Sample 2: private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
00
Code Sample 1: private Bitmap fetchImage(String urlstr) throws Exception { URL url; url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.setRequestProperty("User-Agent", "Agent"); c.connect(); InputStream is = c.getInputStream(); Bitmap img; img = BitmapFactory.decodeStream(is); return img; } Code Sample 2: public static int UsePassword(String username, String password, String new_password) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=ChangePassword&username=" + username + "&password=" + password + "&new_password=" + new_password); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return -1; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return -1; } return 0; } catch (Exception e) { e.printStackTrace(); } return -1; }
00
Code Sample 1: public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } Code Sample 2: public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
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 dumpDB(String in, String out) { try { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { Log.d("exception", e.toString()); } }
11
Code Sample 1: public static void BubbleSortFloat2(float[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { float temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); } Code Sample 2: private static String sort(final String item) { final char[] chars = item.toCharArray(); for (int i = 1; i < chars.length; i++) { for (int j = 0; j < chars.length - 1; j++) { if (chars[j] > chars[j + 1]) { final char temp = chars[j]; chars[j] = chars[j + 1]; chars[j + 1] = temp; } } } return String.valueOf(chars); }
11
Code Sample 1: public boolean isServerAlive(String pStrURL) { boolean isAlive; long t1 = System.currentTimeMillis(); try { URL url = new URL(pStrURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { logger.fine(inputLine); } logger.info("** Connection successful.. **"); in.close(); isAlive = true; } catch (Exception e) { logger.info("** Connection failed.. **"); e.printStackTrace(); isAlive = false; } long t2 = System.currentTimeMillis(); logger.info("Time taken to check connection: " + (t2 - t1) + " ms."); return isAlive; } Code Sample 2: public static Set<Municipality> getMunicipios(String pURL) { Set<Municipality> result = new HashSet<Municipality>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniMun = "<muni>"; String finMun = "</muni>"; String iniNomMun = "<nm>"; String finNomMun = "</nm>"; String iniCarto = "<carto>"; String iniCodDelMEH = "<cd>"; String finCodDelMEH = "</cd>"; String iniCodMunMEH = "<cmc>"; String finCodMunMEH = "</cmc>"; String iniCodProvINE = "<cp>"; String finCodProvINE = "</cp>"; String iniCodMunINE = "<cm>"; String finCodMunINE = "</cm>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Municipality municipio; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniMun)) { municipio = new Municipality(); municipio.setCodemunicipalityine(0); municipio.setCodemunicipalitydgc(0); while ((str = br.readLine()) != null && !str.contains(finMun)) { if (str.contains(iniNomMun)) { ini = str.indexOf(iniNomMun) + iniNomMun.length(); fin = str.indexOf(finNomMun); municipio.setMuniName(str.substring(ini, fin).trim()); } if (str.contains(iniCarto)) { if (str.contains("URBANA")) municipio.setIsurban(true); if (str.contains("RUSTICA")) municipio.setIsrustic(true); } if (str.contains(iniCodDelMEH)) { ini = str.indexOf(iniCodDelMEH) + iniCodDelMEH.length(); fin = str.indexOf(finCodDelMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunMEH)) { ini = str.indexOf(iniCodMunMEH) + iniCodMunMEH.length(); fin = str.indexOf(finCodMunMEH); municipio.setCodemunicipalitydgc(municipio.getCodemunicipalitydgc() + Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniCodProvINE)) { ini = str.indexOf(iniCodProvINE) + iniCodProvINE.length(); fin = str.indexOf(finCodProvINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin)) * 1000); } if (str.contains(iniCodMunINE)) { ini = str.indexOf(iniCodMunINE) + iniCodMunINE.length(); fin = str.indexOf(finCodMunINE); municipio.setCodemunicipalityine(municipio.getCodemunicipalityine() + Integer.parseInt(str.substring(ini, fin))); } municipio.setDescription(); } result.add(municipio); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
00
Code Sample 1: public void GetList() throws Exception { Authenticator.setDefault(new MyAuth(this._user, this._pwd)); URL url = new URL(MyFanfou.PublicTimeLine); InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String json = ""; String line; while ((line = reader.readLine()) != null) json += line; JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); String users = object.getString("user"); JSONObject user = new JSONObject(users); System.out.println(object.getString("id") + ":" + user.getString("birthday")); } } Code Sample 2: private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); }
00
Code Sample 1: public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } } Code Sample 2: protected void onSubmit() { try { Connection conn = ((JdbcRequestCycle) getRequestCycle()).getConnection(); String sql = "insert into entry (author, accessibility) values(?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setInt(2, accessibility.getId()); pstmt.executeUpdate(); ResultSet insertedEntryIdRs = pstmt.getGeneratedKeys(); insertedEntryIdRs.next(); int insertedEntryId = insertedEntryIdRs.getInt(1); sql = "insert into revisions (title, entry, content, tags," + " revision_remark) values(?,?,?,?,?)"; PreparedStatement pstmt2 = conn.prepareStatement(sql); pstmt2.setString(1, getTitle()); pstmt2.setInt(2, insertedEntryId); pstmt2.setString(3, getContent()); pstmt2.setString(4, getTags()); pstmt2.setString(5, "newly added"); int insertCount = pstmt2.executeUpdate(); if (insertCount > 0) { info("Successfully added one new record."); } else { conn.rollback(); info("Addition of one new record failed."); } } catch (SQLException ex) { ex.printStackTrace(); } }
11
Code Sample 1: static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } Code Sample 2: public static void main(String[] argv) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56); String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String result = toString(md.digest()); System.out.println(exp); System.out.println(result); if (!exp.equals(result)) System.out.println("NOT EQUAL!"); }
00
Code Sample 1: private static boolean insereTutorial(final Connection con, final Tutorial tut, final Autor aut, final Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodTutorial(con, tut); String titulo = tut.getTitulo().replaceAll("['\"]", ""); String coment = tut.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO tutorial VALUES(" + tut.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO tut_aut VALUES(" + tut.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "TUTORIAL: Database error", JOptionPane.ERROR_MESSAGE); System.out.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); 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 null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; }
00
Code Sample 1: public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; } Code Sample 2: public boolean send(String number, String message) throws IOException { init(); message = message.substring(0, Math.min(MAX_PAYLOAD, message.length())); message = message.replace('\r', ' '); message = message.replace('\n', ' '); ActualFormParameters params = new ActualFormParameters(); String strippedNumber = strip(number); ActualFormParameter number1Param; ActualFormParameter number2Param; if (strippedNumber.startsWith("00")) strippedNumber = "+" + strippedNumber.substring(2); else if (strippedNumber.startsWith("0")) strippedNumber = "+49" + strippedNumber.substring(1); number1Param = new ActualFormParameter(number1InputElement.getName(), strippedNumber.substring(0, 6)); number2Param = new ActualFormParameter(number2InputElement.getName(), strippedNumber.substring(6)); params.add(number1Param); params.add(number2Param); ActualFormParameter messageParam = new ActualFormParameter(messageInputElement.getName(), message); params.add(messageParam); ActualFormParameter letterCountParam = new ActualFormParameter(letterCountInputElement.getName(), "" + (MAX_PAYLOAD - message.length())); params.add(letterCountParam); form.addDefaultParametersTo(params); Reader r = form.submitForm(params, form.getNetscapeRequestProperties()); String result = getStringFromReader(r); String pattern = "<meta http-equiv = \"refresh\" content=\"1; url="; int patternIndex = result.indexOf(pattern); if (patternIndex < 0) return false; int end = result.lastIndexOf("\">"); if (end < 0) return false; String url = result.substring(patternIndex + pattern.length(), end); result = getStringFromReader(new InputStreamReader(new URL(url).openStream())); return result.indexOf("wurde erfolgreich verschickt") >= 0; }
11
Code Sample 1: public void alterar(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "update cliente set nome = ?, sexo = ?, cod_cidade = ? where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); stmt.setLong(4, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } } Code Sample 2: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
00
Code Sample 1: public void doNew(Vector userId, String shareFlag, String folderId) throws AddrException { DBOperation dbo = null; Connection connection = null; PreparedStatement ps = null; ResultSet rset = null; String sql = "insert into " + SHARE_TABLE + " values(?,?,?)"; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); for (int i = 0; i < userId.size(); i++) { String user = (String) userId.elementAt(i); ps = connection.prepareStatement(sql); ps.setInt(1, Integer.parseInt(folderId)); ps.setInt(2, Integer.parseInt(user)); ps.setString(3, shareFlag); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new Exception("error"); } } connection.commit(); } catch (Exception ex) { if (connection != null) { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } logger.error("���������ļ�����Ϣʧ��, " + ex.getMessage()); throw new AddrException("���������ļ�����Ϣʧ��,һ�������ļ���ֻ�ܹ����ͬһ�û�һ��!"); } finally { close(rset, null, ps, connection, dbo); } } Code Sample 2: private HttpURLConnection makeGetRequest(String action, Object... parameters) throws IOException { StringBuffer request = new StringBuffer(remoteUrl); HTMLUtils.appendQuery(request, VERSION_PARAM, CLIENT_VERSION); HTMLUtils.appendQuery(request, ACTION_PARAM, action); for (int i = 0; i < parameters.length; i += 2) { HTMLUtils.appendQuery(request, String.valueOf(parameters[i]), String.valueOf(parameters[i + 1])); } String requestStr = request.toString(); URLConnection conn; if (requestStr.length() < MAX_URL_LENGTH) { URL url = new URL(requestStr); conn = url.openConnection(); } else { int queryPos = requestStr.indexOf('?'); byte[] query = requestStr.substring(queryPos + 1).getBytes(HTTPUtils.DEFAULT_CHARSET); URL url = new URL(requestStr.substring(0, queryPos)); conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(query.length)); OutputStream outputStream = new BufferedOutputStream(conn.getOutputStream()); outputStream.write(query); outputStream.close(); } return (HttpURLConnection) conn; }
11
Code Sample 1: public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } } Code Sample 2: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
11
Code Sample 1: private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } } Code Sample 2: protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
00
Code Sample 1: private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String prefix, String suffix) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, prefix, suffix); } else { if (isFileNameMatch(folder.getName(), prefix, suffix)) { FileInputStream fis = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); IOUtils.copy(fis, zip); fis.close(); } } } Code Sample 2: public Long processAddHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_HOLDING"); seq.setTableName("WM_LIST_HOLDING"); seq.setColumnName("ID_HOLDING"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_HOLDING " + "( ID_HOLDING, full_name_HOLDING, NAME_HOLDING )" + "values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); HoldingBean bean = new HoldingBean(holdingBean); bean.setId(sequenceValue); processInsertRelatedCompany(dbDyn, bean, authSession); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static ArrayList<Credential> importCredentials(String urlString) { ArrayList<Credential> results = new ArrayList<Credential>(); try { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); if (line.equals("-----END PGP SIGNATURE-----")) { Credential credential = ProfileParser.parseCredential(buff.toString(), true); results.add(credential); buff = new StringBuffer(); } else { buff.append(NL); } } } catch (MalformedURLException e) { } catch (IOException e) { } catch (ParsingException e) { System.err.println(e); } return results; } Code Sample 2: JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } }
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 boolean openInputStream() throws Exception { open = false; if (filename == null) return false; try { url = new URL(filename); con = url.openConnection(); con.connect(); lengthOfData = con.getContentLength(); System.out.println(" headers for url: " + url); System.out.println(" lengthOfData = " + lengthOfData); Map m = con.getHeaderFields(); Set s = m.keySet(); Iterator i = s.iterator(); while (i.hasNext()) { String x = (String) i.next(); Object o = m.get(x); String y = null; if (o instanceof String) y = (String) o; else if (o instanceof Collection) y = "" + (Collection) o; else if (o instanceof Integer) y = "" + (Integer) o; else y = o.getClass().getName(); System.out.println(" header " + x + " = " + y); } infile = new DataInputStream(con.getInputStream()); } catch (Exception e) { e.printStackTrace(); throw e; } open = true; count = 0; countLastRead = 0; return true; }
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: protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
11
Code Sample 1: public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/Chrom_623_620.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); s = br.readLine(); st = new StringTokenizer(s); chrom_x[i][j] = Double.parseDouble(st.nextToken()); temp_prev = chrom_x[i][j]; chrom_y[i][j] = Double.parseDouble(st.nextToken()); gridmin = chrom_x[i][j]; gridmax = chrom_x[i][j]; sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); j++; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } chrom_x[i][j] = temp_new; chrom_y[i][j] = Double.parseDouble(st.nextToken()); sext1[i][j] = Double.parseDouble(st.nextToken()); sext2[i][j] = Double.parseDouble(st.nextToken()); sext3[i][j] = Double.parseDouble(st.nextToken()); sext4[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; if (chrom_x[i][j] <= gridmin) gridmin = chrom_x[i][j]; if (chrom_x[i][j] >= gridmax) gridmax = chrom_x[i][j]; } } Code Sample 2: public String getpage(String leurl) throws Exception { int data; StringBuffer lapage = new StringBuffer(); URL myurl = new URL(leurl); URLConnection conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return lapage.toString(); } InputStream in = conn.getInputStream(); for (data = in.read(); data != -1; data = in.read()) lapage.append((char) data); return lapage.toString(); }
11
Code Sample 1: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
11
Code Sample 1: private void copy(String inputPath, String outputPath, String name) { try { FileReader in = new FileReader(inputPath + name); FileWriter out = new FileWriter(outputPath + name); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: @Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
00
Code Sample 1: private boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) { try { String ret; String xml; String moviehash = getHash(movieFile); String moviebytesize = String.valueOf(movieFile.length()); xml = generateXMLRPCSS(moviehash, moviebytesize); ret = sendRPC(xml); String subDownloadLink = getValue("SubDownloadLink", ret); if (subDownloadLink.equals("")) { String moviefilename = movieFile.getName(); if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) { String subfilename = subtitleFile.getName(); int index = subfilename.lastIndexOf("."); String query = subfilename.substring(0, index); xml = generateXMLRPCSS(query); ret = sendRPC(xml); subDownloadLink = getValue("SubDownloadLink", ret); } } if (subDownloadLink.equals("")) { logger.finer("OpenSubtitles Plugin: Subtitle not found for " + movie.getBaseName()); return false; } logger.finer("OpenSubtitles Plugin: Download subtitle for " + movie.getBaseName()); URL url = new URL(subDownloadLink); HttpURLConnection connection = (HttpURLConnection) (url.openConnection()); connection.setRequestProperty("Connection", "Close"); InputStream inputStream = connection.getInputStream(); int code = connection.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { logger.severe("OpenSubtitles Plugin: Download Failed"); return false; } GZIPInputStream a = new GZIPInputStream(inputStream); OutputStream out = new FileOutputStream(subtitleFile); byte buf[] = new byte[1024]; int len; while ((len = a.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); movie.setSubtitles(true); return true; } catch (Exception e) { logger.severe("OpenSubtitles Plugin: Download Exception (Movie Not Found)"); return false; } } Code Sample 2: public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: public String getResponse(URL url) throws OAuthException { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (IOException e) { throw new OAuthException("Error getting HTTP response", e); } } Code Sample 2: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
11
Code Sample 1: public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } Code Sample 2: public static String md5sum(String s, String alg) { try { MessageDigest md = MessageDigest.getInstance(alg); md.update(s.getBytes(), 0, s.length()); StringBuffer sb = new StringBuffer(); synchronized (sb) { for (byte b : md.digest()) sb.append(pad(Integer.toHexString(0xFF & b), ZERO.charAt(0), 2, true)); } return sb.toString(); } catch (Exception ex) { log(ex); } return null; }
11
Code Sample 1: private void handleServerIntroduction(DataPacket serverPacket) { DataPacketIterator iter = serverPacket.getDataPacketIterator(); String version = iter.nextString(); int serverReportedUDPPort = iter.nextUByte2(); _authKey = iter.nextUByte4(); _introKey = iter.nextUByte4(); _clientKey = makeClientKey(_authKey, _introKey); String passwordKey = iter.nextString(); _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort); DataPacket packet = null; if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) { ParameterBuilder builder = new ParameterBuilder(); builder.appendUByte2(_udpSocket.getLocalPort()); builder.appendString(_user); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ignore) { } md5.update(_serverKey.getBytes()); md5.update(passwordKey.getBytes()); md5.update(_password.getBytes()); for (byte b : md5.digest()) { builder.appendByte(b); } packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter()); } else { packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY); } sendTCPPacket(packet); } Code Sample 2: public static String getHash(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { logger.debug("Entering getHash with password = " + password + "\n and salt = " + salt); MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.reset(); digest.update(salt.getBytes()); byte[] input = digest.digest(password.getBytes("UTF-8")); String hashResult = String.valueOf(input); logger.debug("Exiting getHash with hasResult of " + hashResult); return hashResult; }
00
Code Sample 1: public boolean connect() { if (connectStatus > -1) return (connectStatus == 1); connectStatus = 0; try { URL url = new URL(getURL()); m_connection = (HttpURLConnection) url.openConnection(); m_connection.connect(); processHeaders(); m_inputStream = m_connection.getInputStream(); } catch (MalformedURLException e) { newError("connect failed", e, true); } catch (IOException e) { newError("connect failed", e, true); } return (connectStatus == 1); } Code Sample 2: public static String cryptoSHA(String _strSrc) { try { BASE64Encoder encoder = new BASE64Encoder(); MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(_strSrc.getBytes()); byte[] buffer = sha.digest(); return encoder.encode(buffer); } catch (Exception err) { System.out.println(err); } return ""; }
00
Code Sample 1: void readFileHeader(DmgConfigDMO config, ConfigLocation sl) throws IOException { fileHeader = ""; if (config.getGeneratedFileHeader() != null) { StringBuffer sb = new StringBuffer(); if (sl.getJarFilename() != null) { URL url = new URL("jar:file:" + sl.getJarFilename() + "!/" + sl.getJarDirectory() + "/" + config.getGeneratedFileHeader()); LineNumberReader in = new LineNumberReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } else { LineNumberReader in = new LineNumberReader(new FileReader(sl.getDirectory() + File.separator + config.getGeneratedFileHeader())); String str; while ((str = in.readLine()) != null) { sb.append(str + "\n"); } in.close(); } fileHeader = sb.toString(); } } Code Sample 2: public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } }
00
Code Sample 1: public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: private boolean downloadFile(Proxy proxy, URL url, File file) { try { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = new File(file.getAbsolutePath() + ".update"); ; FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); file.delete(); destFile.renameTo(file); return true; } catch (Exception e) { logger.error("Failed to get remote hosts file.", e); } return false; }
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 copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: @Override public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException { String key = logFileNameExtractor.getFileName(fileStatus); int wasWritten = 0; FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key); RollBackOutputStream outputStream = null; File file = null; try { file = getOutputFile(key); lastWrittenFile = file; outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true); outputStream.mark(); wasWritten = IOUtils.copy(input, outputStream); if (postWriteAction != null) { postWriteAction.run(wasWritten); } } catch (Throwable t) { LOG.error(t.toString(), t); if (outputStream != null && wasWritten > 0) { LOG.error("Rolling back file " + file.getAbsolutePath()); try { outputStream.rollback(); } catch (IOException e) { throwException(e); } catch (InterruptedException e) { throw e; } } throwException(t); } finally { try { fileOutputStreamPool.releaseFile(key); } catch (IOException e) { throwException(e); } } return wasWritten; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: private boolean createPKCReqest(String keystoreLocation, String pw) { boolean created = false; Security.addProvider(new BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when creating PKC request: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when creating PKC request: " + e.getMessage()); } return false; } PKCS10CertificationRequest request = null; PublicKey pk = cert.getPublicKey(); try { request = new PKCS10CertificationRequest("SHA1with" + pk.getAlgorithm(), new X500Principal(((X509Certificate) cert).getSubjectDN().toString()), pk, new DERSet(), (PrivateKey) ks.getKey("saws", pw.toCharArray())); PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileOutputStream("sawsRequest.csr"))); pemWrt.writeObject(request); pemWrt.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error creating PKC request file: " + e.getMessage()); } return false; } return created; } 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); } }
11
Code Sample 1: public String getMessageofTheDay(String id) { StringBuffer mod = new StringBuffer(); int serverModId = 0; int clientModId = 0; BufferedReader input = null; try { URL url = new URL(FlyShareApp.BASE_WEBSITE_URL + "/mod.txt"); input = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; inputLine = input.readLine(); try { clientModId = Integer.parseInt(id); serverModId = Integer.parseInt(inputLine); } catch (NumberFormatException e) { } if (clientModId < serverModId || clientModId == 0) { mod.append(serverModId); mod.append('|'); while ((inputLine = input.readLine()) != null) mod.append(inputLine); } } catch (MalformedURLException e) { } catch (IOException e) { } finally { try { input.close(); } catch (Exception e) { } } return mod.toString(); } Code Sample 2: public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
11
Code Sample 1: private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); } 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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } } Code Sample 2: private Properties loadPropertiesFromURL(String propertiesURL, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); URL url; try { url = new URL(propertiesURL); URLConnection urlConnection = url.openConnection(); properties.load(urlConnection.getInputStream()); } catch (MalformedURLException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } return properties; }
00
Code Sample 1: public static void saveZipComponents(ZipComponents zipComponents, File zipFile) throws FileNotFoundException, IOException, Exception { ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (ZipComponent comp : zipComponents.getComponents()) { ZipEntry newEntry = new ZipEntry(comp.getName()); zipOutStream.putNextEntry(newEntry); if (comp.isDirectory()) { } else { if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) { } InputStream inputStream = comp.getInputStream(); IOUtils.copy(inputStream, zipOutStream); inputStream.close(); } } zipOutStream.close(); } Code Sample 2: private static void discoverRegisteryEntries(DataSourceRegistry registry) { try { Enumeration<URL> urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public Leilao insertLeilao(Leilao leilao) throws SQLException { Connection conn = null; String insert = "insert into Leilao (idleilao, atividade_idatividade, datainicio, datafim) " + "values " + "(nextval('seq_leilao'), " + leilao.getAtividade().getIdAtividade() + ", '" + leilao.getDataInicio() + "', '" + leilao.getDataFim() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_leilao"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { leilao.setIdLeilao(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; } Code Sample 2: public static String encryptString(String str) { StringBuffer sb = new StringBuffer(); int i; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] md5Bytes = md5.digest(); for (i = 0; i < md5Bytes.length; i++) { sb.append(md5Bytes[i]); } } catch (Exception e) { } return sb.toString(); }
00
Code Sample 1: public Resultado procesar() { if (resultado != null) return resultado; int[] a = new int[elems.size()]; Iterator iter = elems.iterator(); int w = 0; while (iter.hasNext()) { a[w] = ((Integer) iter.next()).intValue(); w++; } int n = a.length; long startTime = System.currentTimeMillis(); int i, j, temp; for (i = 0; i < n - 1; i++) { for (j = i; j < n - 1; j++) { if (a[i] > a[j + 1]) { temp = a[i]; a[i] = a[j + 1]; a[j + 1] = temp; pasos++; } } } long endTime = System.currentTimeMillis(); resultado = new Resultado((int) (endTime - startTime), pasos, a.length); System.out.println("Resultado BB: " + resultado); return resultado; } Code Sample 2: public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
00
Code Sample 1: public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); } Code Sample 2: public void testBackup() throws Exception { masterJetty.stop(); copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml")); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); for (int i = 0; i < 500; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); class BackupThread extends Thread { volatile String fail = null; public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } ; } ; BackupThread backupThread = new BackupThread(); backupThread.start(); File dataDir = new File(master.getDataDir()); class CheckStatus extends Thread { volatile String fail = null; volatile String response = null; volatile boolean success = false; public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream); if (response.contains("<str name=\"status\">success</str>")) { success = true; } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } ; } ; int waitCnt = 0; CheckStatus checkStatus = new CheckStatus(); while (true) { checkStatus.run(); if (checkStatus.fail != null) { fail(checkStatus.fail); } if (checkStatus.success) { break; } Thread.sleep(200); if (waitCnt == 10) { fail("Backup success not detected:" + checkStatus.response); } waitCnt++; } if (backupThread.fail != null) { fail(backupThread.fail); } File[] files = dataDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.startsWith("snapshot")) { return true; } return false; } }); assertEquals(1, files.length); File snapDir = files[0]; IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(snapDir.getAbsoluteFile(), null), true); TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1); assertEquals(500, hits.totalHits); }
11
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: @Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } }
00
Code Sample 1: @Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; } Code Sample 2: public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
00
Code Sample 1: public boolean send(String number, String message) throws IOException { init(); message = message.substring(0, Math.min(MAX_PAYLOAD, message.length())); message = message.replace('\r', ' '); message = message.replace('\n', ' '); ActualFormParameters params = new ActualFormParameters(); String strippedNumber = strip(number); ActualFormParameter number1Param; ActualFormParameter number2Param; if (strippedNumber.startsWith("00")) strippedNumber = "+" + strippedNumber.substring(2); else if (strippedNumber.startsWith("0")) strippedNumber = "+49" + strippedNumber.substring(1); number1Param = new ActualFormParameter(number1InputElement.getName(), strippedNumber.substring(0, 6)); number2Param = new ActualFormParameter(number2InputElement.getName(), strippedNumber.substring(6)); params.add(number1Param); params.add(number2Param); ActualFormParameter messageParam = new ActualFormParameter(messageInputElement.getName(), message); params.add(messageParam); ActualFormParameter letterCountParam = new ActualFormParameter(letterCountInputElement.getName(), "" + (MAX_PAYLOAD - message.length())); params.add(letterCountParam); form.addDefaultParametersTo(params); Reader r = form.submitForm(params, form.getNetscapeRequestProperties()); String result = getStringFromReader(r); String pattern = "<meta http-equiv = \"refresh\" content=\"1; url="; int patternIndex = result.indexOf(pattern); if (patternIndex < 0) return false; int end = result.lastIndexOf("\">"); if (end < 0) return false; String url = result.substring(patternIndex + pattern.length(), end); result = getStringFromReader(new InputStreamReader(new URL(url).openStream())); return result.indexOf("wurde erfolgreich verschickt") >= 0; } Code Sample 2: public static void find(String pckgname, Class tosubclass) { String name = new String(pckgname); if (!name.startsWith("/")) { name = "/" + name; } name = name.replace('.', '/'); URL url = RTSI.class.getResource(name); System.out.println(name + "->" + url); if (url == null) return; File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Object o = Class.forName(pckgname + "." + classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); String starts = conn.getEntryName(); JarFile jfile = conn.getJarFile(); Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Object o = Class.forName(classname).newInstance(); if (tosubclass.isInstance(o)) { System.out.println(classname.substring(classname.lastIndexOf('.') + 1)); } } catch (ClassNotFoundException cnfex) { System.err.println(cnfex); } catch (InstantiationException iex) { } catch (IllegalAccessException iaex) { } } } } catch (IOException ioex) { System.err.println(ioex); } } }
00
Code Sample 1: public String buscaSAIKU() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("SAIKU")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")) { miLinea = inputLine; log.debug(miLinea); miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/saiku-bi-platform-plugin/target")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build SAIKU: " + miLinea); return miLinea; } Code Sample 2: private static URL lookForDefaultThemeFile(String aFilename) { try { XPathFactory fabrique = XPathFactory.newInstance(); XPath environnement = fabrique.newXPath(); URL url = new URL("file:" + aFilename); InputSource source = new InputSource(url.openStream()); XPathExpression expression; expression = environnement.compile("/alloy/instance/@filename"); String resultat = expression.evaluate(source); AlloyPlugin.getDefault().logInfo("Solution coming from " + resultat); IPath path = new Path(resultat); IPath themePath = path.removeFileExtension().addFileExtension("thm"); File themeFile = themePath.toFile(); if (themeFile.exists()) { AlloyPlugin.getDefault().logInfo("Found default theme " + themeFile); return themeFile.toURI().toURL(); } } catch (MalformedURLException e) { AlloyPlugin.getDefault().log(e); } catch (IOException e) { AlloyPlugin.getDefault().log(e); } catch (XPathExpressionException e) { AlloyPlugin.getDefault().log(e); } return null; }
11
Code Sample 1: public static String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; } Code Sample 2: private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
00
Code Sample 1: private void bokActionPerformed(java.awt.event.ActionEvent evt) { if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) { this.showWarningMessage("Enter Series Title"); } else { String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet"); 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(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } } } Code Sample 2: private GenomicSequence fetch(Chromosome k, int start, int end) throws IOException { try { String chr = k.toString(); if (chr.toLowerCase().startsWith("chr")) chr = chr.substring(3); SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(false); f.setValidating(false); SAXParser parser = f.newSAXParser(); URL url = new URL("http://genome.ucsc.edu/cgi-bin/das/" + genomeVersion + "/dna?segment=" + URLEncoder.encode(chr, "UTF-8") + ":" + (start + 1) + "," + (end)); DASHandler handler = new DASHandler(); InputStream in = url.openStream(); parser.parse(in, handler); in.close(); GenomicSequence seq = new GenomicSequence(); seq.sequence = handler.bytes.toByteArray(); seq.start = start; seq.end = end; if (seq.sequence.length != seq.length()) throw new IOException("bad bound " + seq + " " + seq.sequence.length + " " + seq.length()); return seq; } catch (IOException err) { throw err; } catch (Exception e) { throw new IOException(e); } }
00
Code Sample 1: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } Code Sample 2: public Dbf(URL url) throws java.io.IOException, DbfFileException { if (DEBUG) System.out.println("---->uk.ac.leeds.ccg.dbffile.Dbf constructed. Will identify itself as " + DBC); URLConnection uc = url.openConnection(); InputStream in = uc.getInputStream(); EndianDataInputStream sfile = new EndianDataInputStream(in); init(sfile); }
00
Code Sample 1: @Override public void send(String payload, TransportReceiver receiver) { HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); configureConnection(connection); OutputStream out = connection.getOutputStream(); out.write(payload.getBytes("UTF-8")); out.close(); int status = connection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { ServerFailure failure = new ServerFailure(status + " " + connection.getResponseMessage()); receiver.onTransportFailure(failure); return; } List<String> cookieHeaders = connection.getHeaderFields().get("Set-Cookie"); if (cookieHeaders != null) { for (String header : cookieHeaders) { try { JSONObject cookie = Cookie.toJSONObject(header); String name = cookie.getString("name"); String value = cookie.getString("value"); String domain = cookie.optString("Domain"); if (domain == null || url.getHost().endsWith(domain)) { String path = cookie.optString("Path"); if (path == null || url.getPath().startsWith(path)) { cookies.put(name, value); } } } catch (JSONException ignored) { } } } String encoding = connection.getContentEncoding(); InputStream in = connection.getInputStream(); if ("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else if ("deflate".equalsIgnoreCase(encoding)) { in = new InflaterInputStream(in); } else if (encoding != null) { receiver.onTransportFailure(new ServerFailure("Unknown server encoding " + encoding)); return; } ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int read = in.read(buffer); while (read != -1) { bytes.write(buffer, 0, read); read = in.read(buffer); } in.close(); String received = new String(bytes.toByteArray(), "UTF-8"); receiver.onTransportSuccess(received); } catch (IOException e) { ServerFailure failure = new ServerFailure(e.getMessage(), e.getClass().getName(), null, true); receiver.onTransportFailure(failure); } finally { if (connection != null) { connection.disconnect(); } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } } Code Sample 2: private static void identify(ContentNetwork cn, String str) { try { URL url = new URL(str); HttpURLConnection con = (HttpURLConnection) url.openConnection(); UrlUtils.setBrowserHeaders(con, null); String key = "cn." + cn.getID() + ".identify.cookie"; String cookie = COConfigurationManager.getStringParameter(key, null); if (cookie != null) { con.setRequestProperty("Cookie", cookie + ";"); } con.setRequestProperty("Connection", "close"); con.getResponseCode(); cookie = con.getHeaderField("Set-Cookie"); if (cookie != null) { String[] bits = cookie.split(";"); if (bits.length > 0 && bits[0].length() > 0) { COConfigurationManager.setParameter(key, bits[0]); } } } catch (Throwable e) { } }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String get(String u, String usr, String pwd) { String response = ""; logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(0); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); logger.debug("Response: " + sb.toString()); response = sb.toString(); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
00
Code Sample 1: @BeforeClass public static void setUpOnce() throws OWLOntologyCreationException { dbManager = (OWLDBOntologyManager) OWLDBManager.createOWLOntologyManager(OWLDataFactoryImpl.getInstance()); dbIRI = IRI.create(ontoUri); System.out.println("copying ontology to work folder..."); try { final File directory = new File("./resources/LUBM10-DB-forUpdate/"); final File[] filesToDelete = directory.listFiles(); if (filesToDelete != null && filesToDelete.length > 0) { for (final File file : filesToDelete) { if (!file.getName().endsWith(".svn")) Assert.assertTrue(file.delete()); } } final File original = new File("./resources/LUBM10-DB/LUBM10.h2.db"); final File copy = new File("./resources/LUBM10-DB-forUpdate/LUBM10.h2.db"); final FileChannel inChannel = new FileInputStream(original).getChannel(); final FileChannel outChannel = new FileOutputStream(copy).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException ioe) { System.err.println(ioe.getMessage()); Assert.fail(); } onto = (OWLMutableOntology) dbManager.loadOntology(dbIRI); factory = dbManager.getOWLDataFactory(); } Code Sample 2: public void execute(PaymentInfoMagcard payinfo) { if (payinfo.getTotal().compareTo(BigDecimal.ZERO) > 0) { try { StringBuffer sb = new StringBuffer(); sb.append("x_login="); sb.append(URLEncoder.encode(m_sCommerceID, "UTF-8")); sb.append("&x_password="); sb.append(URLEncoder.encode(m_sCommercePassword, "UTF-8")); sb.append("&x_version=3.1"); sb.append("&x_test_request="); sb.append(m_bTestMode); sb.append("&x_method=CC"); sb.append("&x_type="); sb.append(OPERATIONVALIDATE); sb.append("&x_amount="); NumberFormat formatter = new DecimalFormat("000.00"); String amount = formatter.format(payinfo.getTotal()); sb.append(URLEncoder.encode((String) amount, "UTF-8")); sb.append("&x_delim_data=TRUE"); sb.append("&x_delim_char=|"); sb.append("&x_relay_response=FALSE"); sb.append("&x_exp_date="); String tmp = payinfo.getExpirationDate(); sb.append(tmp.charAt(2)); sb.append(tmp.charAt(3)); sb.append(tmp.charAt(0)); sb.append(tmp.charAt(1)); sb.append("&x_card_num="); sb.append(URLEncoder.encode(payinfo.getCardNumber(), "UTF-8")); sb.append("&x_description=Shop+Transaction"); String[] cc_name = payinfo.getHolderName().split(" "); sb.append("&x_first_name="); if (cc_name.length > 0) { sb.append(URLEncoder.encode(cc_name[0], "UTF-8")); } sb.append("&x_last_name="); if (cc_name.length > 1) { sb.append(URLEncoder.encode(cc_name[1], "UTF-8")); } URL url = new URL(ENDPOINTADDRESS); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(sb.toString().getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; line = in.readLine(); in.close(); String[] ccRep = line.split("\\|"); if ("1".equals(ccRep[0])) { payinfo.paymentOK((String) ccRep[4]); } else { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + ccRep[0] + " -- " + ccRep[3]); } } catch (UnsupportedEncodingException eUE) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eUE.getMessage()); } catch (MalformedURLException eMURL) { payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice") + "\n" + eMURL.getMessage()); } catch (IOException e) { payinfo.paymentError(AppLocal.getIntString("message.paymenterror") + "\n" + e.getMessage()); } } else { payinfo.paymentError(AppLocal.getIntString("message.paymentrefundsnotsupported")); } }
00
Code Sample 1: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; } Code Sample 2: public static int writeFile(URL url, File outFilename) { InputStream input; try { input = url.openStream(); } catch (IOException e) { e.printStackTrace(); return 0; } FileOutputStream outputStream; try { outputStream = new FileOutputStream(outFilename); } catch (FileNotFoundException e) { e.printStackTrace(); return 0; } return writeFile(input, outputStream); }
00
Code Sample 1: public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } } Code Sample 2: public static Recipes addRecipe(Lists complexity, String about, String title, Users user, int preparationTime, int cookingTime, int servings, Lists dishType, String picUrl, Iterable<String> instructions) throws Exception { URL url = new URL(picUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); Recipes rec = new Recipes(user, title, about, preparationTime, cookingTime, servings, complexity, dishType, Hibernate.createBlob(conn.getInputStream(), conn.getContentLength()), new Date(), 0); session.save(rec); for (String s : instructions) { createRecipeInstructions(rec, s); } return rec; }
11
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: public OOXMLSignatureService(InputStream documentInputStream, OutputStream documentOutputStream, SignatureFacet signatureFacet, String role, IdentityDTO identity, byte[] photo, RevocationDataService revocationDataService, TimeStampService timeStampService, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".ooxml"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(signatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
00
Code Sample 1: public static void insert(Connection c, MLPApprox net, int azioneId, String descrizione, int[] indiciID, int output, Date from, Date to) throws SQLException { try { PreparedStatement ps = c.prepareStatement(insertNet, PreparedStatement.RETURN_GENERATED_KEYS); ArrayList<Integer> indexes = new ArrayList<Integer>(indiciID.length); for (int i = 0; i < indiciID.length; i++) indexes.add(indiciID[i]); ps.setObject(1, net); ps.setInt(2, azioneId); ps.setObject(3, indexes); ps.setInt(4, output); ps.setDate(5, from); ps.setDate(6, to); ps.setString(7, descrizione); ps.executeUpdate(); ResultSet key = ps.getGeneratedKeys(); if (key.next()) { int id = key.getInt(1); for (int i = 0; i < indiciID.length; i++) { PreparedStatement psIndex = c.prepareStatement(insertNetIndex); psIndex.setInt(1, indiciID[i]); psIndex.setInt(2, id); psIndex.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw e1; } throw e; } } Code Sample 2: protected URLConnection getConnection(String uri, String data) throws MalformedURLException, IOException { URL url = new URL(uri); URLConnection conn = url.openConnection(); conn.setConnectTimeout((int) MINUTE / 2); conn.setReadTimeout((int) MINUTE / 2); return conn; }
00
Code Sample 1: private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; } Code Sample 2: public static String getDigestResponse(String user, String password, String method, String requri, String authstr) { String realm = ""; String nonce = ""; String opaque = ""; String algorithm = ""; String qop = ""; StringBuffer digest = new StringBuffer(); String cnonce; String noncecount; String pAuthStr = authstr; int ptr = 0; String response = ""; int i = 0; StringTokenizer st = new StringTokenizer(pAuthStr, ","); StringTokenizer stprob = null; String str = null; String key = null; String value = null; Properties probs = new Properties(); while (st.hasMoreTokens()) { String nextToken = st.nextToken(); stprob = new StringTokenizer(nextToken, "="); key = stprob.nextToken(); value = stprob.nextToken(); if (value.charAt(0) == '"' || value.charAt(0) == '\'') { value = value.substring(1, value.length() - 1); } probs.put(key, value); } digest.append("Digest username=\"" + user + "\", "); digest.append("realm=\""); digest.append(probs.getProperty("realm")); digest.append("\", "); digest.append("nonce=\""); digest.append(probs.getProperty("nonce")); digest.append("\", "); digest.append("uri=\"" + requri + "\", "); cnonce = "abcdefghi"; noncecount = "00000001"; String toDigest = user + ":" + realm + ":" + password; byte[] digestbuffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toDigest.getBytes()); digestbuffer = md.digest(); } catch (Exception e) { System.err.println("Error creating digest request: " + e); return null; } digest.append("qop=\"auth\", "); digest.append("cnonce=\"" + cnonce + "\", "); digest.append("nc=" + noncecount + ", "); digest.append("response=\"" + response + "\""); if (probs.getProperty("opaque") != null) { digest.append(", opaque=\"" + probs.getProperty("opaque") + "\""); } System.out.println("SipProtocol: Digest calculated."); return digest.toString(); }
00
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); throw new RuntimeException(e); } }
00
Code Sample 1: protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; } Code Sample 2: @SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private static void checkClients() { try { sendMultiListEntry('l'); } catch (Exception e) { if (Util.getDebugLevel() > 90) e.printStackTrace(); } try { if (CANT_CHECK_CLIENTS != null) KeyboardHero.removeStatus(CANT_CHECK_CLIENTS); URL url = new URL(URL_STR + "?req=clients" + (server != null ? "&port=" + server.getLocalPort() : "")); URLConnection connection = url.openConnection(getProxy()); connection.setRequestProperty("User-Agent", USER_AGENT); BufferedReader bufferedRdr = new BufferedReader(new InputStreamReader(connection.getInputStream())); String ln; if (Util.getDebugLevel() > 30) Util.debug("URL: " + url); while ((ln = bufferedRdr.readLine()) != null) { String[] parts = ln.split(":", 2); if (parts.length < 2) { Util.debug(12, "Line read in checkClients: " + ln); continue; } try { InetSocketAddress address = new InetSocketAddress(parts[0], Integer.parseInt(parts[1])); boolean notFound = true; if (Util.getDebugLevel() > 25) Util.debug("NEW Address: " + address.toString()); synchronized (clients) { Iterator<Client> iterator = clients.iterator(); while (iterator.hasNext()) { final Client client = iterator.next(); if (client.socket.isClosed()) { iterator.remove(); continue; } if (Util.getDebugLevel() > 26 && client.address != null) Util.debug("Address: " + client.address.toString()); if (address.equals(client.address)) { notFound = false; break; } } } if (notFound) { connectClient(address); } } catch (NumberFormatException e) { } } bufferedRdr.close(); } catch (MalformedURLException e) { Util.conditionalError(PORT_IN_USE, "Err_PortInUse"); Util.error(Util.getMsg("Err_CantCheckClients")); } catch (FileNotFoundException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), Util.getMsg("Err_FileNotFound")); } catch (SocketException e) { Util.error(Util.getMsg("Err_CantCheckClients_Proxy"), e.getLocalizedMessage()); } catch (Exception e) { CANT_CHECK_CLIENTS.setException(e.toString()); KeyboardHero.addStatus(CANT_CHECK_CLIENTS); } } Code Sample 2: public static int[] sortDescending(int input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] < input[j + 1]) { int mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; }
00
Code Sample 1: public void bubble() { boolean test = false; int kars = 0, tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } System.out.print(kars + " " + tas); } Code Sample 2: @Override protected boolean sendBytes(byte[] data, int offset, int length) { try { String hex = toHex(data, offset, length); URL url = new URL(this.endpoint, "?raw=" + hex); System.out.println("Connecting to " + url); URLConnection conn = url.openConnection(); conn.connect(); Object content = conn.getContent(); return true; } catch (IOException ex) { LOGGER.warning(ex.getMessage()); return false; } }
00
Code Sample 1: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); } Code Sample 2: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; }
11
Code Sample 1: public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } Code Sample 2: private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private EventSeries<PhotoEvent> loadIncomingEvents(long reportID) { EventSeries<PhotoEvent> events = new EventSeries<PhotoEvent>(); try { URL url = new URL(SERVER_URL + XML_PATH + "reports.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = reader.readLine()) != null) { String[] values = str.split(","); if (values.length == 2) { long id = Long.parseLong(values[0]); if (id == reportID) { long time = Long.parseLong(values[1]); events.addEvent(new PhotoEvent(time)); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return events; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); } Code Sample 2: void writeToFile(String dir, InputStream input, String fileName) throws FileNotFoundException, IOException { makeDirs(dir); FileOutputStream fo = null; try { System.out.println(Thread.currentThread().getName() + " : " + "Writing file " + fileName + " to path " + dir); File file = new File(dir, fileName); fo = new FileOutputStream(file); IOUtils.copy(input, fo); } catch (Exception e) { e.printStackTrace(); System.err.println("Failed to write " + fileName); } }
00
Code Sample 1: protected String getCitations(String ticket, String query) throws IOException { String urlQuery; try { urlQuery = "http://www.jstor.org/search/BasicResults?hp=" + MAX_CITATIONS + "&si=1&gw=jtx&jtxsi=1&jcpsi=1&artsi=1&Query=" + URLEncoder.encode(query, "UTF-8") + "&wc=on&citationAction=saveAll"; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } URL url = new URL(urlQuery); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", ticket); return getCookie(COOKIE_CITATIONS, conn); } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
00
Code Sample 1: public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void zipDirectory(String dir, String zipfile) throws IOException, IllegalArgumentException { File d = new File(dir); if (!d.isDirectory()) throw new IllegalArgumentException("Not a directory: " + dir); String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); } Code Sample 2: public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } }
11
Code Sample 1: public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } } Code Sample 2: public void processAction(DatabaseAdapter db_, DataDefinitionActionDataListType parameters) throws Exception { PreparedStatement ps = null; try { if (log.isDebugEnabled()) log.debug("db connect - " + db_.getClass().getName()); String seqName = DefinitionService.getString(parameters, "sequence_name", null); if (seqName == null) { String errorString = "Name of sequnce not found"; log.error(errorString); throw new Exception(errorString); } String tableName = DefinitionService.getString(parameters, "name_table", null); if (tableName == null) { String errorString = "Name of table not found"; log.error(errorString); throw new Exception(errorString); } String columnName = DefinitionService.getString(parameters, "name_pk_field", null); if (columnName == null) { String errorString = "Name of column not found"; log.error(errorString); throw new Exception(errorString); } CustomSequenceType seqSite = new CustomSequenceType(); seqSite.setSequenceName(seqName); seqSite.setTableName(tableName); seqSite.setColumnName(columnName); long seqValue = db_.getSequenceNextValue(seqSite); String valueColumnName = DefinitionService.getString(parameters, "name_value_field", null); if (columnName == null) { String errorString = "Name of valueColumnName not found"; log.error(errorString); throw new Exception(errorString); } String insertValue = DefinitionService.getString(parameters, "insert_value", null); if (columnName == null) { String errorString = "Name of insertValue not found"; log.error(errorString); throw new Exception(errorString); } String sql = "insert into " + tableName + " " + "(" + columnName + "," + valueColumnName + ")" + "values" + "(?,?)"; if (log.isDebugEnabled()) { log.debug(sql); log.debug("pk " + seqValue); log.debug("value " + insertValue); } ps = db_.prepareStatement(sql); ps.setLong(1, seqValue); ps.setString(2, insertValue); ps.executeUpdate(); db_.commit(); } catch (Exception e) { try { db_.rollback(); } catch (Exception e1) { } log.error("Error insert value", e); throw e; } finally { org.riverock.generic.db.DatabaseManager.close(ps); ps = null; } }
11
Code Sample 1: private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; } Code Sample 2: private File newFile(File oldFile) throws IOException { int counter = 0; File nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName()); while (nFile.exists()) { nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName() + "_" + counter); } IOUtils.copyFile(oldFile, nFile); return nFile; }
11
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: public static String hashMD5(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
00
Code Sample 1: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } Code Sample 2: private Scanner getUrlScanner(String strUrl) { URL urlParticipants = null; Scanner scannerParticipants; try { urlParticipants = new URL(strUrl); URLConnection connParticipants; if (StringUtils.isBlank(this.configProxyIp)) { connParticipants = urlParticipants.openConnection(); } else { SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); connParticipants = urlParticipants.openConnection(proxy); } InputStream streamParticipant = connParticipants.getInputStream(); String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset="); scannerParticipants = new Scanner(streamParticipant, charSet); } catch (MalformedURLException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() })); } catch (IOException e) { throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() })); } return scannerParticipants; }
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 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; }
11
Code Sample 1: public void deletePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public void save(String oid, String key, Serializable obj) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _data_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to save object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } } Code Sample 2: public XmlDocument parseLocation(String locationUrl) { URL url = null; try { url = new URL(locationUrl); } catch (MalformedURLException e) { throw new XmlBuilderException("could not parse URL " + locationUrl, e); } try { return parseInputStream(url.openStream()); } catch (IOException e) { throw new XmlBuilderException("could not open connection to URL " + locationUrl, e); } }
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: public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
00
Code Sample 1: public static void main(String[] args) throws HttpException, IOException { String headerName = null; String t = "http://localhost:8080/access/content/group/81c8542d-3f58-48cf-ac72-9f482df47ebe/sss/QuestionarioSocioEc.pdf"; URL url = new URL(t); HttpURLConnection srvletConnection = (HttpURLConnection) url.openConnection(); srvletConnection.setDoOutput(true); srvletConnection.setDoInput(true); srvletConnection.setRequestMethod("POST"); srvletConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); String myCookie = "JSESSIONID=acab62f5-bc6a-4886-9719-e040e8af3fc6.localhost"; srvletConnection.setRequestProperty("Cookie", myCookie); srvletConnection.setInstanceFollowRedirects(false); srvletConnection.connect(); System.out.println(srvletConnection.getContent()); System.out.println(srvletConnection.getContentType()); System.out.println(srvletConnection.getContent().toString()); System.out.println(srvletConnection.getContentLength()); System.out.println(srvletConnection.getContentEncoding()); DataOutputStream out2 = new DataOutputStream(srvletConnection.getOutputStream()); out2.flush(); out2.close(); } Code Sample 2: public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
11
Code Sample 1: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } } Code Sample 2: private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
00
Code Sample 1: public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } Code Sample 2: private static List retrieveQuotes(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
11
Code Sample 1: protected void updateJava2ScriptProject(String prjFolder, String binRelative) { try { File cpFile = new File(prjFolder, ".classpath"); FileInputStream fis = new FileInputStream(cpFile); String classpath = J2SLaunchingUtil.readAFile(fis); if (classpath != null) { boolean needUpdate = false; if (classpath.indexOf("ECLIPSE_SWT") == -1 && classpath.indexOf("SWT_LIBRARY") == -1 && classpath.indexOf("eclipse.swt") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry kind=\"var\" path=\"ECLIPSE_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_SWT") == -1 && classpath.indexOf("ajaxswt.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_SWT_SRC\" kind=\"var\" path=\"AJAX_SWT\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_RPC") == -1 && classpath.indexOf("ajaxrpc.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_RPC_SRC\" kind=\"var\" path=\"AJAX_RPC\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (classpath.indexOf("AJAX_PIPE") == -1 && classpath.indexOf("ajaxpipe.jar") == -1) { int idx = classpath.lastIndexOf("<"); classpath = classpath.substring(0, idx) + "\t<classpathentry sourcepath=\"AJAX_PIPE_SRC\" kind=\"var\" path=\"AJAX_PIPE\"/>\r\n" + classpath.substring(idx); needUpdate = true; } if (needUpdate) { try { FileOutputStream fos = new FileOutputStream(cpFile); fos.write(classpath.getBytes("utf-8")); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } File webinf = new File(prjFolder, "WEB-INF"); webinf.mkdir(); new File(webinf, "classes").mkdir(); File lib = new File(webinf, "lib"); lib.mkdir(); IPath newPath = null; URL starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); String root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxrpc.jar"); File rpcFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(rpcFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxrpc.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root + "/ajaxpipe.jar"); File pipeFile = new File(newPath.toOSString()); try { FileInputStream is = new FileInputStream(pipeFile); FileOutputStream os = new FileOutputStream(new File(lib, "ajaxpipe.jar")); byte[] buf = new byte[1024]; int read = -1; while ((read = is.read(buf)) != -1) { os.write(buf, 0, read); } os.close(); is.close(); } catch (IOException e1) { e1.printStackTrace(); } StringBuffer buildxml = new StringBuffer(); buildxml.append("<?xml version=\"1.0\"?>\r\n"); buildxml.append("<project name=\"java2script.servlet.pack\" default=\"pack.war\" basedir=\".\">\r\n"); buildxml.append(" <description>Pack Java2Script Servlet Application</description>\r\n"); buildxml.append("\r\n"); String name = new File(prjFolder).getName(); buildxml.append(" <property name=\"java2script.app.name\" value=\"" + name + "\"/>\r\n"); buildxml.append(" <property name=\"bin.folder\" value=\"${basedir}/../" + binRelative + "\"/>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.war\" depends=\"pack.jar\">\r\n"); buildxml.append(" <tstamp>\r\n"); buildxml.append(" <format property=\"now\" pattern=\"yyyy-MM-dd-HH-mm-ss\"/>\r\n"); buildxml.append(" </tstamp>\r\n"); buildxml.append(" <delete file=\"${basedir}/../${java2script.app.name}.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../${java2script.app.name}.${now}.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/../\">\r\n"); buildxml.append(" <exclude name=\"src/**\"/>\r\n"); buildxml.append(" <exclude name=\"META-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.java\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.class\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" <fileset dir=\"${basedir}/..\">\r\n"); buildxml.append(" <include name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"WEB-INF/build.xml\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" <copy file=\"${basedir}/../${java2script.app.name}.${now}.war\"\r\n"); buildxml.append(" tofile=\"${basedir}/../${java2script.app.name}.war\"/>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append(" <target name=\"pack.jar\">\r\n"); buildxml.append(" <delete file=\"${basedir}/lib/${java2script.app.name}.jar\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/lib/${java2script.app.name}.jar\">\r\n"); buildxml.append(" <fileset dir=\"${bin.folder}\">\r\n"); buildxml.append(" <exclude name=\"WEB-INF/**\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.html\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.js\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.css\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.bmp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.gif\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.png\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jpeg\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swp\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.swo\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.jar\"/>\r\n"); buildxml.append(" <exclude name=\"**/*.war\"/>\r\n"); buildxml.append(" <exclude name=\".classpath\"/>\r\n"); buildxml.append(" <exclude name=\".project\"/>\r\n"); buildxml.append(" <exclude name=\".j2s\"/>\r\n"); buildxml.append(" <exclude name=\"web.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.xml\"/>\r\n"); buildxml.append(" <exclude name=\"build.properties\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"plugin.properties\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); starterURL = AjaxPlugin.getDefault().getBundle().getEntry(File.separator); root = "."; try { root = Platform.asLocalURL(starterURL).getFile(); } catch (IOException e1) { e1.printStackTrace(); } newPath = Path.fromPortableString(root); String ajaxPath = newPath.toOSString(); String key = "net.sf.j2s.ajax"; int idx = ajaxPath.lastIndexOf(key); if (idx != -1) { ajaxPath = ajaxPath.substring(0, idx) + "net.sf.j2s.lib" + ajaxPath.substring(idx + key.length()); } File libFile = new File(ajaxPath); String j2sRelativePath = FileUtil.toRelativePath(libFile.getAbsolutePath(), webinf.getAbsolutePath()); if (j2sRelativePath.length() > 0 && !j2sRelativePath.endsWith("/")) { j2sRelativePath += "/"; } int slashIndex = j2sRelativePath.lastIndexOf('/', j2sRelativePath.length() - 2); String pluginPath = j2sRelativePath.substring(0, slashIndex); String libPluginPath = j2sRelativePath.substring(slashIndex + 1, j2sRelativePath.length() - 1); buildxml.append(" <target name=\"pack.plugins.j2slib.war\">\r\n"); buildxml.append(" <delete file=\"${basedir}/../plugins.war\" quiet=\"true\"/>\r\n"); buildxml.append(" <zip destfile=\"${basedir}/../plugins.war\">\r\n"); buildxml.append(" <fileset dir=\"${basedir}/" + pluginPath + "/\">\r\n"); buildxml.append(" <include name=\"" + libPluginPath + "/**\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/library.jar\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/plugin.xml\"/>\r\n"); buildxml.append(" <exclude name=\"" + libPluginPath + "/META-INF/**\"/>\r\n"); buildxml.append(" </fileset>\r\n"); buildxml.append(" </zip>\r\n"); buildxml.append(" </target>\r\n"); buildxml.append("\r\n"); buildxml.append("</project>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "build.xml")); fos.write(buildxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } StringBuffer webxml = new StringBuffer(); webxml.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n"); webxml.append("<!DOCTYPE web-app\r\n"); webxml.append(" PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\r\n"); webxml.append(" \"http://java.sun.com/dtd/web-app_2_3.dtd\">\r\n"); webxml.append("<web-app>\r\n"); webxml.append(" <display-name>Java2Script</display-name>\r\n"); webxml.append(" <description>Java2Script application</description>\r\n"); webxml.append(genereateServlet("simplerpc", "net.sf.j2s.ajax.SimpleRPCHttpServlet")); webxml.append(genereateServlet("piperpc", "net.sf.j2s.ajax.CompoundPipeRPCHttpServlet")); webxml.append(" <servlet>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <servlet-class>net.sf.j2s.ajax.SimplePipeHttpServlet</servlet-class>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.query.timeout</param-name>\r\n"); webxml.append(" <param-value>20000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.script.breakout</param-name>\r\n"); webxml.append(" <param-value>1200000</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" <init-param>\r\n"); webxml.append(" <param-name>simple.pipe.max.items.per.query</param-name>\r\n"); webxml.append(" <param-value>60</param-value>\r\n"); webxml.append(" </init-param>\r\n"); webxml.append(" </servlet>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplerpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplerpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>piperpc</servlet-name>\r\n"); webxml.append(" <url-pattern>/piperpc</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append(" <servlet-mapping>\r\n"); webxml.append(" <servlet-name>simplepipe</servlet-name>\r\n"); webxml.append(" <url-pattern>/simplepipe</url-pattern>\r\n"); webxml.append(" </servlet-mapping>\r\n"); webxml.append("</web-app>\r\n"); try { FileOutputStream fos = new FileOutputStream(new File(webinf, "web.xml")); fos.write(webxml.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } } 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(); }
11
Code Sample 1: public static String hashMD5(String baseString) { MessageDigest digest = null; StringBuffer hexString = new StringBuffer(); try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(baseString.getBytes()); byte[] hash = digest.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Password.class.getName()).log(Level.SEVERE, null, ex); } return hexString.toString(); } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
11
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }