label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
public void setInitialValues(String Tag, Vector subfields) { this.tftag.setText(Tag); presentineditor = new ArrayList(); this.glosf = subfields; for (int i = 0; i < subfields.size(); i++) { this.dlm2.addElement(subfields.elementAt(i).toString().trim()); presentineditor.add(subfields.elementAt(i).toString().trim()); } String xmlreq = CataloguingXMLGenerator.getInstance().getSubFieldsRepeat("5", Tag); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "MarcDictionaryServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element retroot = retdoc.getRootElement(); hashtable = new Hashtable(); List list = retroot.getChildren(); System.out.println("Point of execution came here " + list.size()); for (int i = 0; i < list.size(); i++) { List chilist = ((Element) list.get(i)).getChildren(); hashtable.put(((Element) chilist.get(0)).getText().trim(), ((Element) chilist.get(1)).getText().trim()); } System.out.println(hashtable); Enumeration keys = hashtable.keys(); while (keys.hasMoreElements()) this.dlm1.addElement(keys.nextElement()); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
public void handleMessage(Message message) throws Fault { InputStream is = message.getContent(InputStream.class); if (is == null) { return; } CachedOutputStream bos = new CachedOutputStream(); try { IOUtils.copy(is, bos); is.close(); bos.close(); sendMsg("Inbound Message \n" + "--------------" + bos.getOut().toString() + "\n--------------"); message.setContent(InputStream.class, bos.getInputStream()); } catch (IOException e) { throw new Fault(e); } }
|
00
|
Code Sample 1:
public void setUserPassword(final List<NewUser> users) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); Iterator<NewUser> iter = users.iterator(); NewUser user; PasswordHasher ph; while (iter.hasNext()) { user = iter.next(); ph = PasswordFactory.getInstance().getPasswordHasher(); psImpl.setString(1, ph.hashPassword(user.password)); psImpl.setString(2, ph.getSalt()); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); usersToRemoveFromCache.add(user.userId); } } }); List<JESRealmUser> list = (List<JESRealmUser>) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { List<JESRealmUser> list = new ArrayList<JESRealmUser>(users.size() + 10); psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realms.user.load")); Iterator<NewUser> iter = users.iterator(); NewUser user; while (iter.hasNext()) { user = iter.next(); psImpl.setInt(1, user.userId); rsImpl = psImpl.executeQuery(); while (rsImpl.next()) { list.add(new JESRealmUser(user.username, user.userId, rsImpl.getInt("realm_id"), rsImpl.getInt("domain_id"), user.password, rsImpl.getString("realm_name_lower_case"))); } } return list; } }); final List<JESRealmUser> encrypted = new ArrayList<JESRealmUser>(list.size()); Iterator<JESRealmUser> iter = list.iterator(); JESRealmUser jesRealmUser; Realm realm; while (iter.hasNext()) { jesRealmUser = iter.next(); realm = cm.getRealm(jesRealmUser.realm); encrypted.add(new JESRealmUser(null, jesRealmUser.userId, jesRealmUser.realmId, jesRealmUser.domainId, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(jesRealmUser.username.toLowerCase(locale), realm.getFullRealmName().equals("null") ? "" : realm.getFullRealmName(), jesRealmUser.password), null)); } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realms.user.update")); Iterator<JESRealmUser> iter = encrypted.iterator(); JESRealmUser jesRealmUser; while (iter.hasNext()) { jesRealmUser = iter.next(); psImpl.setString(1, jesRealmUser.password); psImpl.setInt(2, jesRealmUser.realmId); psImpl.setInt(3, jesRealmUser.userId); psImpl.setInt(4, jesRealmUser.domainId); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
Code Sample 2:
@Deprecated public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { List<SearchKeyResult> outVec = new ArrayList<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, UTF8); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } IOUtils.closeQuietly(input); return outVec; }
|
11
|
Code Sample 1:
public Login authenticateClient() { Object o; String user, password; Vector<Login> clientLogins = ClientLoginsTableModel.getClientLogins(); Login login = null; try { socket.setSoTimeout(25000); objectOut.writeObject("JFRITZ SERVER 1.1"); objectOut.flush(); o = objectIn.readObject(); if (o instanceof String) { user = (String) o; objectOut.flush(); for (Login l : clientLogins) { if (l.getUser().equals(user)) { login = l; break; } } if (login != null) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(login.getPassword().getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] dataKeySeed = new byte[32]; Random random = new Random(); random.nextBytes(dataKeySeed); md.reset(); md.update(dataKeySeed); dataKeySeed = md.digest(); SealedObject dataKeySeedSealed; dataKeySeedSealed = new SealedObject(dataKeySeed, desCipher); objectOut.writeObject(dataKeySeedSealed); objectOut.flush(); desKeySpec = new DESKeySpec(dataKeySeed); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(inCipher); if (o instanceof String) { String response = (String) o; if (response.equals("OK")) { SealedObject ok_sealed = new SealedObject("OK", outCipher); objectOut.writeObject(ok_sealed); return login; } else { Debug.netMsg("Client sent false response to challenge!"); } } else { Debug.netMsg("Client sent false object as response to challenge!"); } } else { Debug.netMsg("client sent unkown username: " + user); } } } catch (IllegalBlockSizeException e) { Debug.netMsg("Wrong blocksize for sealed object!"); Debug.error(e.toString()); e.printStackTrace(); } catch (ClassNotFoundException e) { Debug.netMsg("received unrecognized object from client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.netMsg("Error authenticating client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.netMsg("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return null; }
Code Sample 2:
private 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:
@Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } }
Code Sample 2:
public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
00
|
Code Sample 1:
public String[] fetchAutocomplete(String text) { String[] result = new String[0]; String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.autocomplete.url", text); HttpContext context = new BasicHttpContext(); HttpGet method = new HttpGet(url); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity).split("\n"); EntityUtils.consume(entity); } } catch (Exception ex) { result = new String[0]; } finally { method.abort(); } return result; }
Code Sample 2:
@Override public boolean delete(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasDelete = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("delete")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasDelete = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasDelete > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Delete"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } }
|
00
|
Code Sample 1:
private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (; ; ) { int r = in.read(); if (r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch (IOException e) { throw new UndeclaredThrowableException(e); } }
Code Sample 2:
protected String readFileUsingHttp(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Type", "text/html"); httpConn.setRequestProperty("Content-Length", "0"); httpConn.setRequestMethod("GET"); httpConn.setDoOutput(true); httpConn.setDoInput(true); httpConn.setAllowUserInteraction(false); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) System.out.write(x); } if (args.length == 1) print("Checksum: " + csumi.getChecksum().getValue()); bis.close(); ZipFile zf = new ZipFile("test.zip"); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); print("File: " + ze2); } }
Code Sample 2:
public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); }
|
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:
static Collection<InetSocketAddress> getAddresses(Context ctx, long userId) throws Exception { AGLog.d(TAG, "Connecting to HTTP service to obtain IP addresses"); String host = (String) ctx.getResources().getText(R.string.gg_webservice_addr); String ver = App.getInstance().getGGClientVersion(); String url = host + "?fmnumber=" + Long.toString(userId) + "&lastmsg=0&version=" + ver; HttpClient httpClient = new DefaultHttpClient(); AGLog.d(TAG, "connecting to http service at " + url); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); AGLog.d(TAG, "response status:" + response.getStatusLine().getReasonPhrase()); HttpEntity ent = response.getEntity(); if (ent == null) { AGLog.e(TAG, "No response entity"); throw new ClientProtocolException("No response entity"); } InputStream content = ent.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line = reader.readLine(); AGLog.d(TAG, "response: " + line); StringTokenizer tokenizer = new StringTokenizer(line, " "); @SuppressWarnings("unused") String status = tokenizer.nextToken(); @SuppressWarnings("unused") String unknown = tokenizer.nextToken(); ArrayList<InetSocketAddress> result = new ArrayList<InetSocketAddress>(); while (tokenizer.hasMoreTokens()) { StringTokenizer addrport = new StringTokenizer(tokenizer.nextToken(), ":"); String addrStr = addrport.nextToken(); if (InetAddressUtils.isIPv4Address(addrStr)) { AGLog.d(TAG, "Address decoded successfully: " + addrStr); } else { AGLog.w(TAG, "Failed to decode address: " + addrStr); continue; } String portStr; if (addrport.hasMoreTokens()) { portStr = addrport.nextToken(); } else { portStr = (String) ctx.getResources().getText(R.string.gg_default_port); } AGLog.d(TAG, "Port decoded successfully: " + portStr); short port = Short.decode(portStr); result.add(new InetSocketAddress(addrStr, port)); } return result; }
|
11
|
Code Sample 1:
public String decrypt(String text, String passphrase, int keylen) { RC2ParameterSpec parm = new RC2ParameterSpec(keylen); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes(getCharset())); SecretKeySpec skeySpec = new SecretKeySpec(md.digest(), "RC2"); Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, parm); byte[] dString = Base64.decode(text); byte[] d = cipher.doFinal(dString); String clearTextNew = decodeBytesNew(d); return clearTextNew; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } }
|
11
|
Code Sample 1:
private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); }
Code Sample 2:
public static void readFile(FOUserAgent ua, String uri, OutputStream output) throws IOException { InputStream in = getURLInputStream(ua, uri); try { IOUtils.copy(in, output); } finally { IOUtils.closeQuietly(in); } }
|
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 DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
|
00
|
Code Sample 1:
private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); }
Code Sample 2:
private String _doPost(final String urlStr, final Map<String, String> params) { String paramsStr = ""; for (String key : params.keySet()) { try { paramsStr += URLEncoder.encode(key, ENCODING) + "=" + URLEncoder.encode(params.get(key), ENCODING) + "&"; } catch (UnsupportedEncodingException e) { s_logger.debug("UnsupportedEncodingException caught. Trying to encode: " + key + " and " + params.get(key)); return null; } } if (paramsStr.length() == 0) { s_logger.debug("POST will not complete, no parameters specified."); return null; } s_logger.debug("POST to server will be done with the following parameters: " + paramsStr); HttpURLConnection connection = null; String responseStr = null; try { connection = (HttpURLConnection) (new URL(urlStr)).openConnection(); connection.setRequestMethod(REQUEST_METHOD); connection.setDoOutput(true); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.write(paramsStr.getBytes()); dos.flush(); dos.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); responseStr = response.toString(); } catch (ProtocolException e) { s_logger.debug("ProtocolException caught. Unable to execute POST."); } catch (MalformedURLException e) { s_logger.debug("MalformedURLException caught. Unexpected. Url is: " + urlStr); } catch (IOException e) { s_logger.debug("IOException caught. Unable to execute POST."); } return responseStr; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) System.out.print((char) buff.get()); }
Code Sample 2:
public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } }
|
00
|
Code Sample 1:
private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
00
|
Code Sample 1:
static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + 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.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
00
|
Code Sample 1:
protected QName _getServiceName(String wsdlLocation) throws IOException, WSDLException { URL url = new URL(wsdlLocation); InputStream is = null; QName service = null; try { is = url.openStream(); WSDLReader reader = WSDLFactory.newInstance().newWSDLReader(); Definition def = reader.readWSDL(null, new InputSource(is)); Map services = def.getServices(); if (services.size() == 1) { javax.wsdl.Service se = (javax.wsdl.Service) services.values().iterator().next(); service = se.getQName(); } } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return service; }
Code Sample 2:
protected String getRequestContent(String urlText, String method) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestProperty("Referer", REFERER_STR); urlcon.setRequestMethod(method); urlcon.setUseCaches(false); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
|
11
|
Code Sample 1:
private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; }
Code Sample 2:
public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
|
00
|
Code Sample 1:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); LOG.info("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { LOG.info("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); String urlString = url.getPath(); LOG.info("OKIOSIDManagedObject.contentType(): urlString = " + urlString + "\n"); if (urlString != null) { uti = UTType.preferredIdentifierForTag(UTType.FilenameExtensionTagClass, (NSPathUtilities.pathExtension(urlString)).toLowerCase(), null); } if (uti == null) { uti = UTType.Item; } return uti; } if (contentType != null) { LOG.info("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; LOG.info("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
Code Sample 2:
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; this.logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; this.logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; this.logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { this.logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
|
11
|
Code Sample 1:
public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; }
Code Sample 2:
public String encodePassword(String password, byte[] salt) throws Exception { if (salt == null) { salt = new byte[12]; secureRandom.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); byte[] digest = md.digest(); byte[] storedPassword = new byte[digest.length + 12]; System.arraycopy(salt, 0, storedPassword, 0, 12); System.arraycopy(digest, 0, storedPassword, 12, digest.length); return new String(Base64.encode(storedPassword)); }
|
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 Vector Get() throws Exception { String query_str = BuildYahooQueryString(); if (query_str == null) return null; Vector result = new Vector(); HttpURLConnection urlc = null; try { URL url = new URL(URL_YAHOO_QUOTE + "?" + query_str + "&" + FORMAT); urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/html;charset=UTF-8"); if (urlc.getResponseCode() == 200) { InputStream in = urlc.getInputStream(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String msg = null; while ((msg = reader.readLine()) != null) { ExchangeRate rate = ParseYahooData(msg); if (rate != null) result.add(rate); } } finally { if (reader != null) try { reader.close(); } catch (Exception e1) { } if (in != null) try { in.close(); } catch (Exception e1) { } } return result; } } finally { if (urlc != null) try { urlc.disconnect(); } catch (Exception e) { } } return null; }
|
00
|
Code Sample 1:
public static void main(String[] args) { FileInputStream in; DeflaterOutputStream out; FileOutputStream fos; FileDialog fd; fd = new FileDialog(new Frame(), "Find a file to deflate", FileDialog.LOAD); fd.show(); if (fd.getFile() != null) { try { in = new FileInputStream(new File(fd.getDirectory(), fd.getFile())); fos = new FileOutputStream(new File("Deflated.out")); out = new DeflaterOutputStream(fos, new Deflater(Deflater.DEFLATED, true)); int bytes_read = 0; byte[] buffer = new byte[1024]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } fos.flush(); fos.close(); out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done"); } }
Code Sample 2:
public static void main(String[] arg) throws IOException { XmlPullParserFactory PULL_PARSER_FACTORY; try { PULL_PARSER_FACTORY = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); PULL_PARSER_FACTORY.setNamespaceAware(true); DasParser dp = new DasParser(PULL_PARSER_FACTORY); URL url = new URL("http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/features?segment=P05067"); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String aLine, xml = ""; while ((aLine = br.readLine()) != null) { xml += aLine; } WritebackDocument wbd = dp.parse(xml); System.out.println("FIN" + wbd); } catch (XmlPullParserException xppe) { throw new IllegalStateException("Fatal Exception thrown at initialisation. Cannot initialise the PullParserFactory required to allow generation of the DAS XML.", xppe); } }
|
11
|
Code Sample 1:
private static void copyFile(File inputFile, File outputFile) throws IOException { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public Image storeImage(String title, String pathToImage, Map<String, Object> additionalProperties) { File collectionFolder = ProjectManager.getInstance().getFolder(PropertyHandler.getInstance().getProperty("_default_collection_name")); File imageFile = new File(pathToImage); String filename = ""; String format = ""; File copiedImageFile; while (true) { filename = "image" + UUID.randomUUID().hashCode(); if (!DbEntryProvider.INSTANCE.idExists(filename)) { Path path = new Path(pathToImage); format = path.getFileExtension(); copiedImageFile = new File(collectionFolder.getAbsolutePath() + File.separator + filename + "." + format); if (!copiedImageFile.exists()) break; } } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(imageFile), 4096); out = new BufferedOutputStream(new FileOutputStream(copiedImageFile), 4096); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } Image image = new ImageImpl(); image.setId(filename); image.setFormat(format); image.setEntryDate(new Date()); image.setTitle(title); image.setAdditionalProperties(additionalProperties); boolean success = DbEntryProvider.INSTANCE.storeNewImage(image); if (success) return image; return null; }
|
00
|
Code Sample 1:
public boolean import_status(String filename) { int pieceId; int i, j, col, row; int rotation; int number; boolean byurl = false; e2piece temppiece; String lineread; StringTokenizer tok; BufferedReader entree; try { if (byurl == true) { URL url = new URL(baseURL, filename); InputStream in = url.openStream(); entree = new BufferedReader(new InputStreamReader(in)); } else { entree = new BufferedReader(new FileReader(filename)); } pieceId = 0; for (i = 0; i < board.colnb; i++) { for (j = 0; j < board.rownb; j++) { unplace_piece_at(i, j); } } while (true) { lineread = entree.readLine(); if (lineread == null) { break; } tok = new StringTokenizer(lineread, " "); pieceId = Integer.parseInt(tok.nextToken()); col = Integer.parseInt(tok.nextToken()) - 1; row = Integer.parseInt(tok.nextToken()) - 1; rotation = Integer.parseInt(tok.nextToken()); place_piece_at(pieceId, col, row, 0); temppiece = board.get_piece_at(col, row); temppiece.reset_rotation(); temppiece.rotate(rotation); } return true; } catch (IOException err) { return false; } }
Code Sample 2:
@Override public HttpResponse makeRequest() throws RequestCancelledException, IllegalStateException, IOException { checkState(); OutputStream out = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(destFile)); URLConnection conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[BUFFRE_SIZE]; int numRead; long totalSize = conn.getContentLength(); long transferred = 0; started(totalSize); while (!checkAbortFlag() && (numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); out.flush(); transferred += numRead; progress(transferred); } if (checkAbortFlag()) { cancelled(); } else { finished(); } if (checkAbortFlag()) { throw new RequestCancelledException(); } } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } return null; }
|
11
|
Code Sample 1:
protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
Code Sample 2:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { } } catch (FileNotFoundException e) { } }
|
00
|
Code Sample 1:
public static URL getWikipediaPage(String concept, String language) throws MalformedURLException, IOException { String url = "http://" + language + ".wikipedia.org/wiki/Special:Search?search=" + URLEncoder.encode(concept, UTF_8_ENCODING) + "&go=Go"; HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { return null; } else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) { return new URL(httpConnection.getHeaderField("Location")); } else { logger.warn("Unexpected response code (" + responseCode + ")."); return null; } } finally { if (httpConnection != null) { httpConnection.disconnect(); } } }
Code Sample 2:
protected List<String> execute(String queryString, String sVar, String filter) throws UnsupportedEncodingException, IOException { String query = URLEncoder.encode(queryString, "UTF-8"); String urlString = "http://sparql.bibleontology.com/sparql.jsp?sparql=" + query + "&type1=xml"; URL url; BufferedReader br = null; ArrayList<String> values = new ArrayList<String>(); try { url = new URL(urlString); URLConnection conn = url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { String sURI = getURI(line); if (sURI != null) { sURI = checkURISyntax(sURI); if (filter == null || sURI.startsWith(filter)) { values.add(sURI); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { br.close(); } return values; }
|
00
|
Code Sample 1:
public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); }
Code Sample 2:
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; }
|
00
|
Code Sample 1:
public static void copyTo(java.io.File source, java.io.File dest) throws Exception { java.io.FileInputStream inputStream = null; java.nio.channels.FileChannel sourceChannel = null; java.io.FileOutputStream outputStream = null; java.nio.channels.FileChannel destChannel = null; long size = source.length(); long bufferSize = 1024; long count = 0; if (size < bufferSize) bufferSize = size; Exception exception = null; try { if (dest.exists() == false) dest.createNewFile(); inputStream = new java.io.FileInputStream(source); sourceChannel = inputStream.getChannel(); outputStream = new java.io.FileOutputStream(dest); destChannel = outputStream.getChannel(); while (count < size) count += sourceChannel.transferTo(count, bufferSize, destChannel); } catch (Exception e) { exception = e; } finally { closeFileChannel(sourceChannel); closeFileChannel(destChannel); } if (exception != null) throw exception; }
Code Sample 2:
public Void doInBackground() { Transferable clipData = clipboard.getContents(this); File file = new File("Videos/" + (mp3.getArtist() + " - " + mp3.getTitle() + ".jpg").replace("/", "").replace("\\", "")); try { String test = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); String testje = test.toLowerCase(); if (testje.indexOf(".flv") > 0 || testje.indexOf(".wmv") > 0 || testje.indexOf(".mpg") > 0 || testje.indexOf(".mpeg") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".avi") > 0 || testje.indexOf(".divx") > 0 || testje.indexOf(".avi") > 0) { URL url = new URL(test); (new File("Videos/")).mkdirs(); System.out.println("Saving video to " + file); try { URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); System.out.flush(); FileOutputStream fos = null; fos = new FileOutputStream(file); byte[] buf = new byte[32768]; int len; while ((len = is.read(buf)) > 0) { fos.write(buf, 0, len); } is.close(); fos.close(); } catch (Exception e) { System.out.println("Error saving video from url: " + url); mp3.setVideo(file.getAbsolutePath()); } } } catch (Exception ex) { System.out.println("not a valid video file"); ex.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); }
Code Sample 2:
private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
|
00
|
Code Sample 1:
public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); }
Code Sample 2:
public String encryptToMD5(String info) { byte[] digesta = null; try { MessageDigest alga = MessageDigest.getInstance("MD5"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String rs = byte2hex(digesta); return rs; }
|
11
|
Code Sample 1:
@Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); }
Code Sample 2:
static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
|
00
|
Code Sample 1:
public int addLocationInfo(int id, double lattitude, double longitude) { int ret = 0; Connection conn = null; PreparedStatement psmt = null; try { String sql = "insert into kddb.location_info (user_id, latitude, longitude) values(?, ?, ?)"; conn = getConnection(); psmt = conn.prepareStatement(sql); psmt.setInt(1, id); psmt.setDouble(2, lattitude); psmt.setDouble(3, longitude); ret = psmt.executeUpdate(); if (ret == 1) { conn.commit(); } else { conn.rollback(); } } catch (SQLException ex) { log.error("[addLocationInfo]", ex); } finally { endProsess(conn, psmt, null, null); } return ret; }
Code Sample 2:
private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } }
|
00
|
Code Sample 1:
public String getContent(URL url) { Logger.getLogger(this.getClass().getName()).log(Level.INFO, "getting content from " + url.toString()); String content = ""; try { URLConnection httpc; httpc = url.openConnection(); httpc.setDoInput(true); httpc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(httpc.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { content = content + line; } in.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Problem writing to " + url, e); } return content; }
Code Sample 2:
public static String md5sum(String s, String alg) { try { MessageDigest md = MessageDigest.getInstance(alg); md.update(s.getBytes(), 0, s.length()); StringBuffer sb = new StringBuffer(); synchronized (sb) { for (byte b : md.digest()) sb.append(pad(Integer.toHexString(0xFF & b), ZERO.charAt(0), 2, true)); } return sb.toString(); } catch (Exception ex) { log(ex); } return null; }
|
00
|
Code Sample 1:
public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); }
Code Sample 2:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
|
11
|
Code Sample 1:
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(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.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 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 @Transactional public FileData store(FileData data, InputStream stream) { try { FileData file = save(data); file.setPath(file.getGroup() + File.separator + file.getId()); file = save(file); File folder = new File(PATH, file.getGroup()); if (!folder.exists()) folder.mkdirs(); File filename = new File(folder, file.getId() + ""); IOUtils.copyLarge(stream, new FileOutputStream(filename)); return file; } catch (IOException e) { throw new ServiceException("storage", e); } }
Code Sample 2:
public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
|
00
|
Code Sample 1:
private InputStream openConnection(URL url) throws IOException, DODSException { connection = url.openConnection(); if (acceptDeflate) connection.setRequestProperty("Accept-Encoding", "deflate"); connection.connect(); InputStream is = null; int retry = 1; long backoff = 100L; while (true) { try { is = connection.getInputStream(); break; } catch (NullPointerException e) { System.out.println("DConnect NullPointer; retry open (" + retry + ") " + url); try { Thread.currentThread().sleep(backoff); } catch (InterruptedException ie) { } } catch (FileNotFoundException e) { System.out.println("DConnect FileNotFound; retry open (" + retry + ") " + url); try { Thread.currentThread().sleep(backoff); } catch (InterruptedException ie) { } } if (retry == 3) throw new DODSException("Connection cannot be opened"); retry++; backoff *= 2; } String type = connection.getHeaderField("content-description"); handleContentDesc(is, type); ver = new ServerVersion(connection.getHeaderField("xdods-server")); String encoding = connection.getContentEncoding(); return handleContentEncoding(is, encoding); }
Code Sample 2:
public String getContents(String fileUri) throws IOException { StringBuffer contents = new StringBuffer(); if (fileUri != null && !fileUri.equals("")) { BufferedReader input = null; try { LOG.info("Reading:" + fileUri); URL url = getClass().getClassLoader().getResource(fileUri); if (url != null) { InputStream stream = url.openStream(); input = new BufferedReader(new InputStreamReader(stream)); appendInputToContents(input, contents); } else { LOG.error("Unable to locate file:" + fileUri + " in directory " + new File(".").getAbsolutePath()); } } finally { if (input != null) { input.close(); } } } return contents.toString(); }
|
11
|
Code Sample 1:
@Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); if (remainingsize >= splitsize) { in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; } else { in.transferTo(pos, remainingsize, out); } pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
Code Sample 2:
private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
|
11
|
Code Sample 1:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
Code Sample 2:
@Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("sort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("sort :: INPATH not given."); return 3; } final String wrkDir = args.get(0), out = (String) parser.getOptionValue(outputFileOpt); final List<String> strInputs = args.subList(1, args.size()); final List<Path> inputs = new ArrayList<Path>(strInputs.size()); for (final String in : strInputs) inputs.add(new Path(in)); final boolean verbose = parser.getBoolean(verboseOpt); final String intermediateOutName = out == null ? inputs.get(0).getName() : out; final Configuration conf = getConf(); conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0])); conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName); final Path wrkDirPath = new Path(wrkDir); final Timer t = new Timer(); try { for (final Path in : inputs) Utils.configureSampling(in, conf); @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = new Job(conf); job.setJarByClass(Sort.class); job.setMapperClass(Mapper.class); job.setReducerClass(SortReducer.class); job.setMapOutputKeyClass(LongWritable.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(SAMRecordWritable.class); job.setInputFormatClass(BAMInputFormat.class); job.setOutputFormatClass(SortOutputFormat.class); for (final Path in : inputs) FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, wrkDirPath); job.setPartitionerClass(TotalOrderPartitioner.class); System.out.println("sort :: Sampling..."); t.start(); InputSampler.<LongWritable, SAMRecordWritable>writePartitionFile(job, new InputSampler.IntervalSampler<LongWritable, SAMRecordWritable>(0.01, 100)); System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms()); job.submit(); System.out.println("sort :: Waiting for job completion..."); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("sort :: Job failed."); return 4; } System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("sort :: Merging output..."); t.start(); final Path outPath = new Path(out); final FileSystem srcFS = wrkDirPath.getFileSystem(conf); FileSystem dstFS = outPath.getFileSystem(conf); if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem) dstFS).getRaw(); final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File("")); w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true); w.setHeader(getHeaderMerger(conf).getMergedHeader()); w.close(); final OutputStream outs = dstFS.append(outPath); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Output merging failed: %s\n", e); return 5; } return 0; }
|
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:
private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
|
11
|
Code Sample 1:
private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; }
Code Sample 2:
public boolean open(String mode) { if (source instanceof String) return false; else if (mode == null) mode = ""; else mode = mode.toLowerCase(); boolean toread = false, towrite = false; if (mode.indexOf("r") >= 0) toread = true; if (mode.indexOf("w") >= 0) towrite = true; if (!toread && !towrite) toread = towrite = true; try { if (toread && input == null) { if (isDirectory()) return true; else if (reader != null) return true; else if (source instanceof File) input = new FileInputStream((File) source); else if (source instanceof Socket) input = ((Socket) source).getInputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } if (towrite && output == null) { if (isDirectory()) return false; else if (writer != null) return true; else if (source instanceof File) output = new FileOutputStream((File) source); else if (source instanceof Socket) output = ((Socket) source).getOutputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } return true; } catch (Exception e) { return false; } }
|
00
|
Code Sample 1:
private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } }
Code Sample 2:
public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } }
|
00
|
Code Sample 1:
public void mode(String env) { String path = this.envs.get(env); InputStream in = null; try { URL url = ResourceUtil.getResourceNoException(path); if (url == null) { throw new IllegalEnvironmentException(env); } load(URLUtil.openStream(url)); } catch (IOException e) { throw new IllegalEnvironmentException(env, e); } finally { StreamUtil.close(in); } }
Code Sample 2:
public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
|
00
|
Code Sample 1:
public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "[email protected]", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); }
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 echo(HttpRequest request, HttpResponse response) throws IOException { InputStream in = request.getInputStream(); if ("gzip".equals(request.getField("Content-Encoding"))) { in = new GZIPInputStream(in); } IOUtils.copy(in, response.getOutputStream()); }
Code Sample 2:
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw e; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw e; } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
00
|
Code Sample 1:
public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
public static void copyFile(File in, File out, long maxCount) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); if (maxCount == 0) maxCount = sourceChannel.size(); try { final long size = sourceChannel.size(); long position = 0; while (position < size) { position += sourceChannel.transferTo(position, maxCount, destinationChannel); } } finally { sourceChannel.close(); destinationChannel.close(); } }
|
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 void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
11
|
Code Sample 1:
private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } }
Code Sample 2:
private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
|
00
|
Code Sample 1:
private void sendToURL(String URL, String file) throws Exception { URL url = new URL(URL); InputStream is = new BufferedInputStream(new FileInputStream(file)); OutputStream os = url.openConnection().getOutputStream(); copyDocument(is, os); is.close(); os.close(); }
Code Sample 2:
public boolean download(String address, String localFileName) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } return true; } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return false; }
|
00
|
Code Sample 1:
public static String encryptStringWithSHA2(String input) { String output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(input.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } output = sb.toString(); return output; }
Code Sample 2:
private void downloadFile(String name, URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); int expectedSize = conn.getContentLength(); progressPanel.downloadStarting(name, expectedSize == -1); int downloaded = 0; byte[] buf = new byte[1024]; int length; in = conn.getInputStream(); out = new FileOutputStream(file); while ((in != null) && ((length = in.read(buf)) != -1)) { downloaded += length; out.write(buf, 0, length); if (expectedSize != -1) progressPanel.downloadProgress((downloaded * 100) / expectedSize); } out.flush(); } finally { progressPanel.downloadFinished(); if (out != null) out.close(); if (in != null) in.close(); } }
|
11
|
Code Sample 1:
private void update() throws IOException { FileOutputStream out = new FileOutputStream(combined); try { File[] _files = listJavascript(); List<File> files = new ArrayList<File>(Arrays.asList(_files)); files.add(0, new File(jsdir.getAbsolutePath() + "/leemba.js")); files.add(0, new File(jsdir.getAbsolutePath() + "/jquery.min.js")); for (File js : files) { FileInputStream fin = null; try { int count = 0; byte buf[] = new byte[16384]; fin = new FileInputStream(js); while ((count = fin.read(buf)) > 0) out.write(buf, 0, count); } catch (Throwable t) { log.error("Failed to read file: " + js.getAbsolutePath(), t); } finally { if (fin != null) fin.close(); } } } finally { out.close(); } }
Code Sample 2:
public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
|
00
|
Code Sample 1:
public ByteArrayOutputStream download(final String contentUuid) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } inputStream.close(); return outputStream; } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static void loadPackage1(String ycCode) { InputStream input = null; try { TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new FakeHostnameVerifier()); uc.setConnectTimeout(CONNECTION_TIMEOUT); uc.setReadTimeout(CONNECTION_TIMEOUT); input = uc.getInputStream(); StringBuilder sb = new StringBuilder(); int c; while ((c = input.read()) != -1) { sb.append((char) c); } Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString()); String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml"; YouthClub.getMiniModel().getXMLParser().writeXML(doc, target); Debug.log("YC XML saved to " + target); } catch (Exception e) { Debug.logException(e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void run() { if (software == null) return; Jvm.hashtable(HKEY).put(software, this); try { software.setException(null); software.setDownloaded(false); software.setDownloadStartTime(System.currentTimeMillis()); try { software.downloadStarted(); } catch (Exception dsx) { } if (software.getDownloadDir() == null) { software.setException(new Exception("The DownloadDir is null.")); software.setDownloadStartTime(0); software.setDownloaded(false); throw software.getException(); } URL url = new URL(software.getURL()); URLConnection con = url.openConnection(); software.setDownloadLength(con.getContentLength()); inputStream = con.getInputStream(); File file = new File(software.getDownloadDir(), software.getURLFilename()); outputStream = new FileOutputStream(file); int totalBytes = 0; byte[] buffer = new byte[8192]; while (!cancelled) { int bytesRead = Jvm.copyPartialStream(inputStream, outputStream, buffer); if (bytesRead == -1) break; totalBytes += bytesRead; try { software.downloadProgress(totalBytes); } catch (Exception dx) { } } if (!cancelled) software.setDownloaded(true); } catch (Exception x) { software.setException(x); software.setDownloadStartTime(0); software.setDownloaded(false); } try { software.downloadComplete(); } catch (Exception dcx) { } Jvm.hashtable(HKEY).remove(software); closeStreams(); }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
|
00
|
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:
private Properties loadPropertiesFromURL(String propertiesURL, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); URL url; try { url = new URL(propertiesURL); URLConnection urlConnection = url.openConnection(); properties.load(urlConnection.getInputStream()); } catch (MalformedURLException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } return properties; }
|
00
|
Code Sample 1:
public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException { if (localFile.isFile()) { long localContentLength = localFile.length(); long localLastModified = localFile.lastModified() / 1000; long contentLength = -1; long lastModified = -1; HttpClient httpclient = createHttpClient(creds); try { HttpHead httphead = new HttpHead(url); HttpResponse response = httpclient.execute(httphead); if (response != null) { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000; } catch (ParseException e) { logger.error(e); } } } else { return true; } } } finally { httpclient.getConnectionManager().shutdown(); } if (logger.isDebugEnabled()) { logger.debug("local:" + localContentLength + " " + localLastModified); logger.debug("remote:" + contentLength + " " + lastModified); } if (contentLength != -1 && localContentLength != contentLength) return false; if (lastModified != -1 && lastModified != localLastModified) return false; if (contentLength == -1 && lastModified == -1) return false; return true; } return false; }
Code Sample 2:
public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
|
00
|
Code Sample 1:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
Code Sample 2:
private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } }
|
11
|
Code Sample 1:
public void sortPlayersTurn() { Token tempT = new Token(); Player tempP = new Player("test name", tempT); int tempN = 0; boolean exchangeMade = true; for (int i = 0; i < playerNum - 1 && exchangeMade; i++) { exchangeMade = false; for (int j = 0; j < playerNum - 1 - i; j++) { if (diceSum[j] < diceSum[j + 1]) { tempP = players[j]; tempN = diceSum[j]; players[j] = players[j + 1]; diceSum[j] = diceSum[j + 1]; players[j + 1] = tempP; diceSum[j + 1] = tempN; exchangeMade = true; } } } }
Code Sample 2:
private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } }
|
11
|
Code Sample 1:
public IUserProfile getUserProfile(String profileID) throws MM4UUserProfileNotFoundException { SimpleUserProfile tempProfile = null; String tempProfileString = this.profileURI + profileID + FILE_SUFFIX; try { URL url = new URL(tempProfileString); Debug.println("Retrieve profile with ID: " + url); tempProfile = new SimpleUserProfile(); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; tempProfile.add("id", profileID); while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempProfile.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); } catch (MalformedURLException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } catch (IOException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } return tempProfile; }
Code Sample 2:
public String readLines() { StringBuffer lines = new StringBuffer(); try { int HttpResult; URL url = new URL(address); URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { System.out.println("�����ӵ�" + address); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); while (true) { String line = reader.readLine(); if (line == null) break; lines.append(line + "\r\n"); } reader.close(); } } catch (Exception e) { e.printStackTrace(); } return lines.toString(); }
|
00
|
Code Sample 1:
public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; }
|
11
|
Code Sample 1:
public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } }
Code Sample 2:
public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
|
11
|
Code Sample 1:
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(); } } } } } } } }
Code Sample 2:
public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } }
|
11
|
Code Sample 1:
public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } }
Code Sample 2:
private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; }
|
00
|
Code Sample 1:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } }
Code Sample 2:
public 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); }
|
00
|
Code Sample 1:
public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
|
00
|
Code Sample 1:
public synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException { PreparedStatement preStat = null; StringBuffer sqlStat = new StringBuffer(); MailSetting tmpMailSetting = (MailSetting) ((MailSetting) obj).clone(); synchronized (dbConn) { try { Integer nextID = getNextPrimaryID(); Timestamp currTime = Utility.getCurrentTimestamp(); sqlStat.append("INSERT "); sqlStat.append("INTO MAIL_SETTING(ID, USER_RECORD_ID, PROFILE_NAME, MAIL_SERVER_TYPE, DISPLAY_NAME, EMAIL_ADDRESS, REMEMBER_PWD_FLAG, SPA_LOGIN_FLAG, INCOMING_SERVER_HOST, INCOMING_SERVER_PORT, INCOMING_SERVER_LOGIN_NAME, INCOMING_SERVER_LOGIN_PWD, OUTGOING_SERVER_HOST, OUTGOING_SERVER_PORT, OUTGOING_SERVER_LOGIN_NAME, OUTGOING_SERVER_LOGIN_PWD, PARAMETER_1, PARAMETER_2, PARAMETER_3, PARAMETER_4, PARAMETER_5, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) "); sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "); preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); setPrepareStatement(preStat, 1, nextID); setPrepareStatement(preStat, 2, tmpMailSetting.getUserRecordID()); setPrepareStatement(preStat, 3, tmpMailSetting.getProfileName()); setPrepareStatement(preStat, 4, tmpMailSetting.getMailServerType()); setPrepareStatement(preStat, 5, tmpMailSetting.getDisplayName()); setPrepareStatement(preStat, 6, tmpMailSetting.getEmailAddress()); setPrepareStatement(preStat, 7, tmpMailSetting.getRememberPwdFlag()); setPrepareStatement(preStat, 8, tmpMailSetting.getSpaLoginFlag()); setPrepareStatement(preStat, 9, tmpMailSetting.getIncomingServerHost()); setPrepareStatement(preStat, 10, tmpMailSetting.getIncomingServerPort()); setPrepareStatement(preStat, 11, tmpMailSetting.getIncomingServerLoginName()); setPrepareStatement(preStat, 12, tmpMailSetting.getIncomingServerLoginPwd()); setPrepareStatement(preStat, 13, tmpMailSetting.getOutgoingServerHost()); setPrepareStatement(preStat, 14, tmpMailSetting.getOutgoingServerPort()); setPrepareStatement(preStat, 15, tmpMailSetting.getOutgoingServerLoginName()); setPrepareStatement(preStat, 16, tmpMailSetting.getOutgoingServerLoginPwd()); setPrepareStatement(preStat, 17, tmpMailSetting.getParameter1()); setPrepareStatement(preStat, 18, tmpMailSetting.getParameter2()); setPrepareStatement(preStat, 19, tmpMailSetting.getParameter3()); setPrepareStatement(preStat, 20, tmpMailSetting.getParameter4()); setPrepareStatement(preStat, 21, tmpMailSetting.getParameter5()); setPrepareStatement(preStat, 22, GlobalConstant.RECORD_STATUS_ACTIVE); setPrepareStatement(preStat, 23, new Integer(0)); setPrepareStatement(preStat, 24, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 25, currTime); setPrepareStatement(preStat, 26, sessionContainer.getUserRecordID()); setPrepareStatement(preStat, 27, currTime); preStat.executeUpdate(); tmpMailSetting.setID(nextID); tmpMailSetting.setCreatorID(sessionContainer.getUserRecordID()); tmpMailSetting.setCreateDate(currTime); tmpMailSetting.setUpdaterID(sessionContainer.getUserRecordID()); tmpMailSetting.setUpdateDate(currTime); tmpMailSetting.setUpdateCount(new Integer(0)); tmpMailSetting.setCreatorName(UserInfoFactory.getUserFullName(tmpMailSetting.getCreatorID())); tmpMailSetting.setUpdaterName(UserInfoFactory.getUserFullName(tmpMailSetting.getUpdaterID())); dbConn.commit(); return (tmpMailSetting); } catch (SQLException sqle) { log.error(sqle, sqle); } catch (Exception e) { try { dbConn.rollback(); } catch (Exception ex) { } log.error(e, e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } return null; } }
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 void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
Code Sample 2:
public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static ArrayList<String> remoteCall(Map<String, String> dataDict) { ArrayList<String> result = new ArrayList<String>(); String encodedData = ""; for (String key : dataDict.keySet()) { String encodedSegment = ""; String value = dataDict.get(key); if (value == null) continue; try { encodedSegment = key + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encodedData.length() > 0) { encodedData += "&"; } encodedData += encodedSegment; } try { URL url = new URL(baseURL + encodedData); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.add(line); System.out.println("GOT: " + line); } reader.close(); result.remove(0); if (result.size() != 0) { if (!result.get(result.size() - 1).equals("DONE")) { result.clear(); } else { result.remove(result.size() - 1); } } } catch (MalformedURLException e) { } catch (IOException e) { } return result; }
|
11
|
Code Sample 1:
public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; }
Code Sample 2:
private static String md5Encode(String pass) { String string; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); string = bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La libreria java.security no implemente MD5"); } return string; }
|
11
|
Code Sample 1:
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
Code Sample 2:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
|
11
|
Code Sample 1:
public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
|
11
|
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:
private static void copySmallFile(File sourceFile, File targetFile) throws BusinessException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new BusinessException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to '" + targetFile.getAbsolutePath() + "'!", e); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LOG.error("Could not close input stream!", e); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LOG.error("Could not close output stream!", e); } } }
|
00
|
Code Sample 1:
public static Vector<String> readFileFromURL(URL url) { Vector<String> text = new Vector<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { text.add(line); } in.close(); } catch (Exception e) { return null; } return text; }
Code Sample 2:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
00
|
Code Sample 1:
private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } }
Code Sample 2:
private static void loadPluginsFromClassLoader(ClassLoader classLoader) throws IOException { Enumeration res = classLoader.getResources("META-INF/services/" + GDSFactoryPlugin.class.getName()); while (res.hasMoreElements()) { URL url = (URL) res.nextElement(); InputStreamReader rin = new InputStreamReader(url.openStream()); BufferedReader bin = new BufferedReader(rin); while (bin.ready()) { String className = bin.readLine(); try { Class clazz = Class.forName(className); GDSFactoryPlugin plugin = (GDSFactoryPlugin) clazz.newInstance(); registerPlugin(plugin); } catch (ClassNotFoundException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (IllegalAccessException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } catch (InstantiationException ex) { if (log != null) log.error("Can't register plugin" + className, ex); } } } }
|
00
|
Code Sample 1:
private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; }
Code Sample 2:
public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
|
00
|
Code Sample 1:
protected BufferedImage handleICCException() { if (params.uri.startsWith("http://vacani.icc.cat") || params.uri.startsWith("http://louisdl.louislibraries.org")) try { params.uri = params.uri.replace("cdm4/item_viewer.php", "cgi-bin/getimage.exe") + "&DMSCALE=3"; params.uri = params.uri.replace("/u?", "cgi-bin/getimage.exe?CISOROOT=").replace(",", "&CISOPTR=") + "&DMSCALE=3"; URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
Code Sample 2:
public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public void setInternalReferences() { for (int i = 0; i < REFSPECS.length; i++) { REFSPECS[i].setTypeRefs(conn); } String sql, sql2; try { String[][] params2 = { { "PACKAGE", "name" }, { "CLASSTYPE", "qualifiedname" }, { "MEMBER", "qualifiedname" }, { "EXECMEMBER", "fullyqualifiedname" } }; for (int i = 0; i < params2.length; i++) { log.traceln("\tProcessing seetag " + params2[i][0] + " references.."); sql = "select r.sourcedoc_id, " + params2[i][0] + ".id, " + params2[i][0] + "." + params2[i][1] + " from REFERENCE r, " + params2[i][0] + " where r.refdoc_name = " + params2[i][0] + "." + params2[i][1] + " and r.refdoc_id is null"; Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); sql2 = "update REFERENCE set refdoc_id=? where sourcedoc_id=? and refdoc_name=?"; PreparedStatement pstmt = conn.prepareStatement(sql2); while (rset.next()) { pstmt.clearParameters(); pstmt.setInt(1, rset.getInt(2)); pstmt.setInt(2, rset.getInt(1)); pstmt.setString(3, rset.getString(3)); pstmt.executeUpdate(); } pstmt.close(); rset.close(); stmt.close(); conn.commit(); } } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
Code Sample 2:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
|
00
|
Code Sample 1:
public StringBuffer getReturn(String url_address) { StringBuffer message = new StringBuffer(); try { URL url = new URL(url_address); try { HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.connect(); InputStreamReader insr = new InputStreamReader(httpConnection.getInputStream()); BufferedReader in = new BufferedReader(insr); String temp = in.readLine(); while (temp != null) { message.append(temp + "\n"); temp = in.readLine(); } in.close(); } catch (IOException e) { System.out.println("httpConnecter:Error[" + e + "]"); message.append("Connect error [" + url_address + "]"); } } catch (MalformedURLException e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } catch (Exception e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } return message; }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
|
00
|
Code Sample 1:
public static String descripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "descripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "descripta(String)"); } }
Code Sample 2:
@Override public void exec() { BufferedReader in = null; try { URL url = new URL(getUrl()); in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer result = new StringBuffer(); String str; while ((str = in.readLine()) != null) { result.append(str); } logger.info("received message: " + result); } catch (Exception e) { logger.error("HttpGetEvent could not execute", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error("BufferedReader could not be closed", e); } } } }
|
11
|
Code Sample 1:
public void run() { try { IOUtils.copy(is, os); os.flush(); } catch (IOException ioe) { logger.error("Unable to copy", ioe); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
Code Sample 2:
public static void copyFile(final File source, final File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
|
11
|
Code Sample 1:
public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a> "); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } }
Code Sample 2:
@Test public void testCopyOverSize() throws IOException { final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(TEST_DATA.length); final int cpySize = ExtraIOUtils.copy(in, out, TEST_DATA.length + Long.SIZE); assertEquals("Mismatched copy size", TEST_DATA.length, cpySize); final byte[] outArray = out.toByteArray(); assertArrayEquals("Mismatched data", TEST_DATA, outArray); }
|
00
|
Code Sample 1:
@Override public final boolean save() throws RecordException, RecordValidationException, RecordValidationSyntax { if (frozen) { throw new RecordException("The object is frozen."); } boolean toReturn = false; Class<? extends Record> actualClass = this.getClass(); HashMap<String, Integer> columns = getColumns(TableNameResolver.getTableName(actualClass)); Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; try { if (exists()) { doValidations(true); StatementBuilder builder = new StatementBuilder("update " + TableNameResolver.getTableName(actualClass) + " set"); String updates = ""; for (String key : columns.keySet()) { if (!key.equals("id")) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } updates += key + " = :" + key + ", "; builder.set(key, FieldHandler.getValue(f, this)); } } builder.append(updates.substring(0, updates.length() - 2)); builder.append("where id = :id"); builder.set(":id", FieldHandler.getValue(FieldHandler.findField(actualClass, "id"), this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } else { doValidations(false); StatementBuilder builder = new StatementBuilder("insert into " + TableNameResolver.getTableName(actualClass) + " "); String names = ""; String values = ""; for (String key : columns.keySet()) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } if (key.equals("id") && (Integer) FieldHandler.getValue(f, this) == 0) { continue; } names += key + ", "; values += ":" + key + ", "; builder.set(key, f.get(this)); } names = names.substring(0, names.length() - 2); values = values.substring(0, values.length() - 2); builder.append("(" + names + ")"); builder.append("values"); builder.append("(" + values + ")"); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } if (childList != null) { if (childObjects == null) { childObjects = new HashMap<Class<? extends Record>, Record>(); } for (Class<? extends Record> c : childList.keySet()) { if (childObjects.get(c) != null) { childObjects.get(c).save(); } } } if (childrenList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : childrenList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } if (relatedList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : relatedList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } return toReturn; } catch (Exception e) { if (e instanceof RecordValidationException) { throw (RecordValidationException) e; } if (e instanceof RecordValidationSyntax) { throw (RecordValidationSyntax) e; } try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
Code Sample 2:
static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } }
|
00
|
Code Sample 1:
public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
Code Sample 2:
@Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
private void writeResponse(final Collection<? extends Resource> resources, final HttpServletResponse response) throws IOException { for (final Resource resource : resources) { InputStream in = null; try { in = resource.getInputStream(); final OutputStream out = response.getOutputStream(); final long bytesCopied = IOUtils.copyLarge(in, out); if (bytesCopied < 0L) throw new StreamCorruptedException("Bad number of copied bytes (" + bytesCopied + ") for resource=" + resource.getFilename()); if (logger.isDebugEnabled()) logger.debug("writeResponse(" + resource.getFile() + ") copied " + bytesCopied + " bytes"); } finally { if (in != null) in.close(); } } }
|
11
|
Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
11
|
Code Sample 1:
@Test public void testDocumentDownloadKnowledgeBase() throws IOException { if (uploadedKbDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateTextDownloadLink(uploadedKbDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } }
Code Sample 2:
public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.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 int download() { FTPClient client = null; URL url = null; try { client = new FTPClient(); url = new URL(ratingsUrl); if (log.isDebugEnabled()) log.debug("Downloading " + url); client.connect(url.getHost()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { if (log.isErrorEnabled()) log.error("Connection to " + url + " refused"); return RESULT_CONNECTION_REFUSED; } if (log.isDebugEnabled()) log.debug("Logging in l:" + getUserName() + " p:" + getPassword()); client.login(getUserName(), getPassword()); client.changeWorkingDirectory(url.getPath()); FTPFile[] files = client.listFiles(url.getPath()); if ((files == null) || (files.length != 1)) throw new FileNotFoundException("No remote file"); FTPFile remote = files[0]; if (log.isDebugEnabled()) log.debug("Remote file data: " + remote); File local = new File(getOutputFile()); if (local.exists()) { if ((local.lastModified() == remote.getTimestamp().getTimeInMillis())) { if (log.isDebugEnabled()) log.debug("File " + local.getAbsolutePath() + " is not changed on the server"); return RESULT_NO_NEW_FILE; } } if (log.isDebugEnabled()) log.debug("Setting binary transfer modes"); client.mode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); OutputStream fos = new FileOutputStream(local); boolean result = client.retrieveFile(url.getPath(), fos); if (log.isDebugEnabled()) log.debug("The transfer result is :" + result); fos.flush(); fos.close(); local.setLastModified(remote.getTimestamp().getTimeInMillis()); if (result) uncompress(); if (result) return RESULT_OK; else return RESULT_TRANSFER_ERROR; } catch (MalformedURLException e) { return RESULT_ERROR; } catch (SocketException e) { return RESULT_ERROR; } catch (FileNotFoundException e) { return RESULT_ERROR; } catch (IOException e) { return RESULT_ERROR; } finally { if (client != null) { try { if (log.isDebugEnabled()) log.debug("Logging out"); client.logout(); } catch (Exception e) { } try { if (log.isDebugEnabled()) log.debug("Disconnecting"); client.disconnect(); } catch (Exception e) { } } } }
|
11
|
Code Sample 1:
public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; }
Code Sample 2:
private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } }
|
00
|
Code Sample 1:
private boolean load(URL url) { try { URLConnection connection = url.openConnection(); parser = new PDFParser(connection.getInputStream()); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public static String getMD5(String... list) { if (list.length == 0) return null; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); for (String in : list) md.update(in.getBytes()); byte[] digest = md.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { String hex = Integer.toHexString(0xFF & digest[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
|
11
|
Code Sample 1:
private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
Code Sample 2:
private 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:
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:
private void zip(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
|
00
|
Code Sample 1:
public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } }
Code Sample 2:
protected void syncMessages(Message message) { if (message.getEvent() == Event.CONNECT || message.getEvent() == Event.SYNC_DONE) return; logger.info(String.format("remove stale replication messages: %s", message.toString())); String className = ""; long classId = 0; if (message.getBody() instanceof Entity) { Entity entity = (Entity) message.getBody(); className = entity.getClass().getName(); classId = entity.getId(); } ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) portalDao.getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement("delete from light_replication_message where event=? and className=? and classId=?"); ps.setString(1, message.getEvent().toString()); ps.setString(2, className); ps.setLong(3, classId); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { try { conn.rollback(); ps.close(); conn.close(); } catch (Exception se) { } } }
|
11
|
Code Sample 1:
public void saveDownloadFiles(List downloadFiles) throws SQLException { Connection conn = AppLayerDatabase.getInstance().getPooledConnection(); try { conn.setAutoCommit(false); Statement s = conn.createStatement(); s.executeUpdate("DELETE FROM DOWNLOADFILES"); s.close(); s = null; PreparedStatement ps = conn.prepareStatement("INSERT INTO DOWNLOADFILES " + "(name,targetpath,size,fnkey,enabled,state,downloadaddedtime,downloadstartedtime,downloadfinishedtime," + "retries,lastdownloadstoptime,gqid,filelistfilesha) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); for (Iterator i = downloadFiles.iterator(); i.hasNext(); ) { FrostDownloadItem dlItem = (FrostDownloadItem) i.next(); int ix = 1; ps.setString(ix++, dlItem.getFilename()); ps.setString(ix++, dlItem.getTargetPath()); ps.setLong(ix++, (dlItem.getFileSize() == null ? 0 : dlItem.getFileSize().longValue())); ps.setString(ix++, dlItem.getKey()); ps.setBoolean(ix++, (dlItem.isEnabled() == null ? true : dlItem.isEnabled().booleanValue())); ps.setInt(ix++, dlItem.getState()); ps.setLong(ix++, dlItem.getDownloadAddedTime()); ps.setLong(ix++, dlItem.getDownloadStartedTime()); ps.setLong(ix++, dlItem.getDownloadFinishedTime()); ps.setInt(ix++, dlItem.getRetries()); ps.setLong(ix++, dlItem.getLastDownloadStopTime()); ps.setString(ix++, dlItem.getGqIdentifier()); ps.setString(ix++, dlItem.getFileListFileObject() == null ? null : dlItem.getFileListFileObject().getSha()); ps.executeUpdate(); } ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (Throwable t) { logger.log(Level.SEVERE, "Exception during save", t); try { conn.rollback(); } catch (Throwable t1) { logger.log(Level.SEVERE, "Exception during rollback", t1); } try { conn.setAutoCommit(true); } catch (Throwable t1) { } } finally { AppLayerDatabase.getInstance().givePooledConnection(conn); } }
Code Sample 2:
public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } }
|
00
|
Code Sample 1:
public String selectFROM() throws Exception { BufferedReader in = null; String data = null; try { HttpClient httpclient = new DefaultHttpClient(); URI uri = new URI("http://**.**.**.**/OctopusManager/index2.php"); HttpGet request = new HttpGet(); request.setURI(uri); HttpResponse httpresponse = httpclient.execute(request); HttpEntity httpentity = httpresponse.getEntity(); in = new BufferedReader(new InputStreamReader(httpentity.getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
Code Sample 2:
public void openJadFile(URL url) { try { setStatusBar("Loading..."); jad.clear(); jad.load(url.openStream()); loadFromJad(url); } catch (FileNotFoundException ex) { System.err.println("Cannot found " + url.getPath()); } catch (NullPointerException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IllegalArgumentException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IOException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } }
|
00
|
Code Sample 1:
public static final byte[] getHttpStream(final String uri) { URL url; try { url = new URL(uri); } catch (Exception e) { return null; } InputStream is = null; try { is = url.openStream(); } catch (Exception e) { return null; } ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] arrayByte = null; try { arrayByte = new byte[4096]; int read; while ((read = is.read(arrayByte)) >= 0) { os.write(arrayByte, 0, read); } arrayByte = os.toByteArray(); } catch (IOException e) { return null; } finally { try { if (os != null) { os.close(); os = null; } if (is != null) { is.close(); is = null; } } catch (IOException e) { } } return arrayByte; }
Code Sample 2:
private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
|
11
|
Code Sample 1:
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.