label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private void init() throws IOException { JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); try { do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (!ze.isDirectory()) { entries.add(ze.getName()); } } while (true); } finally { jis.close(); } } Code Sample 2: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: public boolean update(int idJugador, jugador jugadorModificado) { int intResult = 0; String sql = "UPDATE jugador " + "SET apellidoPaterno = ?, apellidoMaterno = ?, nombres = ?, fechaNacimiento = ?, " + " pais = ?, rating = ?, sexo = ? " + " WHERE idJugador = " + idJugador; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(jugadorModificado); 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: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
00
Code Sample 1: public CertificateID(String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull()); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert); digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new DEROctetString(digest.digest()); PublicKey issuerKey = issuerCert.getPublicKey(); ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest()); DERInteger serialNumber = new DERInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } } Code Sample 2: public FTPManager(URL location) throws IOException { this.client = new FTPClient(); String host = location.getHost(); int port = location.getPort(); if (port < 0) { this.client.connect(host); } else { this.client.connect(host, port); } String[] login = StringUtils.split(location.getUserInfo(), ':'); this.client.login(login[0], login.length > 1 ? login[1] : ""); if (!this.client.setFileType(FTP.BINARY_FILE_TYPE)) throw new IOException("Unable to set the transfert mode"); }
11
Code Sample 1: public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } } Code Sample 2: public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
11
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public void getFile(OutputStream output, Fragment fragment) throws Exception { Assert.Arg.notNull(output, "output"); Assert.Arg.notNull(fragment, "fragment"); Assert.Arg.notNull(fragment.getId(), "fragment.getId()"); if (this.delegate != null) { this.delegate.getFile(output, fragment); return; } ensureBaseDirectoryCreated(); File filePath = getFragmentFilePath(fragment); InputStream input = FileUtils.openInputStream(filePath); try { IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public File createFileFromClasspathResource(String resourceUrl) throws IOException { File fichierTest = File.createTempFile("xmlFieldTestFile", ""); FileOutputStream fos = new FileOutputStream(fichierTest); InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl); IOUtils.copy(is, fos); is.close(); fos.close(); return fichierTest; } Code Sample 2: public String login() { String authSuccess = "false"; try { String errorMesg = ""; int error; if ((error = utils.stringIsNull(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(passwd)) != -1) { errorMesg += rb.getString("passwdField") + ": " + utils.errors[error] + " "; } if ((error = utils.stringIsNull(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } else if ((error = utils.stringIsEmpty(login)) != -1) { errorMesg += rb.getString("loginField") + ": " + utils.errors[error] + " "; } String[] admins = conf.getProperty("admin").split("\\s"); boolean admin = false; for (int i = 0; i < admins.length; i++) { if (admins[i].equals(login)) { admin = true; } } if (!admin) { errorMesg += rb.getString("noAdmin"); session.invalidate(); } else { session.setAttribute("conf", conf); } if (errorMesg.length() > 0) { status = errorMesg; System.out.println(status); FacesContext context = FacesContext.getCurrentInstance(); context.renderResponse(); } else { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(passwd.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xFF & result[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } authSuccess = (sqlManager.getPassword(login).equals(hexString.toString())) ? "true" : "false"; if (authSuccess.equals("false")) session.invalidate(); } } catch (NoSuchAlgorithmException nsae) { utils.catchExp(nsae); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } catch (SQLException sqle) { utils.catchExp(sqle); status = utils.getStatus(); if (stacktrace) { stackTrace = utils.getStackTrace(); } FacesContext.getCurrentInstance().renderResponse(); } return authSuccess; }
11
Code Sample 1: public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); } Code Sample 2: private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: private FTPClient getFtpClient(Entry parentEntry) throws Exception { Object[] values = parentEntry.getValues(); if (values == null) { return null; } String server = (String) values[COL_SERVER]; String baseDir = (String) values[COL_BASEDIR]; String user = (String) values[COL_USER]; String password = (String) values[COL_PASSWORD]; if (password != null) { password = getRepository().getPageHandler().processTemplate(password, false); } else { password = ""; } FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server); if (user != null) { ftpClient.login(user, password); } int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return null; } ftpClient.setFileType(FTP.IMAGE_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return ftpClient; } catch (Exception exc) { System.err.println("Could not connect to ftp server:" + exc); return null; } } Code Sample 2: public static String loadUrlContentAsString(URL url) throws IOException { char[] buf = new char[2048]; StringBuffer ret = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) { ret.append(buf, 0, chars); } reader.close(); return ret.toString(); }
00
Code Sample 1: private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } } Code Sample 2: @Override public boolean saveCart(Carrito cart, boolean completado, String date, String formPago) { Connection conexion = null; PreparedStatement insertHistorial = null; PreparedStatement insertCarrito = null; boolean exito = false; try { conexion = pool.getConnection(); conexion.setAutoCommit(false); insertHistorial = conexion.prepareStatement("INSERT INTO " + nameBD + ".HistorialCarritos VALUES (?,?,?,?,?,?)"); insertHistorial.setString(1, cart.getUser()); insertHistorial.setString(2, cart.getCodigo()); insertHistorial.setString(3, date); insertHistorial.setDouble(4, cart.getPrecio()); insertHistorial.setString(5, formPago); insertHistorial.setBoolean(6, completado); int filasAfectadas = insertHistorial.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); } else { insertCarrito = conexion.prepareStatement("INSERT INTO " + nameBD + ".Carritos VALUES (?,?,?,?,?)"); Iterator<String> iteradorProductos = cart.getArticulos().keySet().iterator(); while (iteradorProductos.hasNext()) { String key = iteradorProductos.next(); Producto prod = getProduct(key); int cantidad = cart.getArticulos().get(key); insertCarrito.setString(1, cart.getCodigo()); insertCarrito.setString(2, prod.getCodigo()); insertCarrito.setString(3, prod.getNombre()); insertCarrito.setDouble(4, prod.getPrecio()); insertCarrito.setInt(5, cantidad); filasAfectadas = insertCarrito.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); break; } insertCarrito.clearParameters(); } conexion.commit(); exito = true; } } catch (SQLException ex) { logger.log(Level.SEVERE, "Error aรฑadiendo carrito al registro", ex); try { conexion.rollback(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Error haciendo rollback de la transacciรณn para insertar carrito en el registro", ex1); } } finally { cerrarConexionYStatement(conexion, insertCarrito, insertHistorial); } return exito; }
00
Code Sample 1: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: 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!"); } 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; }
00
Code Sample 1: void acessResource(ClassLoader cl, String resource) throws IOException { URL url = cl.getResource(resource); if (url == null) { println("Ups can't find resource " + resource); } else { println("URL OK " + resource + " ->" + url); InputStream is = url.openStream(); try { is.read(); } finally { is.close(); } println("Read OK " + resource + " ->" + url); } } Code Sample 2: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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(); } Code Sample 2: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
11
Code Sample 1: public static boolean filecopy(final File source, final File target) { boolean out = false; if (source.isDirectory() || !source.exists() || target.isDirectory() || source.equals(target)) return false; try { target.getParentFile().mkdirs(); target.createNewFile(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); try { FileChannel targetChannel = new FileOutputStream(target).getChannel(); try { targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); out = true; } finally { targetChannel.close(); } } finally { sourceChannel.close(); } } catch (IOException e) { out = false; } return out; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); } Code Sample 2: private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } }
00
Code Sample 1: protected static DynamicJasperDesign generateJasperDesign(DynamicReport dr) throws CoreException { DynamicJasperDesign jd = null; try { if (dr.getTemplateFileName() != null) { log.info("loading template file: " + dr.getTemplateFileName()); log.info("Attemping to find the file directly in the file system..."); File file = new File(dr.getTemplateFileName()); if (file.exists()) { JasperDesign jdesign = JRXmlLoader.load(file); jd = DJJRDesignHelper.downCast(jdesign, dr); } else { log.info("Not found: Attemping to find the file in the classpath..."); URL url = DynamicJasperHelper.class.getClassLoader().getResource(dr.getTemplateFileName()); JasperDesign jdesign = JRXmlLoader.load(url.openStream()); jd = DJJRDesignHelper.downCast(jdesign, dr); } JasperDesignHelper.populateReportOptionsFromDesign(jd, dr); } else { jd = DJJRDesignHelper.getNewDesign(dr); } registerParameters(jd, dr); } catch (JRException e) { throw new CoreException(e.getMessage(), e); } catch (IOException e) { throw new CoreException(e.getMessage(), e); } return jd; } Code Sample 2: public static String getMD5(final String data) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(data.getBytes()); BigInteger bigInt = new BigInteger(1, m.digest()); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return e.getMessage(); } }
11
Code Sample 1: private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); } Code Sample 2: public static String encrypt(String password) throws NoSuchAlgorithmException { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] cr = d.digest(); return getString(cr).toLowerCase(); }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { Logger.error(FileUtil.class, ioe.getMessage(), ioe); } } Code Sample 2: private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
00
Code Sample 1: public String getNextSequence(Integer id) throws ApplicationException { java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noRecordMatch = false; String prefix = ""; String suffix = ""; Long startID = null; Integer length = null; Long currID = null; Integer increment = null; int nextID; String formReferenceID = null; synchronized (lock) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT PREFIX,SUFFIX,START_NO,LENGTH,CURRENT_NO,INCREMENT FROM FORM_RECORD WHERE ID=?"); setPrepareStatement(preStat, 1, id); rs = preStat.executeQuery(); if (rs.next()) { prefix = rs.getString(1); suffix = rs.getString(2); startID = new Long(rs.getLong(3)); length = new Integer(rs.getInt(4)); currID = new Long(rs.getLong(5)); increment = new Integer(rs.getInt(6)); if (Utility.isEmpty(startID) || Utility.isEmpty(length) || Utility.isEmpty(currID) || Utility.isEmpty(increment) || startID.intValue() < 0 || length.intValue() < startID.toString().length() || currID.intValue() < startID.intValue() || increment.intValue() < 1 || new Integer(increment.intValue() + currID.intValue()).toString().length() > length.intValue()) { noRecordMatch = true; } else { if (!Utility.isEmpty(prefix)) { formReferenceID = prefix; } String strCurrID = currID.toString(); for (int i = 0; i < length.intValue() - strCurrID.length(); i++) { formReferenceID += "0"; } formReferenceID += strCurrID; if (!Utility.isEmpty(suffix)) { formReferenceID += suffix; } } } else { noRecordMatch = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (!noRecordMatch && formReferenceID != null) { try { int updateCnt = 0; nextID = currID.intValue() + increment.intValue(); do { preStat = dbConn.prepareStatement("UPDATE FORM_RECORD SET CURRENT_NO=? WHERE ID=?"); setPrepareStatement(preStat, 1, new Integer(nextID)); setPrepareStatement(preStat, 2, id); updateCnt = preStat.executeUpdate(); if (updateCnt == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } return formReferenceID; } } } Code Sample 2: public void readDocument(URL url) { stopTiming(); try { String xmlData = ""; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; boolean cont = true; while (cont) { line = in.readLine(); if (line == null) { break; } line = line.trim(); if (line.length() > 0 && line.charAt(0) != '%') { xmlData = xmlData + line + System.getProperty("line.separator"); } if (line.length() > 1 && line.charAt(0) == '%' && line.charAt(1) == '=') { cont = false; } } XmlDataAdaptor readAdp = null; readAdp = XmlDataAdaptor.adaptorForString(xmlData, false); if (readAdp != null) { XmlDataAdaptor mpsfileData_Adaptor = readAdp.childAdaptor(dataRootName); if (mpsfileData_Adaptor != null) { setTitle(mpsfileData_Adaptor.stringValue("title")); java.util.Iterator<XmlDataAdaptor> plotIt = mpsfileData_Adaptor.childAdaptorIterator("Plot"); while (plotIt.hasNext()) { XmlDataAdaptor pvDA = plotIt.next(); String name = pvDA.stringValue("name"); String xMin = pvDA.stringValue("xmin"); String xMax = pvDA.stringValue("xmax"); String step = pvDA.stringValue("step"); System.out.println(name + " " + xMax + " " + xMin + " " + step); bModel.setPlotAxes(name, xMin, xMax, step); } java.util.Iterator<XmlDataAdaptor> timingIt = mpsfileData_Adaptor.childAdaptorIterator("TimingPV"); while (timingIt.hasNext()) { XmlDataAdaptor pvDA = timingIt.next(); String name = pvDA.stringValue("name"); bModel.setTimingPVName(name); } java.util.Iterator<XmlDataAdaptor> trigIt = mpsfileData_Adaptor.childAdaptorIterator("Trigger"); while (trigIt.hasNext()) { XmlDataAdaptor pvDA = trigIt.next(); String name = pvDA.stringValue("name"); String type = pvDA.stringValue("type"); bModel.addTrigger(name, type); } java.util.Iterator<XmlDataAdaptor> blmIt = mpsfileData_Adaptor.childAdaptorIterator("BLMdevice"); while (blmIt.hasNext()) { XmlDataAdaptor pvDA = blmIt.next(); String name = pvDA.stringValue("name"); String section = pvDA.stringValue("section"); String mpschan = pvDA.stringValue("mpschan"); String devType = pvDA.stringValue("devicetype"); String location = pvDA.stringValue("locationz"); double locz = 0; try { locz = Double.parseDouble(location); } catch (NumberFormatException e) { locz = 0.0; } if (devType == null) bModel.addBLM(new IonizationChamber(name, section, mpschan, locz)); else if (devType.equals("ND")) bModel.addBLM(new NeutronDetector(name, section, mpschan, locz)); else if (devType.equals("IC")) bModel.addBLM(new IonizationChamber(name, section, mpschan, locz)); } } } in.close(); } catch (IOException exception) { System.out.println("Fatal error. Something wrong with input file. Stop."); } startTiming(); }
11
Code Sample 1: public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; } Code Sample 2: public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: public void testDelegateUsage() throws IOException { MockControl elementParserControl = MockControl.createControl(ElementParser.class); ElementParser elementParser = (ElementParser) elementParserControl.getMock(); elementParserControl.replay(); URL url = getClass().getResource("/net/sf/ngrease/core/ast/simple-element.ngr"); ElementSource source = new ElementSourceUrlImpl(url, elementParser); elementParserControl.verify(); elementParserControl.reset(); Element element = new ElementDefaultImpl(""); elementParser.parse(url.openStream()); elementParserControl.setMatcher(new ArgumentsMatcher() { public boolean matches(Object[] arg0, Object[] arg1) { if (!arg0[0].getClass().equals(arg1[0].getClass())) { return false; } return true; } public String toString(Object[] arg0) { return Arrays.asList(arg0).toString(); } }); elementParserControl.setReturnValue(element, 1); elementParserControl.replay(); Element elementAgain = source.getElement(); elementParserControl.verify(); assertTrue(element == elementAgain); } Code Sample 2: public static void addClasses(final Checker checker, final ArrayList<Class<?>> list, final String packageName, final int levels, final URL url) { final File directory = new File(url.getFile()); if (directory.exists()) addClasses(checker, list, packageName, levels, directory); else try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); addClasses(checker, list, levels, conn, packageName.replace('.', '/')); } catch (final IOException ioex) { System.err.println(ioex); } }
00
Code Sample 1: public static void loginWuploader() throws IOException { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to Wupload"); HttpPost httppost = new HttpPost("http://www.wupload.in/account/login"); httppost.setHeader("Referer", "http://www.wupload.in/"); httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("email", uname)); formparams.add(new BasicNameValuePair("password", pwd)); formparams.add(new BasicNameValuePair("redirect", "/")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("PHPSESSID")) { sessioncookie = "PHPSESSID=" + escookie.getValue(); System.out.println(sessioncookie); } if (escookie.getName().equalsIgnoreCase("email")) { mailcookie = "email=" + escookie.getValue(); login = true; System.out.println(mailcookie); } if (escookie.getName().equalsIgnoreCase("nickname")) { namecookie = "nickname=" + escookie.getValue(); System.out.println(namecookie); } if (escookie.getName().equalsIgnoreCase("isAffiliate")) { affiliatecookie = "isAffiliate=" + escookie.getValue(); System.out.println(affiliatecookie); } if (escookie.getName().equalsIgnoreCase("role")) { rolecookie = "role=" + escookie.getValue(); System.out.println(rolecookie); } } if (login) { System.out.println("Login Success"); getFolderCookies(); } else { System.out.println("Login failed"); } } Code Sample 2: 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()); }
00
Code Sample 1: @Override protected void removeOrphansElements() throws DatabaseException { this.getIdChache().clear(); final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); PreparedStatement preparedStatement; preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallElementsSchemaAndTableName() + " FROM " + this.getCallElementsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallElementsSchemaAndTableName() + ".element_id = " + this.getCallInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallExceptionsSchemaAndTableName() + " FROM " + this.getCallExceptionsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallExceptionsSchemaAndTableName() + ".exception_id = " + this.getCallInvocationsSchemaAndTableName() + ".exception_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getCallPrincipalsSchemaAndTableName() + " FROM " + this.getCallPrincipalsSchemaAndTableName() + " LEFT JOIN " + this.getCallInvocationsSchemaAndTableName() + " ON " + this.getCallPrincipalsSchemaAndTableName() + ".principal_id = " + this.getCallInvocationsSchemaAndTableName() + ".principal_id WHERE " + this.getCallInvocationsSchemaAndTableName() + ".principal_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getHttpSessionElementsSchemaAndTableName() + " FROM " + this.getHttpSessionElementsSchemaAndTableName() + " LEFT JOIN " + this.getHttpSessionInvocationsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getJvmElementsSchemaAndTableName() + " FROM " + this.getJvmElementsSchemaAndTableName() + " LEFT JOIN " + this.getJvmInvocationsSchemaAndTableName() + " ON " + this.getJvmElementsSchemaAndTableName() + ".element_id = " + this.getJvmInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getJvmInvocationsSchemaAndTableName() + ".element_id IS NULL"); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getPersistenceEntityElementsSchemaAndTableName() + " FROM " + this.getPersistenceEntityElementsSchemaAndTableName() + " LEFT JOIN " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " ON " + this.getPersistenceEntityElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id WHERE " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getPersistenceQueryElementsSchemaAndTableName() + " FROM " + this.getPersistenceQueryElementsSchemaAndTableName() + " LEFT JOIN " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " ON " + this.getPersistenceQueryElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id WHERE " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); preparedStatement = DebugPreparedStatement.prepareStatement(connection, "DELETE " + this.getHardDiskElementsSchemaAndTableName() + " FROM " + this.getHardDiskElementsSchemaAndTableName() + " LEFT JOIN " + this.getHardDiskInvocationsSchemaAndTableName() + " ON " + this.getHardDiskElementsSchemaAndTableName() + ".element_id = " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id WHERE " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id IS NULL "); preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error cleaning database.", e); } finally { this.releaseConnection(connection); } return; } Code Sample 2: public void readMESHDescriptorFileIntoFiles(String outfiledir) { String inputLine, ins; String filename = getMESHdescriptorfilename(); String uid = ""; String name = ""; String description = ""; String element_of = ""; Vector treenr = new Vector(); Vector related = new Vector(); Vector synonyms = new Vector(); Vector actions = new Vector(); Vector chemicals = new Vector(); Vector allCASchemicals = new Vector(); Set CAS = new TreeSet(); Map treenr2uid = new TreeMap(); Map uid2name = new TreeMap(); String cut1, cut2; try { BufferedReader in = new BufferedReader(new FileReader(filename)); String outfile = outfiledir + "\\mesh"; BufferedWriter out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); BufferedWriter out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_relation = new BufferedWriter(new FileWriter(outfile + "_relation.txt")); BufferedWriter cas_mapping = new BufferedWriter(new FileWriter(outfile + "to_cas_mapping.txt")); BufferedWriter ec_mapping = new BufferedWriter(new FileWriter(outfile + "to_ec_mapping.txt")); Connection db = tools.openDB("kb"); String query = "SELECT hierarchy_complete,uid FROM mesh_tree, mesh_graph_uid_name WHERE term=name"; ResultSet rs = tools.executeQuery(db, query); while (rs.next()) { String db_treenr = rs.getString("hierarchy_complete"); String db_uid = rs.getString("uid"); treenr2uid.put(db_treenr, db_uid); } db.close(); System.out.println("Reading in the DUIDs ..."); BufferedReader in_for_mapping = new BufferedReader(new FileReader(filename)); inputLine = getNextLine(in_for_mapping); boolean leave = false; while ((in_for_mapping != null) && (inputLine != null)) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { inputLine = getNextLine(in_for_mapping); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String mesh_uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (mesh_uid.compareTo("D041441") == 0) leave = true; inputLine = getNextLine(in_for_mapping); inputLine = getNextLine(in_for_mapping); cut1 = "<String>"; cut2 = "</String>"; String mesh_name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); uid2name.put(mesh_uid, mesh_name); } inputLine = getNextLine(in_for_mapping); } in_for_mapping.close(); BufferedReader in_ec_numbers = new BufferedReader(new FileReader("e:\\projects\\ondex\\ec_concept_acc.txt")); Set ec_numbers = new TreeSet(); String ec_line = in_ec_numbers.readLine(); while (in_ec_numbers.ready()) { StringTokenizer st = new StringTokenizer(ec_line); st.nextToken(); ec_numbers.add(st.nextToken()); ec_line = in_ec_numbers.readLine(); } in_ec_numbers.close(); tools.printDate(); inputLine = getNextLine(in); while (inputLine != null) { if (inputLine.startsWith("<DescriptorRecord DescriptorClass")) { treenr.clear(); related.clear(); synonyms.clear(); actions.clear(); chemicals.clear(); boolean id_ready = false; boolean line_read = false; while ((inputLine != null) && (!inputLine.startsWith("</DescriptorRecord>"))) { line_read = false; if ((inputLine.startsWith("<DescriptorUI>")) && (!id_ready)) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; uid = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; name = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); id_ready = true; } if (inputLine.compareTo("<SeeRelatedList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</SeeRelatedList>") == -1)) { if (inputLine.startsWith("<DescriptorUI>")) { cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); related.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.compareTo("<TreeNumberList>") == 0) { while ((inputLine != null) && (inputLine.indexOf("</TreeNumberList>") == -1)) { if (inputLine.startsWith("<TreeNumber>")) { cut1 = "<TreeNumber>"; cut2 = "</TreeNumber>"; String id = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); treenr.add(id); } inputLine = getNextLine(in); line_read = true; } } if (inputLine.startsWith("<Concept PreferredConceptYN")) { boolean prefConcept = false; if (inputLine.compareTo("<Concept PreferredConceptYN=\"Y\">") == 0) prefConcept = true; while ((inputLine != null) && (inputLine.indexOf("</Concept>") == -1)) { if (inputLine.startsWith("<CASN1Name>") && prefConcept) { cut1 = "<CASN1Name>"; cut2 = "</CASN1Name>"; String casn1 = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); String chem_name = casn1; String chem_description = ""; if (casn1.length() > chem_name.length() + 2) chem_description = casn1.substring(chem_name.length() + 2, casn1.length()); String reg_number = ""; inputLine = getNextLine(in); if (inputLine.startsWith("<RegistryNumber>")) { cut1 = "<RegistryNumber>"; cut2 = "</RegistryNumber>"; reg_number = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); } Vector chemical = new Vector(); String type = ""; if (reg_number.startsWith("EC")) { type = "EC"; reg_number = reg_number.substring(3, reg_number.length()); } else { type = "CAS"; } chemical.add(type); chemical.add(reg_number); chemical.add(chem_name); chemical.add(chem_description); chemicals.add(chemical); if (type.compareTo("CAS") == 0) { if (!CAS.contains(reg_number)) { CAS.add(reg_number); allCASchemicals.add(chemical); } } } if (inputLine.startsWith("<ScopeNote>") && prefConcept) { cut1 = "<ScopeNote>"; description = inputLine.substring(cut1.length(), inputLine.length()); } if (inputLine.startsWith("<TermUI>")) { inputLine = getNextLine(in); cut1 = "<String>"; cut2 = "</String>"; String syn = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); if (syn.indexOf("&amp;") != -1) { String syn1 = syn.substring(0, syn.indexOf("&amp;")); String syn2 = syn.substring(syn.indexOf("amp;") + 4, syn.length()); syn = syn1 + " & " + syn2; } if (name.compareTo(syn) != 0) synonyms.add(syn); } if (inputLine.startsWith("<PharmacologicalAction>")) { inputLine = getNextLine(in); inputLine = getNextLine(in); cut1 = "<DescriptorUI>"; cut2 = "</DescriptorUI>"; String act_ui = inputLine.substring(cut1.length(), inputLine.indexOf(cut2)); actions.add(act_ui); } inputLine = getNextLine(in); line_read = true; } } if (!line_read) inputLine = getNextLine(in); } String pos_tag = ""; element_of = "MESHD"; String is_primary = "0"; out_concept.write(uid + "\t" + pos_tag + "\t" + description + "\t" + element_of + "\t"); out_concept.write(is_primary + "\n"); String name_stemmed = ""; String name_tagged = ""; element_of = "MESHD"; String is_unique = "0"; int is_preferred = 1; String original_name = name; String is_not_substring = "0"; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); is_preferred = 0; for (int i = 0; i < synonyms.size(); i++) { name = (String) synonyms.get(i); original_name = name; out_concept_name.write(uid + "\t" + name + "\t" + name_stemmed + "\t"); out_concept_name.write(name_tagged + "\t" + element_of + "\t"); out_concept_name.write(is_unique + "\t" + is_preferred + "\t"); out_concept_name.write(original_name + "\t" + is_not_substring + "\n"); } String rel_type = "is_r"; element_of = "MESHD"; String from_name = name; for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } rel_type = "is_a"; element_of = "MESHD"; related.clear(); for (int i = 0; i < treenr.size(); i++) { String tnr = (String) treenr.get(i); if (tnr.length() > 3) tnr = tnr.substring(0, tnr.lastIndexOf(".")); String rel_uid = (String) treenr2uid.get(tnr); if (rel_uid != null) related.add(rel_uid); else System.out.println(uid + ": No DUI found for " + tnr); } for (int i = 0; i < related.size(); i++) { String to_uid = (String) related.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } if (related.size() == 0) System.out.println(uid + ": No is_a relations"); rel_type = "act"; element_of = "MESHD"; for (int i = 0; i < actions.size(); i++) { String to_uid = (String) actions.get(i); String to_name = (String) uid2name.get(to_uid); out_relation.write(uid + "\t" + to_uid + "\t"); out_relation.write(rel_type + "\t" + element_of + "\t"); out_relation.write(from_name + "\t" + to_name + "\n"); } String method = "IMPM"; String score = "1.0"; for (int i = 0; i < chemicals.size(); i++) { Vector chemical = (Vector) chemicals.get(i); String type = (String) chemical.get(0); String chem = (String) chemical.get(1); if (!ec_numbers.contains(chem) && (type.compareTo("EC") == 0)) { if (chem.compareTo("1.14.-") == 0) chem = "1.14.-.-"; else System.out.println("MISSING EC: " + chem); } String id = type + ":" + chem; String entry = uid + "\t" + id + "\t" + method + "\t" + score + "\n"; if (type.compareTo("CAS") == 0) cas_mapping.write(entry); else ec_mapping.write(entry); } } else inputLine = getNextLine(in); } System.out.println("End import descriptors"); tools.printDate(); in.close(); out_concept.close(); out_concept_name.close(); out_relation.close(); cas_mapping.close(); ec_mapping.close(); outfile = outfiledir + "\\cas"; out_concept = new BufferedWriter(new FileWriter(outfile + "_concept.txt")); out_concept_name = new BufferedWriter(new FileWriter(outfile + "_concept_name.txt")); BufferedWriter out_concept_acc = new BufferedWriter(new FileWriter(outfile + "_concept_acc.txt")); for (int i = 0; i < allCASchemicals.size(); i++) { Vector chemical = (Vector) allCASchemicals.get(i); String cas_id = "CAS:" + (String) chemical.get(1); String cas_name = (String) chemical.get(2); String cas_pos_tag = ""; String cas_description = (String) chemical.get(3); String cas_element_of = "CAS"; String cas_is_primary = "0"; out_concept.write(cas_id + "\t" + cas_pos_tag + "\t" + cas_description + "\t"); out_concept.write(cas_element_of + "\t" + cas_is_primary + "\n"); String cas_name_stemmed = ""; String cas_name_tagged = ""; String cas_is_unique = "0"; String cas_is_preferred = "0"; String cas_original_name = cas_name; String cas_is_not_substring = "0"; out_concept_name.write(cas_id + "\t" + cas_name + "\t" + cas_name_stemmed + "\t"); out_concept_name.write(cas_name_tagged + "\t" + cas_element_of + "\t"); out_concept_name.write(cas_is_unique + "\t" + cas_is_preferred + "\t"); out_concept_name.write(cas_original_name + "\t" + cas_is_not_substring + "\n"); out_concept_acc.write(cas_id + "\t" + (String) chemical.get(1) + "\t"); out_concept_acc.write(cas_element_of + "\n"); } out_concept.close(); out_concept_name.close(); out_concept_acc.close(); } catch (Exception e) { settings.writeLog("Error while reading MESH descriptor file: " + e.getMessage()); } }
11
Code Sample 1: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); }
11
Code Sample 1: public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); } Code Sample 2: @Test public void testWriteAndReadFirstLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile file = new RFile(directory1, "testreadwrite1st.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
11
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: public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } } Code Sample 2: public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; }
00
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: @Test public void testEmptyValue() throws Exception { System.out.println("Test Empty Value..."); EProperties props = new EProperties(); URL url = this.getClass().getResource("emptyval.properties"); System.out.println("Properties URL " + url); System.out.println("****************** LOADING URL *************************"); props.load(url); System.out.println("---list---"); System.out.println(props.list()); System.out.println("---list---"); System.out.println("****************** LOADING Reader *************************"); EProperties p2 = new EProperties(); p2.load(new InputStreamReader(url.openStream())); System.out.println("---list---"); System.out.println(p2.list()); System.out.println("---list---"); }
11
Code Sample 1: public static String getUserToken(String userName) { if (userName != null && userName.trim().length() > 0) try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update((userName + seed).getBytes("ISO-8859-1")); return BaseController.bytesToHex(md.digest()); } catch (NullPointerException npe) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; } Code Sample 2: public boolean validatePassword(UserType nameMatch, String password) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(nameMatch.getSalt().getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); return encodedString.equals(nameMatch.getPassword()); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); logger.fatal("Shutting down..."); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); assert false : "This should never happen"; return false; } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(ex.getMessage()); logger.fatal(errorMessage); GlobalUITools.displayFatalExceptionMessage(null, "Could not use algorithm " + HASH_ALGORITHM, ex, true); assert false : "This could should never be reached"; return false; } }
11
Code Sample 1: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: @Test public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
11
Code Sample 1: private void copyFile(File f) throws IOException { File newFile = new File(destdir + "/" + f.getName()); newFile.createNewFile(); FileInputStream fin = new FileInputStream(f); FileOutputStream fout = new FileOutputStream(newFile); int c; while ((c = fin.read()) != -1) fout.write(c); fin.close(); fout.close(); } Code Sample 2: public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; }
11
Code Sample 1: private static boolean moveFiles(String sourceDir, String targetDir) { boolean isFinished = false; boolean fileMoved = false; File stagingDir = new File(sourceDir); if (!stagingDir.exists()) { System.out.println(getTimeStamp() + "ERROR - source directory does not exist."); return true; } if (stagingDir.listFiles() == null) { System.out.println(getTimeStamp() + "ERROR - Empty file list. Possible permission error on source directory " + sourceDir); return true; } File[] fileList = stagingDir.listFiles(); for (int x = 0; x < fileList.length; x++) { File f = fileList[x]; if (f.getName().startsWith(".")) { continue; } String targetFileName = targetDir + File.separator + f.getName(); String operation = "move"; boolean success = f.renameTo(new File(targetFileName)); if (success) { fileMoved = true; } else { operation = "mv"; try { Process process = Runtime.getRuntime().exec(new String[] { "mv", f.getCanonicalPath(), targetFileName }); process.waitFor(); process.destroy(); if (!new File(targetFileName).exists()) { success = false; } else { success = true; fileMoved = true; } } catch (Exception e) { success = false; } if (!success) { operation = "copy"; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(f).getChannel(); File outFile = new File(targetFileName); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); in = null; out.close(); out = null; f.delete(); success = true; } catch (Exception e) { success = false; } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } if (out != null) { try { out.close(); } catch (Exception e) { } } } } } if (success) { System.out.println(getTimeStamp() + operation + " " + f.getAbsolutePath() + " to " + targetDir); fileMoved = true; } else { System.out.println(getTimeStamp() + "ERROR - " + operation + " " + f.getName() + " to " + targetFileName + " failed."); isFinished = true; } } if (fileMoved && !isFinished) { try { currentLastActivity = System.currentTimeMillis(); updateLastActivity(currentLastActivity); } catch (NumberFormatException e) { System.out.println(getTimeStamp() + "ERROR: NumberFormatException when trying to update lastActivity."); isFinished = true; } catch (IOException e) { System.out.println(getTimeStamp() + "ERROR: IOException when trying to update lastActivity. " + e.toString()); isFinished = true; } } return isFinished; } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
11
Code Sample 1: public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public static String hash(String plainTextPwd) { MessageDigest hashAlgo; try { hashAlgo = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new QwickException(e); } hashAlgo.update(plainTextPwd.getBytes()); return new String(hashAlgo.digest()); }
00
Code Sample 1: private void getXMLData() { String result = null; URL url = null; URLConnection conn = null; BufferedReader rd = null; StringBuffer sb = new StringBuffer(); String line; try { url = new URL(this.url); conn = url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (MalformedURLException e) { log.error("URL was malformed: {}", url, e); } catch (IOException e) { log.error("IOException thrown: {}", url, e); } this.xmlString = result; } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static String appletLoad(String file, Output OUT) { if (!urlpath.endsWith("/")) { urlpath += '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = ""; if (file.equals("languages.txt")) { url = urlpath + file; } else { url = urlpath + "users/" + file; } try { StringBuffer sb = new StringBuffer(2000); BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String a; while ((a = br.readLine()) != null) { sb.append(a).append('\n'); } return sb.toString(); } catch (Exception e) { OUT.println("load failed for file->" + file); } return ""; }
11
Code Sample 1: public static void copyFile(File src, String srcEncoding, File dest, String destEncoding) throws IOException { InputStreamReader in = new InputStreamReader(new FileInputStream(src), srcEncoding); OutputStreamWriter out = new OutputStreamWriter(new RobustFileOutputStream(dest), destEncoding); int c; while ((c = in.read()) != -1) out.write(c); out.flush(); in.close(); out.close(); } Code Sample 2: public static void copyTo(File src, File dest) throws IOException { if (src.equals(dest)) throw new IOException("copyTo src==dest file"); FileOutputStream fout = new FileOutputStream(dest); InputStream in = new FileInputStream(src); IOUtils.copyTo(in, fout); fout.flush(); fout.close(); in.close(); }
00
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 String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
00
Code Sample 1: public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); 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])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; } Code Sample 2: public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } }
00
Code Sample 1: private void buildCache() { cache = new HashMap<String, byte[]>(); JarInputStream jis = null; BufferedInputStream bis = null; URL[] urls = getURLs(); for (URL url : urls) { try { if (url.getPath().endsWith(".jar")) { jis = new JarInputStream(url.openStream()); bis = new BufferedInputStream(jis); JarEntry jarEntry = null; while ((jarEntry = jis.getNextJarEntry()) != null) { String name = jarEntry.getName(); if (!jarEntry.isDirectory() && name.toLowerCase().endsWith(".class")) { String className = name.replaceAll("/", ".").substring(0, name.length() - 6); if (isClassLoaderConditonVerified(className)) { ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); int i = -1; while ((i = bis.read()) != -1) { bos.write(i); } bos.flush(); cache.put(className, baos.toByteArray()); } finally { if (baos != null) { try { baos.close(); } catch (IOException ignore) { } } if (bos != null) { try { bos.close(); } catch (IOException ex) { } } } jis.closeEntry(); } } } try { jis.close(); } catch (IOException ignore) { } } else { File file = new File(url.getFile()); buildCacheFromFile(file, null); } } catch (IOException ex) { continue; } } } Code Sample 2: public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } }
00
Code Sample 1: public static String hash(String plainText) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(plainText.getBytes(), 0, plainText.length()); String hash = new BigInteger(1, m.digest()).toString(16); if (hash.length() == 31) { hash = "0" + hash; } return hash; } Code Sample 2: private void newGame() { List scenarios = getScenarioChoices(); ScenarioChoice scenarioChoice = (ScenarioChoice) JOptionPane.showInputDialog(this, "Choose a Scenario", "Choose a Scenario", JOptionPane.PLAIN_MESSAGE, null, scenarios.toArray(), scenarios.get(0)); if (scenarioChoice == null) { return; } Object obj; try { obj = scamsoft.util.Toolkit.loadClass(scenarioChoice.className, null); } catch (ClassNotFoundException e) { handleNetworkException(e); return; } catch (InstantiationException e) { handleNetworkException(e); return; } catch (InvocationTargetException e) { handleNetworkException(e); return; } catch (IllegalArgumentException e) { handleNetworkException(e); return; } catch (IllegalAccessException e) { handleNetworkException(e); return; } if (obj == null || !(obj instanceof Scenario)) { return; } Scenario scenario = (Scenario) obj; String[] variations = scenario.getVariations(); int chosenvariation = 0; if (variations.length > 1) { String[] variationsChoice = new String[variations.length + 1]; System.arraycopy(variations, 0, variationsChoice, 0, variations.length); variationsChoice[variationsChoice.length - 1] = "Cancel"; chosenvariation = JOptionPane.showOptionDialog(this, "Choose a Variation", "Choose Variation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, variationsChoice, variationsChoice[0]); if (chosenvariation == JOptionPane.CLOSED_OPTION || chosenvariation == variationsChoice.length - 1) { return; } } String path = scenarioChoice.filePrefix + chosenvariation + ".sav"; URL url = this.getClass().getClassLoader().getResource(path); try { loadGame(url.openStream()); } catch (IOException e) { handleNetworkException(e); } }
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 boolean connect() { try { int reply; ftp.connect(server, port); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(username, password)) { ftp.enterLocalPassiveMode(); return true; } } else { ftp.disconnect(); System.out.println("FTP server refused connection."); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } System.out.println("Could not connect to server."); } return false; }
00
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: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: protected void shutdown(final boolean unexpected) { ControlerState oldState = this.state; this.state = ControlerState.Shutdown; if (oldState == ControlerState.Running) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } this.controlerListenerManager.fireControlerShutdownEvent(unexpected); if (this.dumpDataAtEnd) { Knowledges kk; if (this.config.scenario().isUseKnowledges()) { kk = (this.getScenario()).getKnowledges(); } else { kk = this.getScenario().retrieveNotEnabledKnowledges(); } new PopulationWriter(this.population, this.network, kk).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); ActivityFacilities facilities = this.getFacilities(); if (facilities != null) { new FacilitiesWriter((ActivityFacilitiesImpl) facilities).write(this.controlerIO.getOutputFilename("output_facilities.xml.gz")); } if (((NetworkFactoryImpl) this.network.getFactory()).isTimeVariant()) { new NetworkChangeEventsWriter().write(this.controlerIO.getOutputFilename("output_change_events.xml.gz"), ((NetworkImpl) this.network).getNetworkChangeEvents()); } if (this.config.scenario().isUseHouseholds()) { new HouseholdsWriterV10(this.scenarioData.getHouseholds()).writeFile(this.controlerIO.getOutputFilename(FILENAME_HOUSEHOLDS)); } if (this.config.scenario().isUseLanes()) { new LaneDefinitionsWriter20(this.scenarioData.getScenarioElement(LaneDefinitions20.class)).write(this.controlerIO.getOutputFilename(FILENAME_LANES)); } if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } } Code Sample 2: private String doOAIQuery(String request) throws IOException, ProtocolException { DannoClient ac = getClient(); HttpGet get = new HttpGet(request); get.setHeader("Accept", "application/xml"); HttpResponse response = ac.execute(get); if (!ac.isOK()) { throw new DannoRequestFailureException("GET", response); } return massage(new BasicResponseHandler().handleResponse(response)); }
00
Code Sample 1: public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } } Code Sample 2: private String getAuthUrlString(String account, String password) throws IOException, NoSuchAlgorithmException { Map<String, String> dict = retrieveLoginPage(); if (dict == null) { return null; } StringBuilder url = new StringBuilder("/config/login?login="); url.append(account); url.append("&passwd="); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); byte[] result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } String md5chal = dict.get(".challenge"); md5 = MessageDigest.getInstance("MD5"); md5.update(md5chal.getBytes(), 0, md5chal.length()); result = md5.digest(); for (int i = 0; i < 16; i++) { url.append(StringUtil.toHex2(result[i])); } Iterator<String> j = dict.keySet().iterator(); while (j.hasNext()) { String key = j.next(); String value = dict.get(key); if (!key.equals("passwd")) { if (key.equals(".save") || key.equals(".js")) { url.append("&" + key + "=1"); } else if (key.equals(".challenge")) { url.append("&" + key + "=" + value); } else { String u = URLEncoder.encode(value, "UTF-8"); url.append("&" + key + "=" + u); } } } url.append("&"); url.append(".hash=1"); url.append("&"); url.append(".md5=1"); return url.toString(); }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static Vector<Person> parseFriends(Worker me, SmEngine sme, Person resource) throws IOException { URL url = new URL(resource.getUrl()); long fid; if (sme.getProxy() == null) me.conn = (HttpURLConnection) url.openConnection(); else me.conn = (HttpURLConnection) url.openConnection(sme.getProxy()); me.conn.setReadTimeout(20 * 1000); Vector<Person> result; org.htmlparser.Parser parser; NodeList nl; NodeFilter[] filters1 = new NodeFilter[2]; filters1[0] = new TagNameFilter("a"); filters1[1] = new HasAttributeFilter("class", "signup_btn uiButton uiButtonSpecial uiButtonLarge"); NodeFilter[] filters2 = new NodeFilter[3]; filters2[0] = new TagNameFilter("a"); filters2[1] = new HasAttributeFilter("class", "title"); filters2[2] = new HasParentFilter(new HasAttributeFilter("class", "UIPortrait_Text")); try { parser = new org.htmlparser.Parser(me.conn); } catch (ParserException e) { System.err.println(e.getMessage()); return null; } try { nl = parser.parse(new AndFilter(filters1)); fid = Long.parseLong(((LinkTag) nl.elementAt(0)).getLink().split("(fid=|&amp)")[2]); } catch (ParserException e) { e.printStackTrace(); return null; } result = new Vector<Person>(); try { nl = parser.parse(new AndFilter(filters2)); } catch (ParserException e) { e.printStackTrace(); return null; } Person p; for (int i = 0; i < nl.size(); i++) { p = sme.getPerson(fid, ((TagNode) nl.elementAt(i)).getAttribute("title"), ((TagNode) nl.elementAt(i)).getAttribute("href")); resource.addFriend(p); p.addFriend(resource); synchronized (p) { if (!p.isInQueue()) { p.setInQueue(true); sme.addResource(p); } } } return result; }
00
Code Sample 1: public static void main(String args[]) throws Exception { FileInputStream fin = new FileInputStream("D:/work/test.txt"); FileOutputStream fout = new FileOutputStream("D:/work/output.txt"); FileChannel inChannel = fin.getChannel(); FileChannel outChannel = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { int ret = inChannel.read(buffer); if (ret == -1) break; buffer.flip(); outChannel.write(buffer); buffer.clear(); } } Code Sample 2: @DeclarePerfMonTimer("SortingTest.bubbleSort") private void bubbleSort(int values[]) { int len = values.length - 1; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i; j++) { if (values[j] > values[j + 1]) { int tmp = values[j]; values[j] = values[j + 1]; values[j + 1] = tmp; } } } }
00
Code Sample 1: public void testCodingBeyondContentLimitFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff; and a lot more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } Code Sample 2: private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
00
Code Sample 1: public static InputStream getInputStreamFromUrl(String url) { InputStream content = null; try { HttpGet httpGet = new HttpGet(url); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpGet); content = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return content; } Code Sample 2: private String encryptUserPassword(int userId, String password) { password = password.trim(); if (password.length() == 0) { return ""; } else { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new BoardRuntimeException(ex); } md.update(String.valueOf(userId).getBytes()); md.update(password.getBytes()); byte b[] = md.digest(); StringBuffer sb = new StringBuffer(1 + b.length * 2); for (int i = 0; i < b.length; i++) { int ii = b[i]; if (ii < 0) { ii = 256 + ii; } sb.append(getHexadecimalValue2(ii)); } return sb.toString(); } }
11
Code Sample 1: 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 copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public static Set<Address> getDatosCatastrales(String pURL) { Set<Address> result = new HashSet<Address>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniInm1 = "<rcdnp>"; String finInm1 = "</rcdnp>"; String iniInm2 = "<bi>"; String finInm2 = "</bi>"; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniCar = "<car>"; String finCar = "</car>"; String iniCC1 = "<cc1>"; String finCC1 = "</cc1>"; String iniCC2 = "<cc2>"; String finCC2 = "</cc2>"; String iniLDT = "<ldt>"; String iniBq = "<bq>"; String finBq = "</bq>"; String iniEs = "<es>"; String finEs = "</es>"; String iniPt = "<pt>"; String finPt = "</pt>"; String iniPu = "<pu>"; String finPu = "</pu>"; boolean error = false; int ini, fin; int postal = 0; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; 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(iniInm1) || str.contains(iniInm2)) { Address inmueble = new Address(); while ((str = br.readLine()) != null && !str.contains(finInm1) && !str.contains(finInm2)) { if (str.contains(iniPC1) && str.contains(finPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); inmueble.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2) && str.contains(finPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniLDT) && str.contains("-")) { postal = Integer.parseInt(str.substring(str.lastIndexOf("-") - 5, str.lastIndexOf("-"))); } if (str.contains(iniCar) && str.contains(finCar)) { ini = str.indexOf(iniCar) + iniCar.length(); fin = str.indexOf(finCar); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC1) && str.contains(finCC1)) { ini = str.indexOf(iniCC1) + iniCC1.length(); fin = str.indexOf(finCC1); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniCC2) && str.contains(finCC2)) { ini = str.indexOf(iniCC2) + iniCC2.length(); fin = str.indexOf(finCC2); inmueble.setDescription(inmueble.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniBq) && str.contains(finBq)) { ini = str.indexOf(iniBq) + iniBq.length(); fin = str.indexOf(finBq); inmueble.setBlock(str.substring(ini, fin)); } if (str.contains(iniEs) && str.contains(finEs)) { ini = str.indexOf(iniEs) + iniEs.length(); fin = str.indexOf(finEs); inmueble.setStairs(str.substring(ini, fin)); } if (str.contains(iniPt) && str.contains(finPt)) { ini = str.indexOf(iniPt) + iniPt.length(); fin = str.indexOf(finPt); inmueble.setFloor(str.substring(ini, fin)); } if (str.contains(iniPu) && str.contains(finPu)) { ini = str.indexOf(iniPu) + iniPu.length(); fin = str.indexOf(finPu); inmueble.setDoor(str.substring(ini, fin)); } } result.add(inmueble); } } } br.close(); if (result.size() == 1) { Object ad[] = result.toArray(); Coordinate coord = ConversorCoordenadas.getCoordenadas(((Address) ad[0]).getDescription()); coord.setPostcode(postal); for (Address inm : result) inm.setCoodinate(coord); } } catch (Exception e) { System.err.println(e); } return result; } Code Sample 2: private void Download(String uri) throws MalformedURLException { URL url = new URL(uri); try { bm = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException ex) { bm = getError(); } }
11
Code Sample 1: private String processFileUploadOperation(boolean isH264File) { String fileType = this.uploadFileFileName.substring(this.uploadFileFileName.lastIndexOf('.')); int uniqueHashCode = UUID.randomUUID().toString().hashCode(); if (uniqueHashCode < 0) { uniqueHashCode *= -1; } String randomFileName = uniqueHashCode + fileType; String fileName = (isH264File) ? getproperty("videoDraftPath") : getproperty("videoDraftPathForNonH264") + randomFileName; File targetVideoPath = new File(fileName + randomFileName); System.out.println("Path: " + targetVideoPath.getAbsolutePath()); try { targetVideoPath.createNewFile(); FileChannel outStreamChannel = new FileOutputStream(targetVideoPath).getChannel(); FileChannel inStreamChannel = new FileInputStream(this.uploadFile).getChannel(); inStreamChannel.transferTo(0, inStreamChannel.size(), outStreamChannel); outStreamChannel.close(); inStreamChannel.close(); return randomFileName; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); try { int read = fis.read(); while (read != -1) { fos.write(read); read = fis.read(); } } finally { fos.close(); } } finally { fis.close(); } }
11
Code Sample 1: private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } 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()); }
11
Code Sample 1: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String version = req.getParameter("version"); String cdn = req.getParameter("cdn"); String dependencies = req.getParameter("dependencies"); String optimize = req.getParameter("optimize"); String cacheFile = null; String result = null; boolean isCached = false; Boolean isError = true; if (!version.equals("1.3.2")) { result = "invalid version: " + version; } if (!cdn.equals("google") && !cdn.equals("aol")) { result = "invalide CDN type: " + cdn; } if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) { result = "invalid optimize type: " + optimize; } if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) { result = "invalid dependency list: " + dependencies; } try { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { result = e.getMessage(); } if (result == null) { md.update(dependencies.getBytes()); String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_'); cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js"; File file = new File(cacheFile); if (file.exists()) { isCached = true; isError = false; } } if (result == null && !isCached) { BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize); ContextFactory.getGlobal().call(contextAction); Exception exception = contextAction.getException(); if (exception != null) { result = exception.getMessage(); } else { result = contextAction.getResult(); FileUtil.writeToFile(cacheFile, result, null, true); isError = false; } } } catch (Exception e) { result = e.getMessage(); } res.setCharacterEncoding("utf-8"); if (isError) { result = result.replaceAll("\\\"", "\\\""); result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>"; PrintWriter writer = res.getWriter(); writer.append(result); } else { res.setHeader("Content-Type", "application/x-javascript"); res.setHeader("Content-disposition", "attachment; filename=dojo.js"); res.setHeader("Content-Encoding", "gzip"); File file = new File(cacheFile); BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file))); OutputStream out = res.getOutputStream(); byte[] bytes = new byte[64000]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = in.read(bytes); if (bytesRead != -1) { out.write(bytes, 0, bytesRead); } } } } Code Sample 2: private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } }
11
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: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private 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()); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: @Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); } Code Sample 2: public static String getCssFile(String url) { StringBuffer buffer = new StringBuffer(); try { buffer = new StringBuffer(); URL urlToCrawl = new URL(url); URLConnection urlToCrawlConnection = urlToCrawl.openConnection(); urlToCrawlConnection.setRequestProperty("User-Agent", "USER_AGENT"); urlToCrawlConnection.setRequestProperty("Referer", "REFERER"); urlToCrawlConnection.setUseCaches(false); InputStreamReader isr = new InputStreamReader(urlToCrawlConnection.getInputStream()); BufferedReader in = new BufferedReader(isr); String str; while ((str = in.readLine()) != null) buffer.append(str); FileOutputStream fos = new FileOutputStream("c:\\downloads\\" + System.currentTimeMillis() + ".css"); Writer out = new OutputStreamWriter(fos); out.write(buffer.toString()); out.close(); } catch (Exception e) { System.out.println("Error Downloading css file" + e); } return buffer.toString(); }
00
Code Sample 1: public void update() { new Thread(new Runnable() { @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } Code Sample 2: public static String getHash(String text) { String ret = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); ret = getHex(md.digest()); } catch (NoSuchAlgorithmException e) { log.error(e); throw new OopsException(e, "Hash Error."); } return ret; }
11
Code Sample 1: private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } } Code Sample 2: public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
00
Code Sample 1: 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; } Code Sample 2: public static byte[] hash(String plainTextValue) { MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(plainTextValue.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); return digest; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
11
Code Sample 1: private void gravaOp(Vector<?> op) { PreparedStatement ps = null; String sql = null; ResultSet rs = null; int seqop = 0; Date dtFabrOP = null; try { sql = "SELECT MAX(SEQOP) FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { seqop = rs.getInt(1) + 1; } rs.close(); ps.close(); con.commit(); sql = "SELECT DTFABROP FROM PPOP WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, txtSeqOP.getVlrInteger().intValue()); rs = ps.executeQuery(); if (rs.next()) { dtFabrOP = rs.getDate(1); } rs.close(); ps.close(); con.commit(); sql = "INSERT INTO PPOP (CODEMP,CODFILIAL,CODOP,SEQOP,CODEMPPD,CODFILIALPD,CODPROD,SEQEST,DTFABROP," + "QTDPREVPRODOP,QTDFINALPRODOP,DTVALIDPDOP,CODEMPLE,CODFILIALLE,CODLOTE,CODEMPTM,CODFILIALTM,CODTIPOMOV," + "CODEMPAX,CODFILIALAX,CODALMOX,CODEMPOPM,CODFILIALOPM,CODOPM,SEQOPM,QTDDISTIOP,QTDSUGPRODOP)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ps = con.prepareStatement(sql); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOP")); ps.setInt(3, txtCodOP.getVlrInteger().intValue()); ps.setInt(4, seqop); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPESTRUTURA")); ps.setInt(7, ((Integer) op.elementAt(4)).intValue()); ps.setInt(8, ((Integer) op.elementAt(6)).intValue()); ps.setDate(9, dtFabrOP); ps.setFloat(10, ((BigDecimal) op.elementAt(7)).floatValue()); ps.setFloat(11, 0); ps.setDate(12, (Funcoes.strDateToSqlDate((String) op.elementAt(11)))); ps.setInt(13, Aplicativo.iCodEmp); ps.setInt(14, ListaCampos.getMasterFilial("EQLOTE")); ps.setString(15, ((String) op.elementAt(10))); ps.setInt(16, Aplicativo.iCodEmp); ps.setInt(17, ListaCampos.getMasterFilial("EQTIPOMOV")); ps.setInt(18, buscaTipoMov()); ps.setInt(19, ((Integer) op.elementAt(13)).intValue()); ps.setInt(20, ((Integer) op.elementAt(14)).intValue()); ps.setInt(21, ((Integer) op.elementAt(12)).intValue()); ps.setInt(22, Aplicativo.iCodEmp); ps.setInt(23, ListaCampos.getMasterFilial("PPOP")); ps.setInt(24, txtCodOP.getVlrInteger().intValue()); ps.setInt(25, txtSeqOP.getVlrInteger().intValue()); ps.setFloat(26, ((BigDecimal) op.elementAt(9)).floatValue()); ps.setFloat(27, ((BigDecimal) op.elementAt(7)).floatValue()); ps.executeUpdate(); ps.close(); con.commit(); geraRMA(seqop); } catch (SQLException e) { Funcoes.mensagemErro(null, "Erro ao gerar OP's de distribui๏ฟฝ๏ฟฝo!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException eb) { } } } Code Sample 2: public void insert() throws Exception { Connection con = DbUtil.connectToDb(); PreparedStatement pStmt = null; try { pStmt = con.prepareStatement("INSERT INTO " + Constants.TABLENAME + " (name,phone,address)" + " values(?,?,?)"); con.setAutoCommit(false); pStmt.setString(1, name); pStmt.setString(2, phone); pStmt.setString(3, address); int j = pStmt.executeUpdate(); con.commit(); } catch (Exception ex) { try { con.rollback(); } catch (SQLException sqlex) { sqlex.printStackTrace(System.out); } throw ex; } finally { try { pStmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
00
Code Sample 1: private static URL getURL(String name) throws EfreetException { URL url = ClassLoader.getSystemResource(name + ".xml"); try { if (url == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); String xmlFileDir = (String) envContext.lookup("xml/efreet"); url = new URL("file:" + xmlFileDir + "/" + name + ".xml"); } catch (NameNotFoundException nnfe) { logger.warn("Name not found on context "); } catch (NamingException e) { logger.error("Error retrieving Context : ", e); } } try { if (url != null) { url.openConnection(); } } catch (FileNotFoundException fnfe) { url = null; } if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(name + ".xml"); } } catch (IOException ioe) { logger.error("Error reading XML file", ioe); throw new EfreetException(ioe.getMessage()); } return url; } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Contact contact = (Contact) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CONTACT")); pst.setInt(1, contact.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
00
Code Sample 1: private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente = '" + id + "'"; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public void setRemoteConfig(String s) { try { HashMap<String, String> map = new HashMap<String, String>(); URL url = new URL(s); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.startsWith("#")) continue; String[] split = line.split("="); if (split.length >= 2) { map.put(split[0], split[1]); } } MethodAndFieldSetter.setMethodsAndFields(this, map); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean copyFile(File sourceFile, File destinationFile) { boolean copySuccessfull = false; FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); long transferedBytes = destination.transferFrom(source, 0, source.size()); copySuccessfull = transferedBytes == source.size() ? true : false; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } return copySuccessfull; }
00
Code Sample 1: private String listaArquivo() { String arquivo = ""; String linha = ""; try { URL url = new URL(this.getCodeBase(), "./listador?dir=" + "cenarios" + "/" + user); URLConnection con = url.openConnection(); con.setUseCaches(false); InputStream in = con.getInputStream(); DataInputStream result = new DataInputStream(new BufferedInputStream(in)); while ((linha = result.readLine()) != null) { arquivo += linha + "\n"; } return arquivo; } catch (Exception e) { return null; } } Code Sample 2: protected void innerProcess(ProcessorURI curi) throws InterruptedException { Pattern regexpr = curi.get(this, STRIP_REG_EXPR); ReplayCharSequence cs = null; try { cs = curi.getRecorder().getReplayCharSequence(); } catch (Exception e) { curi.getNonFatalFailures().add(e); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr != null) { s = cs.toString(); } else { Matcher m = regexpr.matcher(cs); s = m.replaceAll(" "); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
11
Code Sample 1: protected File compress(File orig, IWrapCompression wrapper) throws IOException { File compressed = File.createTempFile("test.", ".gz"); FileOutputStream fos = new FileOutputStream(compressed); OutputStream wos = wrapper.wrap(fos); FileInputStream fis = new FileInputStream(orig); IOUtils.copy(fis, wos); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(wos); return compressed; } Code Sample 2: public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); }
00
Code Sample 1: private static void initMagicRules() { InputStream in = null; try { String fname = System.getProperty("magic-mime"); if (fname != null && fname.length() != 0) { in = new FileInputStream(fname); if (in != null) { parse("-Dmagic-mime=" + fname, new InputStreamReader(in)); } } } catch (Exception e) { log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime [" + System.getProperty("magic-mime") + "]. File will be ignored.", e); } finally { in = closeStream(in); } try { Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime"); while (en.hasMoreElements()) { URL url = (URL) en.nextElement(); in = url.openStream(); if (in != null) { try { parse("classpath:[" + url + "]", new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime rule file [" + url + "] on the classpath. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e); } finally { in = closeStream(in); } try { File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime"); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse .magic.mime file from the users home directory. File will be ignored.", ex); } } } } catch (Exception e) { log.error("Problem while processing .magic.mime file from the users home directory. File will be ignored.", e); } finally { in = closeStream(in); } try { String name = System.getProperty("MAGIC"); if (name != null && name.length() != 0) { if (name.indexOf('.') < 0) { name = name + ".mime"; } else { name = name.substring(0, name.indexOf('.') - 1) + "mime"; } File f = new File(name); if (f.exists()) { in = new FileInputStream(f); if (in != null) { try { parse(f.getAbsolutePath(), new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.", ex); } } } } } catch (Exception e) { log.error("Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.", e); } finally { in = closeStream(in); } int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size(); Iterator it = magicMimeFileLocations.iterator(); while (it.hasNext()) { parseMagicMimeFileLocation((String) it.next()); } if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) { try { String resource = "eu/medsea/mimeutil/magic.mime"; in = MimeUtil.class.getClassLoader().getResourceAsStream(resource); if (in != null) { try { parse("resource:" + resource, new InputStreamReader(in)); } catch (Exception ex) { log.error("Failed to parse internal magic.mime file.", ex); } } } catch (Exception e) { log.error("Problem while processing internal magic.mime file.", e); } finally { in = closeStream(in); } } } Code Sample 2: private void gerarComissao() { int opt = Funcoes.mensagemConfirma(null, "Confirma gerar comiss๏ฟฝes para o vendedor " + txtNomeVend.getVlrString().trim() + "?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPCOMISSAO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("CODEMPVD, CODFILIALVD, CODVEND, VLRCOMISS ) "); insert.append("VALUES "); insert.append("(?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; boolean gerou = false; try { for (int i = 0; i < tab.getNumLinhas(); i++) { if (((BigDecimal) tab.getValor(i, 8)).floatValue() > 0) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPCOMISSAO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPVENDEDOR")); ps.setInt(parameterIndex++, txtCodVend.getVlrInteger()); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.executeUpdate(); gerou = true; } } if (gerou) { Funcoes.mensagemInforma(null, "Comiss๏ฟฝo gerada para " + txtNomeVend.getVlrString().trim()); txtCodPed.setText("0"); lcPedido.carregaDados(); carregaTabela(); con.commit(); } else { Funcoes.mensagemInforma(null, "N๏ฟฝo foi possiv๏ฟฝl gerar comiss๏ฟฝo!\nVerifique os valores das comiss๏ฟฝes dos itens."); } } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar comiss๏ฟฝo!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
00
Code Sample 1: public static Document send(final String urlAddress) { Document responseMessage = null; try { URL url = new URL(urlAddress); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { String contentType = connection.getContentType(); if (contentType != null && contentType.startsWith("text/html")) { InputStream inputStream = connection.getInputStream(); responseMessage = XmlUtils.fromStream(inputStream); } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(contentType); } } else { responseMessage = XmlUtils.newDocument(); Element responseElement = XmlUtils.createElement(responseMessage, "rsp"); Element messageElement = XmlUtils.createElement(responseElement, "message"); messageElement.setTextContent(String.valueOf(connection.getResponseCode())); Element commentElement = XmlUtils.createElement(responseElement, "comment"); commentElement.setTextContent(connection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return responseMessage; } Code Sample 2: private static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); }
11
Code Sample 1: public static String md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); } Code Sample 2: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
11
Code Sample 1: public long getMD5Hash(String str) { MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(str.getBytes(), 0, str.length()); return new BigInteger(1, m.digest()).longValue(); } Code Sample 2: public static String getSHA1(String data) throws NoSuchAlgorithmException { String addr; data = data.toLowerCase(Locale.getDefault()); if (data.startsWith("mailto:")) { addr = data.substring(7); } else { addr = data; } MessageDigest md = MessageDigest.getInstance("SHA"); StringBuffer sb = new StringBuffer(); md.update(addr.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) { hex = "0" + hex; } hex = hex.substring(hex.length() - 2); sb.append(hex); } return sb.toString(); }
11
Code Sample 1: protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
00
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 postData(Reader data, URL endpoint, Writer output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endpoint.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } }
11
Code Sample 1: public static void copyFile(File src, String srcEncoding, File dest, String destEncoding) throws IOException { InputStreamReader in = new InputStreamReader(new FileInputStream(src), srcEncoding); OutputStreamWriter out = new OutputStreamWriter(new RobustFileOutputStream(dest), destEncoding); int c; while ((c = in.read()) != -1) out.write(c); out.flush(); in.close(); out.close(); } Code Sample 2: public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
00
Code Sample 1: public static String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } Code Sample 2: public void handle() { FileChannel srcChannel, destChannel; String destOutFile = databaseName + ".script." + System.currentTimeMillis(); String destOutFileCompressed = databaseName + ".script." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(databaseName + ".script"); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate database file '" + databaseName + ".script': " + e); } } else { try { srcChannel = new FileInputStream(databaseName + ".script").getChannel(); } catch (IOException e) { Debug.debug("Unable to read file '" + databaseName + ".script' for database rotation."); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFile + "'"); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(".script.") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
11
Code Sample 1: public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::ๆ‰ง่กŒSQL่ฏญๅฅๆ“ไฝœ(ๆ›ดๆ–ฐๆ•ฐๆฎ ๆœ‰ๅ‚ๆ•ฐ):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::ๆ‰ง่กŒSQL่ฏญๅฅๆ“ไฝœ(ๆ›ดๆ–ฐๆ•ฐๆฎ ๆ— ๅ‚ๆ•ฐ):" + strSql + "ๅคฑ่ดฅ!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::ๆ‰ง่กŒSQL่ฏญๅฅๆ“ไฝœ(ๆ›ดๆ–ฐๆ•ฐๆฎ ๆ— ๅ‚ๆ•ฐ):" + strSql + "ๅคฑ่ดฅ! ๅ‚ๆ•ฐ่ฎพ็ฝฎ็ฑปๅž‹้”™่ฏฏ!"); con.rollback(); throw ex; } return flag; } Code Sample 2: public static boolean update(ItemNotaFiscal objINF) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; CelulaFinanceira objCF = null; if (c == null) { return false; } if (objINF == null) { return false; } try { c.setAutoCommit(false); String sql = ""; sql = "update item_nota_fiscal " + "set id_item_pedido = ? " + "where id_item_nota_fiscal = ?"; pst = c.prepareStatement(sql); pst.setInt(1, objINF.getItemPedido().getCodigo()); pst.setInt(2, objINF.getCodigo()); result = pst.executeUpdate(); if (result > 0) { if (objINF.getItemPedido().getCelulaFinanceira() != null) { objCF = objINF.getItemPedido().getCelulaFinanceira(); objCF.atualizaGastoReal(objINF.getSubtotal()); if (CelulaFinanceiraDAO.update(objCF)) { } } } c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[ItemNotaFiscalDAO.update.rollback] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[ItemNotaFiscalDAO.update.insert] Erro ao inserir -> " + e.getMessage()); result = 0; } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } Code Sample 2: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
11
Code Sample 1: public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } } Code Sample 2: public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n๏ฟฝo pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); }
11
Code Sample 1: @Override public boolean copyFile(String srcRootPath, String srcDir, String srcFileName, String destRootPath, String destDir, String destFileName) { File srcPath = new File(srcRootPath + separator() + Database.getDomainName() + separator() + srcDir); if (!srcPath.exists()) { try { srcPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + srcPath); return false; } } File destPath = new File(destRootPath + separator() + Database.getDomainName() + separator() + destDir); if (!destPath.exists()) { try { destPath.mkdirs(); } catch (Exception e) { logger.error("Can't create directory...:" + destPath); return false; } } File from = new File(srcPath + separator() + srcFileName); File to = new File(destPath + separator() + destFileName); boolean res = true; FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(from).getChannel(); destChannel = new FileOutputStream(to).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (Exception ex) { logger.error("Exception", ex); res = false; } finally { if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } if (srcChannel != null) { try { srcChannel.close(); } catch (IOException ex) { logger.error("Exception", ex); res = false; } } } return res; } Code Sample 2: @Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
00
Code Sample 1: @Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { HttpPost postMethod = new HttpPost(config.getServiceUrl()); postMethod.setEntity(new ByteArrayEntity(baos.toByteArray())); HttpResponse rsp = httpClient.execute(postMethod); StatusLine sl = rsp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]"); } HttpEntity entity = rsp.getEntity(); InputStream responseBody = entity.getContent(); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: public boolean excuteBackup(String backupOrginlDrctry, String targetFileNm, String archiveFormat) throws JobExecutionException { File targetFile = new File(targetFileNm); File srcFile = new File(backupOrginlDrctry); if (!srcFile.exists()) { log.error("๋ฐฑ์—…์›๋ณธ๋””๋ ‰ํ† ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); throw new JobExecutionException("๋ฐฑ์—…์›๋ณธ๋””๋ ‰ํ† ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); } if (srcFile.isFile()) { log.error("๋ฐฑ์—…์›๋ณธ๋””๋ ‰ํ† ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ€ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค. ๋””๋ ‰ํ† ๋ฆฌ๋ช…์„ ์ง€์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. "); throw new JobExecutionException("๋ฐฑ์—…์›๋ณธ๋””๋ ‰ํ† ๋ฆฌ[" + srcFile.getAbsolutePath() + "]๊ฐ€ ํŒŒ์ผ์ž…๋‹ˆ๋‹ค. ๋””๋ ‰ํ† ๋ฆฌ๋ช…์„ ์ง€์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. "); } boolean result = false; FileInputStream finput = null; FileOutputStream fosOutput = null; ArchiveOutputStream aosOutput = null; ArchiveEntry entry = null; try { log.debug("charter set : " + Charset.defaultCharset().name()); fosOutput = new FileOutputStream(targetFile); aosOutput = new ArchiveStreamFactory().createArchiveOutputStream(archiveFormat, fosOutput); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { ((TarArchiveOutputStream) aosOutput).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } File[] fileArr = srcFile.listFiles(); ArrayList list = EgovFileTool.getSubFilesByAll(fileArr); for (int i = 0; i < list.size(); i++) { File sfile = new File((String) list.get(i)); finput = new FileInputStream(sfile); if (ArchiveStreamFactory.TAR.equals(archiveFormat)) { entry = new TarArchiveEntry(sfile, new String(sfile.getAbsolutePath().getBytes(Charset.defaultCharset().name()), "8859_1")); ((TarArchiveEntry) entry).setSize(sfile.length()); } else { entry = new ZipArchiveEntry(sfile.getAbsolutePath()); ((ZipArchiveEntry) entry).setSize(sfile.length()); } aosOutput.putArchiveEntry(entry); IOUtils.copy(finput, aosOutput); aosOutput.closeArchiveEntry(); finput.close(); result = true; } aosOutput.close(); } catch (Exception e) { log.error("๋ฐฑ์—…ํ™”์ผ์ƒ์„ฑ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ์—๋Ÿฌ : " + e.getMessage()); log.debug(e); result = false; throw new JobExecutionException("๋ฐฑ์—…ํ™”์ผ์ƒ์„ฑ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.", e); } finally { try { if (finput != null) finput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (aosOutput != null) aosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (fosOutput != null) fosOutput.close(); } catch (Exception e2) { log.error("IGNORE:", e2); } try { if (result == false) targetFile.delete(); } catch (Exception e2) { log.error("IGNORE:", e2); } } return result; } Code Sample 2: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception { String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH); if (bundleClassPath == null) { bundleClassPath = "."; } ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath); String[] classPaths = new String[0]; for (int i = 0; i < entries.length; i++) { String classPath = entries[i].getName(); if (classPath.startsWith("/")) { classPath = classPath.substring(1); } if (classPath.endsWith(".jar")) { try { File file = new File(cache, classPath); if (!alreadyCached) { file.getParentFile().mkdirs(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } else { if (!file.exists()) { throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString()); } } } catch (IOException e) { FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e); framework.postFrameworkEvent(frameworkEvent); continue; } } classPaths = (String[]) ArrayUtil.add(classPaths, classPath); } if (!alreadyCached) { String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE); if (bundleNativeCode != null) { entries = ManifestEntry.parse(bundleNativeCode); for (int i = 0; i < entries.length; i++) { ManifestEntry entry = entries[i]; String libPath = entry.getName(); String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString(); File file = new File(cache, libPath); file.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(file); InputStream is = new URL(url).openStream(); IOUtil.copy(is, os); is.close(); os.close(); } } } BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache); return urlClassPath; } Code Sample 2: public final void provisionGSLAM() { try { UUID[] slaUUID = new UUID[] { new UUID("AG-1") }; SLA[] slas = sslamContext.getSLARegistry().getIQuery().getSLA(slaUUID); for (SLA s : slas) { Party[] parties = s.getParties(); System.out.println("SLA Info :::" + s.getUuid().toString()); for (Party p : parties) { System.out.println("Printing gslam_epr value for Party" + p.getId() + "--" + p.getAgreementRole()); System.out.println(parties[0].getPropertyValue(new STND("gslam_epr"))); } } sslamContext.getSLARegistry().getIRegister().register(slas[0], slaUUID, SLAState.OBSERVED); String xmlFile2Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "provision.xml"; String soapAction = ""; URL url; url = new URL(syntaxConverterNegotiationWSURL); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn.setRequestProperty("SOAPAction", soapAction); 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); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db; db = factory.newDocumentBuilder(); org.xml.sax.InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new java.io.StringReader(response.toString())); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: GSLAM\n" + "Interface Name: negotiate/coordinage\n" + "Operation Name: Provision\n" + "Input:Type " + "void" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RegistrationFailureException e) { e.printStackTrace(); } catch (SLAManagerContextException e) { e.printStackTrace(); } catch (InvalidUUIDException e) { e.printStackTrace(); } }
11
Code Sample 1: private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } Code Sample 2: public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map<String, String> _headers, Map<String, String> _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; _url = encodeURL(_url); HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams methodParams = ((HttpMethodBase) method).getParams(); if (methodParams == null) { methodParams = new HttpMethodParams(); ((HttpMethodBase) method).setParams(methodParams); } if (_timeout < 0) methodParams.setSoTimeout(0); else methodParams.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("Content-Type", _contentType); } if (_headers == null || !_headers.containsKey("User-Agent")) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("User-Agent", DEFAULT_USERAGENT); } if (_headers != null) { Iterator<Map.Entry<String, String>> iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator<Map.Entry<String, String>> iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); InputStream instream = null; try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { LOG.warn("Http Satus:" + status + ",Url:" + _url); if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); } catch (IOException err) { LOG.error("Failed to access " + _url, err); throw err; } finally { IOUtils.closeQuietly(instream); if (method != null) method.releaseConnection(); } }
00
Code Sample 1: private Map fetchAdData(String url) throws ClientProtocolException, IOException { String app = "1"; String owner = "tx"; String session = ""; String sdk = "ad1.0"; String version = "txLove1.0"; String timestamp = String.valueOf(System.currentTimeMillis()); String sign = ""; String appSecret = "test"; Map<String, String> protocal = new HashMap<String, String>(); protocal.put(AuthUtils.AUTH_APP, app); protocal.put(AuthUtils.AUTH_OWNER, owner); protocal.put(AuthUtils.AUTH_SESSION, session); protocal.put(AuthUtils.SDK, sdk); protocal.put(AuthUtils.VERSION, version); protocal.put(AuthUtils.TIMESTAMP, timestamp); Map<String, String> parameter = new HashMap<String, String>(); parameter.put("uid", String.valueOf(user.getUserId())); parameter.put("ip", "0"); parameter.put("imsi", imsi); parameter.put("width", "0"); sign = AuthUtils.sign(protocal, parameter, appSecret); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url.toString()); request.setHeader(AuthUtils.AUTH_APP, app); request.setHeader(AuthUtils.AUTH_OWNER, owner); request.setHeader(AuthUtils.AUTH_SESSION, session); request.setHeader(AuthUtils.SDK, sdk); request.setHeader(AuthUtils.VERSION, version); request.setHeader(AuthUtils.TIMESTAMP, timestamp); request.setHeader(AuthUtils.SIGN, sign); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); JSONObject object; Map map = new HashMap(); try { System.out.println("##################### line = " + line); object = new JSONObject(line); if (object != null) { System.out.println(object.toString()); map.put("imgAddress", object.getString("imgurl")); map.put("imgUrl", object.getString("url")); return map; } } catch (JSONException e) { e.printStackTrace(); } } return null; } Code Sample 2: public static void track(String strUserName, String strShortDescription, String strLongDescription, String strPriority, String strComponent) { String strFromToken = ""; try { URL url = new URL(getTracUrl() + "newticket"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String buffer = reader.readLine(); while (buffer != null) { if (buffer.contains("__FORM_TOKEN")) { Pattern pattern = Pattern.compile("value=\"[^\"]*\""); Matcher matcher = pattern.matcher(buffer); int start = 0; matcher.find(start); int von = matcher.start() + 7; int bis = matcher.end() - 1; strFromToken = buffer.substring(von, bis); } buffer = reader.readLine(); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(getTracUrl() + "newticket"); method.setRequestHeader("Cookie", "trac_form_token=" + strFromToken); method.addParameter("__FORM_TOKEN", strFromToken); method.addParameter("reporter", strUserName); method.addParameter("summary", strShortDescription); method.addParameter("type", "Fehler"); method.addParameter("description", strLongDescription); method.addParameter("action", "create"); method.addParameter("status", "new"); method.addParameter("priority", strPriority); method.addParameter("milestone", ""); method.addParameter("component", strComponent); method.addParameter("keywords", "BugReporter"); method.addParameter("cc", ""); method.addParameter("version", ""); client.executeMethod(method); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static String calcHA1(String algorithm, String username, String realm, String password, String nonce, String cnonce) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (username == null || realm == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "username or realm"); } if (password == null) { System.err.println("No password has been provided"); throw new IllegalStateException(); } if (algorithm != null && algorithm.equals("MD5-sess") && (nonce == null || cnonce == null)) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce or cnonce"); } md5.update((username + ":" + realm + ":" + password).getBytes()); if (algorithm != null && algorithm.equals("MD5-sess")) { md5.update((":" + nonce + ":" + cnonce).getBytes()); } return encoder.encode(md5.digest()); } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } Code Sample 2: public static String getWebContent(String remoteUrl) { StringBuffer sb = new StringBuffer(); try { java.net.URL url = new java.net.URL(remoteUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (Exception e) { logger.error("่Žทๅ–่ฟœ็จ‹็ฝ‘ๅ€ๅ†…ๅฎนๅคฑ่ดฅ - " + remoteUrl, e); } return sb.toString(); }
00
Code Sample 1: public Resource get(URL serviceUrl, String resourceId) throws Exception { Resource resource = new Resource(); String openurl = serviceUrl.toString() + "?url_ver=Z39.88-2004" + "&rft_id=" + URLEncoder.encode(resourceId, "UTF-8") + "&svc_id=" + SVCID_ADORE4; log.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(StreamUtil.getByteArray(is)); resource.setContentType(huc.getContentType()); } else { log.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; } Code Sample 2: public static String mdFive(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] array = new byte[32]; md.update(string.getBytes("iso-8859-1"), 0, string.length()); array = md.digest(); return convertToHex(array); }
00
Code Sample 1: private void downloadFtp(File file, URL jurl) throws SocketException, IOException { System.out.println("downloadFtp(" + file + ", " + jurl + ")"); FTPClient client = new FTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } }); try { client.connect(jurl.getHost(), -1 == jurl.getPort() ? FTP.DEFAULT_PORT : jurl.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new IOException("FTP server refused connection."); } if (!client.login("anonymous", "anonymous")) { client.logout(); throw new IOException("Authentication failure."); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); FileOutputStream out = new FileOutputStream(file); boolean ok = client.retrieveFile(jurl.getPath(), out); out.close(); client.logout(); if (!ok) { throw new IOException("File transfer failure."); } } catch (IOException e) { throw e; } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } } Code Sample 2: public static String getHash(String plaintext) { String hash = null; try { String text = plaintext; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes("UTF-8")); byte[] rawBytes = md.digest(); hash = new BASE64Encoder().encode(rawBytes); } catch (NoSuchAlgorithmException e) { } } catch (IOException e) { } return hash; }
00
Code Sample 1: public JarClassLoader(ClassLoader parent) { super(parent); initLogger(); hmClass = new HashMap<String, Class<?>>(); lstJarFile = new ArrayList<JarFileInfo>(); hsDeleteOnExit = new HashSet<File>(); String sUrlTopJar = null; pd = getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL urlTopJar = cs.getLocation(); String protocol = urlTopJar.getProtocol(); JarFileInfo jarFileInfo = null; if ("http".equals(protocol) || "https".equals(protocol)) { try { urlTopJar = new URL("jar:" + urlTopJar + "!/"); JarURLConnection jarCon = (JarURLConnection) urlTopJar.openConnection(); JarFile jarFile = jarCon.getJarFile(); jarFileInfo = new JarFileInfo(jarFile, jarFile.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", urlTopJar, protocol); } catch (Exception e) { logError(LogArea.JAR, "Failure to load HTTP JAR: %s %s", urlTopJar, e.toString()); return; } } if ("file".equals(protocol)) { try { sUrlTopJar = URLDecoder.decode(urlTopJar.getFile(), "UTF-8"); } catch (UnsupportedEncodingException e) { logError(LogArea.JAR, "Failure to decode URL: %s %s", urlTopJar, e.toString()); return; } File fileJar = new File(sUrlTopJar); if (fileJar.isDirectory()) { logInfo(LogArea.JAR, "Loading from exploded directory: %s", sUrlTopJar); return; } try { jarFileInfo = new JarFileInfo(new JarFile(fileJar), fileJar.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", sUrlTopJar, protocol); } catch (IOException e) { logError(LogArea.JAR, "Not a JAR: %s %s", sUrlTopJar, e.toString()); return; } } try { if (jarFileInfo == null) { throw new IOException(String.format("Unknown protocol %s", protocol)); } loadJar(jarFileInfo); } catch (IOException e) { logError(LogArea.JAR, "Not valid URL: %s %s", urlTopJar, e.toString()); return; } checkShading(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { shutdown(); } }); } Code Sample 2: public static void unzip(File sourceZipFile, File unzipDestinationDirectory, FileFilter filter) throws IOException { unzipDestinationDirectory.mkdirs(); if (!unzipDestinationDirectory.exists()) { throw new IOException("Unable to create destination directory: " + unzipDestinationDirectory); } ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); if (!entry.isDirectory()) { String currentEntry = entry.getName(); File destFile = new File(unzipDestinationDirectory, currentEntry); if (filter == null || filter.accept(destFile)) { File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); FileOutputStream fos = new FileOutputStream(destFile); IOUtils.copyLarge(is, fos); fos.flush(); IOUtils.closeQuietly(fos); } } } zipFile.close(); }
00
Code Sample 1: private void updateViewerContent(ScrollingGraphicalViewer viewer) { BioPAXGraph graph = (BioPAXGraph) viewer.getContents().getModel(); if (!graph.isMechanistic()) return; Map<String, Color> highlightMap = new HashMap<String, Color>(); for (Object o : graph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (node.isHighlighted()) { highlightMap.put(node.getIDHash(), node.getHighlightColor()); } } for (Object o : graph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (edge.isHighlighted()) { highlightMap.put(edge.getIDHash(), edge.getHighlightColor()); } } HighlightLayer hLayer = (HighlightLayer) ((ChsScalableRootEditPart) viewer.getRootEditPart()).getLayer(HighlightLayer.HIGHLIGHT_LAYER); hLayer.removeAll(); hLayer.highlighted.clear(); viewer.deselectAll(); graph.recordLayout(); PathwayHolder p = graph.getPathway(); if (withContent != null) { p.updateContentWith(withContent); } BioPAXGraph newGraph = main.getRootGraph().excise(p); newGraph.setAsRoot(); viewer.setContents(newGraph); boolean layedout = newGraph.fetchLayout(); if (!layedout) { new CoSELayoutAction(main).run(); } viewer.deselectAll(); GraphAnimation.run(viewer); for (Object o : newGraph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (highlightMap.containsKey(node.getIDHash())) { node.setHighlightColor(highlightMap.get(node.getIDHash())); node.setHighlight(true); } } for (Object o : newGraph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (highlightMap.containsKey(edge.getIDHash())) { edge.setHighlightColor(highlightMap.get(edge.getIDHash())); edge.setHighlight(true); } } } Code Sample 2: public static Collection<String> readXML(Bundle declaringBundle, URL url) throws XmlPullParserException { try { return readXML(declaringBundle, url.openStream()); } catch (IOException e) { throw new XmlPullParserException("Could not open \"" + url + "\" got exception:" + e.getLocalizedMessage()); } }
11
Code Sample 1: public static String hashMD5(String entrada) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(entrada.getBytes(), 0, entrada.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } Code Sample 2: public static String md5It(String data) { MessageDigest digest; String output = ""; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); for (byte b : hash) { output = output + String.format("%02X", b); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Authenticator.class.getName()).log(Level.SEVERE, null, ex); } return output; }
11
Code Sample 1: public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } 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 int gzipFile(File file_input, String file_output) { File gzip_output = new File(file_output); GZIPOutputStream gzip_out_stream; try { FileOutputStream out = new FileOutputStream(gzip_output); gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_GZIP_FAIL; } try { gzip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } }
00
Code Sample 1: private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; } 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 byte[] md5raw(String data) { try { MessageDigest md = MessageDigest.getInstance(MD); md.update(data.getBytes(UTF8)); return md.digest(); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: @Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } } Code Sample 2: @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); }