label
int64 0
1
| func1
stringlengths 173
53.1k
| func2
stringlengths 173
53.1k
| id
int64 0
901k
|
---|---|---|---|
0 | public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } } | private ArrayList<String> getFiles(String date) { ArrayList<String> files = new ArrayList<String>(); String info = ""; try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS + date + "/"); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf(".bz2"); if (pos != -1) { token = token.substring(1, pos + 4); files.add(token); } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return files; } | 900,400 |
0 | private ByteBuffer getByteBuffer(String resource) throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream in = classLoader.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); return ByteBuffer.wrap(out.toByteArray()); } | private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } | 900,401 |
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) { } } } } | public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; } | 900,402 |
0 | public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } | private synchronized jdbcResultSet executeHTTP(String s) throws SQLException { byte result[]; try { URL url = new URL(sConnect); String p = StringConverter.unicodeToHexString(sUser); p += "+" + StringConverter.unicodeToHexString(sPassword); p += "+" + StringConverter.unicodeToHexString(s); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStream os = c.getOutputStream(); os.write(p.getBytes(ENCODING)); os.close(); c.connect(); InputStream is = (InputStream) c.getContent(); BufferedInputStream in = new BufferedInputStream(is); int len = c.getContentLength(); result = new byte[len]; for (int i = 0; i < len; i++) { int r = in.read(); result[i] = (byte) r; } } catch (Exception e) { throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage()); } return new jdbcResultSet(new Result(result)); } | 900,403 |
0 | public void run() { try { if (useStream || inputStream != null) { InputStream inputStream = null; if (LoadDocumentOperation.this.inputStream != null) inputStream = LoadDocumentOperation.this.inputStream; else inputStream = url.openStream(); if (frame != null) document = officeApplication.getDocumentService().loadDocument(frame, inputStream, documentDescriptor); else document = officeApplication.getDocumentService().loadDocument(inputStream, documentDescriptor); try { inputStream.close(); } catch (Throwable throwable) { } } else { if (frame != null) document = officeApplication.getDocumentService().loadDocument(frame, url.toString(), documentDescriptor); else document = officeApplication.getDocumentService().loadDocument(url.toString(), documentDescriptor); } done = true; } catch (Exception exception) { this.exception = exception; } catch (ThreadDeath threadDeath) { } } | public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } | 900,404 |
1 | public static void copy(File source, 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(); } } | public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); } | 900,405 |
1 | public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; } | private String md5(String txt) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(txt.getBytes(), 0, txt.length()); return new BigInteger(1, m.digest()).toString(16); } catch (Exception e) { return "BAD MD5"; } } | 900,406 |
1 | public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } } | private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); } | 900,407 |
0 | public static Map<VariableLengthInteger, ElementDescriptor> readDescriptors(URL url) throws IOException, XMLStreamException { if (url == null) { throw new IllegalArgumentException("url is null"); } InputStream stream = new BufferedInputStream(url.openStream()); try { return readDescriptors(stream); } finally { try { stream.close(); } catch (IOException ignored) { } } } | protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); } | 900,408 |
1 | public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); } | private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); } | 900,409 |
1 | public static void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); } | public static void copy(String from, String to) throws Exception { File inputFile = new File(from); File outputFile = new File(to); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } | 900,410 |
0 | public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } } | public byte[] pipeBytes() { byte ba[] = null; try { URL url = new URL(server); conn = (HttpURLConnection) url.openConnection(); InputStream is = conn.getInputStream(); ByteArrayOutputStream tout = new ByteArrayOutputStream(); int nmax = 10000; byte b[] = new byte[nmax + 1]; int nread = 0; while ((nread = is.read(b, 0, nmax)) >= 0) tout.write(b, 0, nread); ba = tout.toByteArray(); } catch (Exception ex) { System.err.println(ex); } return ba; } | 900,411 |
0 | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | public static StringBuffer getCachedFile(String url) throws Exception { File urlCache = new File("tmp-cache/" + url.replace('/', '-')); new File("tmp-cache/").mkdir(); if (urlCache.exists()) { BufferedReader in = new BufferedReader(new FileReader(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); } in.close(); return buffer; } else { URL url2 = new URL(url.replace(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream())); BufferedWriter cacheWriter = new BufferedWriter(new FileWriter(urlCache)); StringBuffer buffer = new StringBuffer(); String input; while ((input = in.readLine()) != null) { buffer.append(input + "\n"); cacheWriter.write(input + "\n"); } cacheWriter.close(); in.close(); return buffer; } } | 900,412 |
1 | public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } | 900,413 |
1 | public static String extractIconPath(String siteURL) throws IOException { siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String iconPath = null; String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; break; } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); siteURL = getHome(siteURL); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = siteURL; if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); } catch (Exception e) { } return iconPath; } | public static String getTextFileFromURL(String urlName) { try { StringBuffer textFile = new StringBuffer(""); String line = null; URL url = new URL(urlName); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) textFile = textFile.append(line + "\n"); reader.close(); return textFile.toString(); } catch (Exception e) { Debug.signal(Debug.ERROR, null, "Failed to open " + urlName + ", exception " + e); return null; } } | 900,414 |
1 | public static void main(String[] args) throws IOException { ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov"))); Movie movie = MovieCreator.build(in); in.close(); List<Track> tracks = movie.getTracks(); movie.setTracks(new LinkedList<Track>()); double startTime = 35.000; double endTime = 145.000; boolean timeCorrected = false; for (Track track : tracks) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (timeCorrected) { throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); } startTime = correctTimeToNextSyncSample(track, startTime); endTime = correctTimeToNextSyncSample(track, endTime); timeCorrected = true; } } for (Track track : tracks) { long currentSample = 0; double currentTime = 0; long startSample = -1; long endSample = -1; for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) { TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i); for (int j = 0; j < entry.getCount(); j++) { if (currentTime <= startTime) { startSample = currentSample; } if (currentTime <= endTime) { endSample = currentSample; } else { break; } currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale(); currentSample++; } } movie.addTrack(new CroppedTrack(track, startSample, endSample)); } long start1 = System.currentTimeMillis(); IsoFile out = new DefaultMp4Builder().build(movie); long start2 = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime)); FileChannel fc = fos.getChannel(); out.getBox(fc); fc.close(); fos.close(); long start3 = System.currentTimeMillis(); System.err.println("Building IsoFile took : " + (start2 - start1) + "ms"); System.err.println("Writing IsoFile took : " + (start3 - start2) + "ms"); System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s"); } | public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } } | 900,415 |
1 | private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); } | public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } } | 900,416 |
1 | void copyFile(File inputFile, File outputFile) { try { FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } } | 900,417 |
1 | private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } } | private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; } | 900,418 |
0 | public void testSimpleHttpPostsChunked() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } } | private void initURL() { try { log.fine("Checking: " + locator); URLConnection conn = URIFactory.url(locator).openConnection(); conn.setUseCaches(false); log.info(conn.getHeaderFields().toString()); String header = conn.getHeaderField(null); if (header.contains("404")) { log.info("404 file not found: " + locator); return; } if (header.contains("500")) { log.info("500 server error: " + locator); return; } if (conn.getContentLength() > 0) { byte[] buffer = new byte[50]; conn.getInputStream().read(buffer); if (new String(buffer).trim().startsWith("<!DOCTYPE")) return; } else if (conn.getContentLength() == 0) { exists = true; return; } exists = true; length = conn.getContentLength(); } catch (Exception ioe) { System.err.println(ioe); } } | 900,419 |
0 | @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } | public void testDecodeJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); String[] exiFiles = { "/JTLM/publish100/publish100.bitPacked", "/JTLM/publish100/publish100.byteAligned", "/JTLM/publish100/publish100.preCompress", "/JTLM/publish100/publish100.compress" }; for (int i = 0; i < Alignments.length; i++) { AlignmentType alignment = Alignments[i]; EXIDecoder decoder = new EXIDecoder(); Scanner scanner; decoder.setAlignmentType(alignment); URL url = resolveSystemIdAsURL(exiFiles[i]); int n_events, n_texts; decoder.setEXISchema(grammarCache); decoder.setInputStream(url.openStream()); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { String stringValue = exiEvent.getCharacters().makeString(); if (stringValue.length() == 0 && exiEvent.getEventType().itemType == EventCode.ITEM_SCHEMA_CH) { --n_events; continue; } if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], stringValue); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } } | 900,420 |
0 | public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } } | public static String encryptPasswd(String pass) { try { if (pass == null || pass.length() == 0) return pass; MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(pass.getBytes("UTF-8")); return Base64OutputStream.encode(sha.digest()); } catch (Throwable t) { throw new SystemException(t); } } | 900,421 |
1 | @Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } } | protected void doProxyInternally(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpRequestBase proxyReq = buildProxyRequest(req); URI reqUri = proxyReq.getURI(); String cookieDomain = reqUri.getHost(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute("org.atricorel.idbus.kernel.main.binding.http.HttpServletRequest", req); int intIdx = 0; for (int i = 0; i < httpClient.getRequestInterceptorCount(); i++) { if (httpClient.getRequestInterceptor(i) instanceof RequestAddCookies) { intIdx = i; break; } } IDBusRequestAddCookies interceptor = new IDBusRequestAddCookies(cookieDomain); httpClient.removeRequestInterceptorByClass(RequestAddCookies.class); httpClient.addRequestInterceptor(interceptor, intIdx); httpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (logger.isTraceEnabled()) logger.trace("Staring to follow redirects for " + req.getPathInfo()); HttpResponse proxyRes = null; List<Header> storedHeaders = new ArrayList<Header>(40); boolean followTargetUrl = true; byte[] buff = new byte[1024]; while (followTargetUrl) { if (logger.isTraceEnabled()) logger.trace("Sending internal request " + proxyReq); proxyRes = httpClient.execute(proxyReq, httpContext); String targetUrl = null; Header[] headers = proxyRes.getAllHeaders(); for (Header header : headers) { if (header.getName().equals("Server")) continue; if (header.getName().equals("Transfer-Encoding")) continue; if (header.getName().equals("Location")) continue; if (header.getName().equals("Expires")) continue; if (header.getName().equals("Content-Length")) continue; if (header.getName().equals("Content-Type")) continue; storedHeaders.add(header); } if (logger.isTraceEnabled()) logger.trace("HTTP/STATUS:" + proxyRes.getStatusLine().getStatusCode() + "[" + proxyReq + "]"); switch(proxyRes.getStatusLine().getStatusCode()) { case 200: followTargetUrl = false; break; case 404: followTargetUrl = false; break; case 500: followTargetUrl = false; break; case 302: Header location = proxyRes.getFirstHeader("Location"); targetUrl = location.getValue(); if (!internalProcessingPolicy.match(req, targetUrl)) { if (logger.isTraceEnabled()) logger.trace("Do not follow HTTP 302 to [" + location.getValue() + "]"); Collections.addAll(storedHeaders, proxyRes.getHeaders("Location")); followTargetUrl = false; } else { if (logger.isTraceEnabled()) logger.trace("Do follow HTTP 302 to [" + location.getValue() + "]"); followTargetUrl = true; } break; default: followTargetUrl = false; break; } HttpEntity entity = proxyRes.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { if (!followTargetUrl) { for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } IOUtils.copy(instream, res.getOutputStream()); res.getOutputStream().flush(); } else { int r = instream.read(buff); int total = r; while (r > 0) { r = instream.read(buff); total += r; } if (total > 0) logger.warn("Ignoring response content size : " + total); } } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { proxyReq.abort(); throw ex; } finally { try { instream.close(); } catch (Exception ignore) { } } } else { if (!followTargetUrl) { res.setStatus(proxyRes.getStatusLine().getStatusCode()); for (Header header : headers) { if (header.getName().equals("Content-Type")) res.setHeader(header.getName(), header.getValue()); if (header.getName().equals("Content-Length")) res.setHeader(header.getName(), header.getValue()); } for (Header header : storedHeaders) { if (header.getName().startsWith("Set-Cookie")) res.addHeader(header.getName(), header.getValue()); else res.setHeader(header.getName(), header.getValue()); } } } if (followTargetUrl) { proxyReq = buildProxyRequest(targetUrl); httpContext = null; } } if (logger.isTraceEnabled()) logger.trace("Ended following redirects for " + req.getPathInfo()); } | 900,422 |
1 | @Override public Document duplicate() { BinaryDocument b = new BinaryDocument(this.name, this.content.getContentType()); try { IOUtils.copy(this.getContent().getInputStream(), this.getContent().getOutputStream()); return b; } catch (IOException e) { throw ManagedIOException.manage(e); } } | public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } | 900,423 |
0 | private static GSP loadGSP(URL url) { try { InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } Unmarshaller unmarshaller = getUnmarshaller(); unmarshaller.setValidation(false); GSP gsp = (GSP) unmarshaller.unmarshal(new InputSource()); return gsp; } catch (Exception e) { System.out.println("loadGSP " + e); e.printStackTrace(); return null; } } | 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(); } | 900,424 |
1 | public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } | public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } } | 900,425 |
0 | public void delete(String user) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from Principals where PrincipalId = '" + user + "'"); stmt.executeUpdate("delete from Roles where PrincipalId = '" + user + "'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } | public static String MD5Digest(String source) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(source.getBytes("UTF8")); byte[] hash = digest.digest(); String strHash = byteArrayToHexString(hash); return strHash; } catch (NoSuchAlgorithmException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } catch (UnsupportedEncodingException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } } | 900,426 |
0 | @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } | public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; } | 900,427 |
1 | public static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; } | 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(); } } | 900,428 |
0 | private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } } | public static void main(String[] args) throws IOException, DataFormatException { byte in_buf[] = new byte[20000]; if (args.length < 2) { System.out.println("too few arguments"); System.exit(0); } String inputName = args[0]; InputStream in = new FileInputStream(inputName); int index = 0; for (int i = 1; i < args.length; i++) { int size = Integer.parseInt(args[i]); boolean copy = size >= 0; if (size < 0) { size = -size; } OutputStream out = null; if (copy) { index++; out = new FileOutputStream(inputName + "." + index + ".dat"); } while (size > 0) { int read = in.read(in_buf, 0, Math.min(in_buf.length, size)); if (read < 0) { break; } size -= read; if (copy) { out.write(in_buf, 0, read); } } if (copy) { out.close(); } } index++; OutputStream out = new FileOutputStream(inputName + "." + index + ".dat"); while (true) { int read = in.read(in_buf); if (read < 0) { break; } out.write(in_buf, 0, read); } out.close(); in.close(); } | 900,429 |
0 | public Reader create(final URI url) throws IOException { this.url = url; if (!url.isAbsolute()) { return new FileReader(new File(url.toString())); } URLConnection connection = url.toURL().openConnection(); connection.setDoInput(true); final InputStream inputStream = connection.getInputStream(); return new InputStreamReader(inputStream); } | public void ztest_cluster() throws Exception { Configuration.init(); TomcatServer ts1 = new TomcatServer(); ts1.registerServlet("/*", TestServlet.class.getName()); ts1.registerCluster(5554); ts1.start(5555); TomcatServer ts2 = new TomcatServer(); ts2.registerServlet("/*", TestServlet.class.getName()); ts2.registerCluster(5554); ts2.start(5556); URL url1 = new URL("http://127.0.0.1:5555/a"); HttpURLConnection c1 = (HttpURLConnection) url1.openConnection(); assert getData(c1).equals("a null"); String cookie = c1.getHeaderField("Set-Cookie"); Thread.sleep(5000); URL url2 = new URL("http://127.0.0.1:5556/a"); HttpURLConnection c2 = (HttpURLConnection) url2.openConnection(); c2.setRequestProperty("Cookie", cookie); assert getData(c2).equals("a a"); } | 900,430 |
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()); } } | private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); } | 900,431 |
1 | public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } | public static void copyFile(File in, File out) throws IOException { if (in.getCanonicalPath().equals(out.getCanonicalPath())) { return; } FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } | 900,432 |
1 | public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } | public boolean saveTemplate(Template t) { try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String query; ResultSet rset; if (Integer.parseInt(executeMySQLGet("SELECT COUNT(*) FROM templates WHERE name='" + escapeCharacters(t.getName()) + "'")) != 0) return false; query = "select * from templates where templateid = " + t.getID(); rset = stmt.executeQuery(query); if (rset.next()) { System.err.println("Updating already saved template is not supported!!!!!!"); return false; } else { query = "INSERT INTO templates (name, parentid) VALUES ('" + escapeCharacters(t.getName()) + "', " + t.getParentID() + ")"; try { stmt.executeUpdate(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } int templateid = Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()")); t.setID(templateid); LinkedList<Field> fields = t.getFields(); ListIterator<Field> iter = fields.listIterator(); Field f = null; PreparedStatement pstmt = conn.prepareStatement("INSERT INTO templatefields(fieldtype, name, templateid, defaultvalue)" + "VALUES (?,?,?,?)"); try { while (iter.hasNext()) { f = iter.next(); if (f.getType() == Field.IMAGE) { System.out.println("field is an image."); byte data[] = ((FieldDataImage) f.getDefault()).getDataBytes(); pstmt.setBytes(4, data); } else { System.out.println("field is not an image"); String deflt = (f.getDefault()).getData(); pstmt.setString(4, deflt); } pstmt.setInt(1, f.getType()); pstmt.setString(2, f.getName()); pstmt.setInt(3, t.getID()); pstmt.execute(); f.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { System.err.println("Error saving the Template"); return false; } return true; } | 900,433 |
0 | public void transport(File file) throws TransportException { FTPClient client = new FTPClient(); try { client.connect(getOption("host")); client.login(getOption("username"), getOption("password")); client.changeWorkingDirectory(getOption("remotePath")); transportRecursive(client, file); client.disconnect(); } catch (Exception e) { throw new TransportException(e); } } | private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; } | 900,434 |
0 | public static byte[] read(URL url) throws IOException { byte[] bytes; InputStream is = null; try { is = url.openStream(); bytes = readAllBytes(is); } finally { if (is != null) { is.close(); } } return bytes; } | @Override public void testAction(ITestThread testThread) throws Throwable { try { final InputStream urlIn = new URL("http://jdistunit.sourceforge.net").openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (null != testThread && testThread.isActionStopped()) { break; } } } finally { if (null != in) { in.close(); in = null; } } } | 900,435 |
0 | 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(); } } | public void restoreDrivers() throws ExplorerException { try { drivers.clear(); URL url = URLUtil.getResourceURL("default_drivers.xml"); loadDefaultDrivers(url.openStream()); } catch (IOException e) { throw new ExplorerException(e); } } | 900,436 |
0 | public void initFromXml(final String xmlFileName) throws java.net.MalformedURLException, ConfigurationException, IOException { if (xmlInitialized) { return; } templates = null; MergeTemplateWriter.setTokenList(getTokenProvider().getKnownTokens()); java.net.URL url = new FileFinder().getUrl(getTokenProvider().getClass(), xmlFileName); InputStreamReader xmlFileReader = new InputStreamReader(url.openStream()); KnownTemplates temps = MergeTemplateWriter.importFromXML(xmlFileReader); xmlFileReader.close(); KnownTemplates.setDefaultInstance(temps); setTemplates(temps); setInitialized(true); } | public static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException { httprequest.setHeader("Accept", "application/json"); httprequest.setHeader("Content-type", "application/json"); String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httprequest); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result += line + "\n"; } return result; } | 900,437 |
0 | private String grabInformationFromWeb(String query, String infoName) throws Exception { String result = ""; URL url = new URL(query); HttpURLConnection request = null; request = (HttpURLConnection) url.openConnection(); if (request != null) { InputStream in = url.openStream(); int c = 0; StringBuilder sb = new StringBuilder(); while ((c = in.read()) != -1) { sb = sb.append((char) c); } String s = sb.toString(); result = Utils.getTagValue(s, "<" + infoName + ">", "</" + infoName + ">"); in.close(); } return result; } | public JSONObject executeJSON(final String path, final JSONObject jsRequest) throws IOException, HttpException, JSONException { final HttpPost httpRequest = newHttpPost(path); httpRequest.setHeader("Content-Type", "application/json"); final String request = jsRequest.toString(); httpRequest.setEntity(new StringEntity(request)); final HttpResponse httpResponse = executeHttp(httpRequest); final String response = EntityUtils.toString(httpResponse.getEntity()); return new JSONObject(response); } | 900,438 |
0 | public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); } | public static final String getContent(String address) { String content = ""; OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new ByteArrayOutputStream(); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } content = out.toString(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return content; } | 900,439 |
1 | @Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); } | 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("data/icons/view_sidetreeOK.png")); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } | 900,440 |
0 | public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } | public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } } | 900,441 |
0 | public static void bubble(double[] a) { for (int i = a.length - 1; i > 0; i--) for (int j = 0; j < i; j++) if (a[j] > a[j + 1]) { double temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } | public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; } | 900,442 |
1 | final void saveProject(Project project, final File file) { if (projectsList.contains(project)) { if (project.isDirty() || !file.getParentFile().equals(workspaceDirectory)) { try { if (!file.exists()) { if (!file.createNewFile()) throw new IOException("cannot create file " + file.getAbsolutePath()); } File tmpFile = File.createTempFile("JFPSM", ".tmp"); ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); zoStream.setMethod(ZipOutputStream.DEFLATED); ZipEntry projectXMLEntry = new ZipEntry("project.xml"); projectXMLEntry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(projectXMLEntry); CustomXMLEncoder encoder = new CustomXMLEncoder(new BufferedOutputStream(new FileOutputStream(tmpFile))); encoder.writeObject(project); encoder.close(); int bytesIn; byte[] readBuffer = new byte[1024]; FileInputStream fis = new FileInputStream(tmpFile); while ((bytesIn = fis.read(readBuffer)) != -1) zoStream.write(readBuffer, 0, bytesIn); fis.close(); ZipEntry entry; String floorDirectory; for (FloorSet floorSet : project.getLevelSet().getFloorSetsList()) for (Floor floor : floorSet.getFloorsList()) { floorDirectory = "levelset/" + floorSet.getName() + "/" + floor.getName() + "/"; for (MapType type : MapType.values()) { entry = new ZipEntry(floorDirectory + type.getFilename()); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(floor.getMap(type).getImage(), "png", zoStream); } } final String tileDirectory = "tileset/"; for (Tile tile : project.getTileSet().getTilesList()) for (int textureIndex = 0; textureIndex < tile.getMaxTextureCount(); textureIndex++) if (tile.getTexture(textureIndex) != null) { entry = new ZipEntry(tileDirectory + tile.getName() + textureIndex + ".png"); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(tile.getTexture(textureIndex), "png", zoStream); } zoStream.close(); tmpFile.delete(); } catch (IOException ioe) { throw new RuntimeException("The project " + project.getName() + " cannot be saved!", ioe); } } } else throw new IllegalArgumentException("The project " + project.getName() + " is not handled by this project set!"); } | 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(); } } | 900,443 |
1 | private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; } | protected String getManualDownloadURL() { if (_newestVersionString.indexOf("weekly") > 0) { return "http://www.cs.rice.edu/~javaplt/drjavarice/weekly/"; } final String DRJAVA_FILES_PAGE = "http://sourceforge.net/project/showfiles.php?group_id=44253"; final String LINK_PREFIX = "<a href=\"/project/showfiles.php?group_id=44253"; final String LINK_SUFFIX = "\">"; BufferedReader br = null; try { URL url = new URL(DRJAVA_FILES_PAGE); InputStream urls = url.openStream(); InputStreamReader is = new InputStreamReader(urls); br = new BufferedReader(is); String line; int pos; while ((line = br.readLine()) != null) { if ((pos = line.indexOf(_newestVersionString)) >= 0) { int prePos = line.indexOf(LINK_PREFIX); if ((prePos >= 0) && (prePos < pos)) { int suffixPos = line.indexOf(LINK_SUFFIX, prePos); if ((suffixPos >= 0) && (suffixPos + LINK_SUFFIX.length() == pos)) { String versionLink = edu.rice.cs.plt.text.TextUtil.xmlUnescape(line.substring(prePos + LINK_PREFIX.length(), suffixPos)); return DRJAVA_FILES_PAGE + versionLink; } } } } ; } catch (IOException e) { return DRJAVA_FILES_PAGE; } finally { try { if (br != null) br.close(); } catch (IOException e) { } } return DRJAVA_FILES_PAGE; } | 900,444 |
1 | public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { e.printStackTrace(); } } | private void sendFile(File file, HttpExchange response) throws IOException { response.getResponseHeaders().add(FileUploadBase.CONTENT_LENGTH, Long.toString(file.length())); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getResponseBody()); } catch (Exception exception) { throw new IOException("error sending file", exception); } finally { IOUtils.closeQuietly(inputStream); } } | 900,445 |
1 | private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } } | public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } } | 900,446 |
1 | public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; } | 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(); } } | 900,447 |
0 | private boolean importTablesData(Connection conn) { try { boolean status = true; boolean autoCommit = conn.getAutoCommit(); conn.setAutoCommit(false); String dbType = this.getFromSession("database"); List statements = ParseDBDumpFile.parse(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR) + "/database/" + dbType + "/" + dbType + "_data_dump.sql"); for (Iterator iter = statements.iterator(); iter.hasNext(); ) { String query = (String) iter.next(); if (query == null || "".equals(query.trim())) { continue; } query = query.trim(); Statement s = conn.createStatement(); try { if (query.startsWith("UPDATE") || query.startsWith("INSERT") || query.startsWith("SET")) { s.executeUpdate(query); } else if (query.startsWith("SELECT")) { s.executeQuery(query); } else { throw new SQLException("Invalid query: " + query); } } catch (SQLException ex) { status = false; conn.rollback(); logger.error("Error importing data for " + query + ": " + ex, ex); this.context.put("exceptionMessage", ex.getMessage() + "\n" + query); break; } finally { s.close(); } } conn.setAutoCommit(autoCommit); return status; } catch (Exception e) { throw new ForumException(e); } } | public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } } | 900,448 |
1 | public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } | private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); } | 900,449 |
1 | @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); } | public String postXmlRequest(String url, String data) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuffer responseStr = new StringBuffer(); try { System.out.println(data); Log4j.logger.info("Request:\n" + data); StringEntity reqEntity = new StringEntity(data, "UTF-8"); reqEntity.setContentType("text/xml"); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); this.setPostSatus(response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { responseStr.append(line + "\n"); } if (entity != null) { entity.consumeContent(); } } catch (Exception ex) { ex.printStackTrace(); } System.out.println(responseStr); Log4j.logger.info("Response:\n" + responseStr); return responseStr.toString(); } | 900,450 |
1 | public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; } | private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } | 900,451 |
1 | @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } } | public void save(File selectedFile) throws IOException { if (storeEntriesInFiles) { boolean moved = false; for (int i = 0; i < tempFiles.size(); i++) { File newFile = new File(selectedFile.getAbsolutePath() + "_" + Integer.toString(i) + ".zettmp"); moved = tempFiles.get(i).renameTo(newFile); if (!moved) { BufferedReader read = new BufferedReader(new FileReader(tempFiles.get(i))); PrintWriter write = new PrintWriter(newFile); String s; while ((s = read.readLine()) != null) write.print(s); read.close(); write.flush(); write.close(); tempFiles.get(i).delete(); } tempFiles.set(i, newFile); } } GZIPOutputStream output = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(selectedFile))); XStream xml_convert = new XStream(); xml_convert.setMode(XStream.ID_REFERENCES); xml_convert.toXML(this, output); output.flush(); output.close(); } | 900,452 |
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(); } } | private void publishMap(LWMap map) throws IOException { File savedMap = PublishUtil.saveMap(map); InputStream istream = new BufferedInputStream(new FileInputStream(savedMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("ConceptMap", "vue"))); int fileLength = (int) savedMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } | 900,453 |
1 | public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } | public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; } | 900,454 |
1 | public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } } | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | 900,455 |
0 | public static void track(String strUserName, String strShortDescription, String strLongDescription, String strPriority, String strComponent) { String strFromToken = ""; try { URL url = new URL(getTracUrl() + "newticket"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String buffer = reader.readLine(); while (buffer != null) { if (buffer.contains("__FORM_TOKEN")) { Pattern pattern = Pattern.compile("value=\"[^\"]*\""); Matcher matcher = pattern.matcher(buffer); int start = 0; matcher.find(start); int von = matcher.start() + 7; int bis = matcher.end() - 1; strFromToken = buffer.substring(von, bis); } buffer = reader.readLine(); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(getTracUrl() + "newticket"); method.setRequestHeader("Cookie", "trac_form_token=" + strFromToken); method.addParameter("__FORM_TOKEN", strFromToken); method.addParameter("reporter", strUserName); method.addParameter("summary", strShortDescription); method.addParameter("type", "Fehler"); method.addParameter("description", strLongDescription); method.addParameter("action", "create"); method.addParameter("status", "new"); method.addParameter("priority", strPriority); method.addParameter("milestone", ""); method.addParameter("component", strComponent); method.addParameter("keywords", "BugReporter"); method.addParameter("cc", ""); method.addParameter("version", ""); client.executeMethod(method); } catch (IOException e) { e.printStackTrace(); } } | protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } } | 900,456 |
1 | public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } | private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } | 900,457 |
1 | public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); } | 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!"); } | 900,458 |
0 | private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } } | public void loginSendSpace() throws Exception { loginsuccessful = false; HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to sendspace"); HttpPost httppost = new HttpPost("http://www.sendspace.com/login.html"); httppost.setHeader("Cookie", sidcookie + ";" + ssuicookie); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("submit", "login")); formparams.add(new BasicNameValuePair("target", "%252F")); formparams.add(new BasicNameValuePair("action_type", "login")); formparams.add(new BasicNameValuePair("remember", "1")); formparams.add(new BasicNameValuePair("username", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("ssal")) { ssalcookie = escookie.getName() + "=" + escookie.getValue(); NULogger.getLogger().info(ssalcookie); loginsuccessful = true; } } if (loginsuccessful) { username = getUsername(); password = getPassword(); NULogger.getLogger().info("SendSpace login success :)"); } else { NULogger.getLogger().info("SendSpace login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } } | 900,459 |
1 | public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } | public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } | 900,460 |
0 | public void delete(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > max)) throw new IllegalArgumentException("Row number not between 1 and " + max); stmt.executeUpdate("delete from WordClassifications where Rank = " + row); for (int i = row; i < max; ++i) stmt.executeUpdate("update WordClassifications set Rank = " + i + " where Rank = " + (i + 1)); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } | 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; } | 900,461 |
0 | private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; } | public static String hashJopl(String password, String algorithm, String prefixKey, boolean useDefaultEncoding) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (useDefaultEncoding) { digest.update(password.getBytes()); } else { for (char c : password.toCharArray()) { digest.update((byte) (c >> 8)); digest.update((byte) c); } } byte[] digestedPassword = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String encodedDigestedStr = encoder.encode(digestedPassword); return prefixKey + encodedDigestedStr; } catch (NoSuchAlgorithmException ne) { return password; } } | 900,462 |
0 | public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } | private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } } | 900,463 |
0 | 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(); } } | protected String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception ex) { throw new TiiraException(ex); } } | 900,464 |
1 | private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; } | public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } | 900,465 |
1 | void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } | @Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); } | 900,466 |
1 | public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } | 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); } | 900,467 |
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; } | public static String encrypt(String password) { String sign = password; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(sign.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } sign = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return sign; } | 900,468 |
1 | public void testReadNormal() throws Exception { archiveFileManager.executeWith(new TemporaryFileExecutor() { public void execute(File temporaryFile) throws Exception { ZipArchive archive = new ZipArchive(temporaryFile.getPath()); InputStream input = archive.getInputFrom(ARCHIVE_FILE_1); if (input != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, output); assertEquals(ARCHIVE_FILE_1 + " contents not correct", ARCHIVE_FILE_1_CONTENT, output.toString()); } else { fail("cannot open " + ARCHIVE_FILE_1); } } }); } | public static void replaceAll(File file, String substitute, String substituteReplacement) throws IOException { log.debug("Replace " + substitute + " by " + substituteReplacement); Pattern pattern = Pattern.compile(substitute); FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); Charset charset = Charset.forName("ISO-8859-15"); CharsetDecoder decoder = charset.newDecoder(); CharBuffer cb = decoder.decode(bb); Matcher matcher = pattern.matcher(cb); String outString = matcher.replaceAll(substituteReplacement); log.debug(outString); FileOutputStream fos = new FileOutputStream(file.getAbsolutePath()); PrintStream ps = new PrintStream(fos); ps.print(outString); ps.close(); fos.close(); } | 900,469 |
0 | private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } } | PathElement(String path) throws MaxError { this.path = path; if (path.startsWith("http:")) { try { url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); valid = (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { valid = false; } } else { if (path.startsWith("jmax:")) file = new File(Registry.resolveJMaxURI(path)); else file = new File(path); valid = file.exists(); } } | 900,470 |
1 | private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } | public void testCodingBeyondContentLimitFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff; and a lot more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } | 900,471 |
1 | public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } } | public String md5(String password) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } m.update(password.getBytes(), 0, password.length()); return new BigInteger(1, m.digest()).toString(16); } | 900,472 |
1 | static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } } | @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } } | 900,473 |
0 | @SuppressWarnings("unchecked") public static void main(String[] args) { System.out.println("Starting encoding test...."); Properties p = new Properties(); try { InputStream pStream = ClassLoader.getSystemResourceAsStream("sample_weather.properties"); p.load(pStream); } catch (Exception e) { System.err.println("Could not load properties file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } if (WeatherUpdater.DEBUG) { System.out.println("hostname: " + p.getProperty("weather.hostname")); } if (WeatherUpdater.DEBUG) { System.out.println("database: " + p.getProperty("weather.database")); } if (WeatherUpdater.DEBUG) { System.out.println("username: " + p.getProperty("weather.username")); } if (WeatherUpdater.DEBUG) { System.out.println("password: " + p.getProperty("weather.password")); } SqlAccount sqlAccount = new SqlAccount(p.getProperty("weather.hostname"), p.getProperty("weather.database"), p.getProperty("weather.username"), p.getProperty("weather.password")); DatabaseInterface dbi = null; try { dbi = new DatabaseInterface(sqlAccount); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Established connection to database."); String query = "SELECT * FROM Current_Weather WHERE ZipCode = '99702'"; ResultTable results; System.out.println("Executing query: " + query); try { results = dbi.executeQuery(query); } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Got results from query."); System.out.println("Converted results into the following table:"); System.out.println(results); System.out.println(); Class<? extends ResultEncoder> encoder_class; Class<? extends ResultDecoder> decoder_class; try { encoder_class = (Class<? extends ResultEncoder>) Class.forName(p.getProperty("mysms.coding.resultEncoder")); decoder_class = (Class<? extends ResultDecoder>) Class.forName(p.getProperty("mysms.coding.resultDecoder")); } catch (Exception e) { System.err.println("Could not find specified encoder: " + p.getProperty("result.encoder")); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Found class of encoder: " + encoder_class); System.out.println("Found class of decoder: " + decoder_class); ResultEncoder encoder; ResultDecoder decoder; try { encoder = encoder_class.newInstance(); if (encoder_class.equals(decoder_class) && decoder_class.isInstance(encoder)) { decoder = (ResultDecoder) encoder; } else { decoder = decoder_class.newInstance(); } } catch (Exception e) { System.err.println("Could not create instances of encoder and decoder."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Created instances of encoder and decoder."); if (decoder.equals(encoder)) { System.out.println("Decoder and encoder are same object."); } ByteBuffer buffer; try { buffer = encoder.encode(null, results); } catch (Exception e) { System.err.println("Could not encode results."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Encoded results to ByteBuffer with size: " + buffer.capacity()); File temp; try { temp = File.createTempFile("encoding_test", ".results"); temp.deleteOnExit(); FileChannel out = new FileOutputStream(temp).getChannel(); out.write(buffer); out.close(); } catch (Exception e) { System.err.println("Could not write buffer to file."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Wrote buffer to file: \"" + temp.getName() + "\" with length: " + temp.length()); ByteBuffer re_buffer; try { FileInputStream in = new FileInputStream(temp.getAbsolutePath()); byte[] temp_buffer = new byte[(int) temp.length()]; int totalRead = 0; int numRead = 0; while (totalRead < temp_buffer.length) { numRead = in.read(temp_buffer, totalRead, temp_buffer.length - totalRead); if (numRead < 0) { break; } else { totalRead += numRead; } } re_buffer = ByteBuffer.wrap(temp_buffer); in.close(); } catch (Exception e) { System.err.println("Could not read from temporary file into buffer."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Read file back into buffer with length: " + re_buffer.capacity()); ResultTable re_results; try { re_results = decoder.decode(null, re_buffer); } catch (Exception e) { System.err.println("Could not decode buffer into a ResultTable."); System.err.println(e.getMessage()); e.printStackTrace(); return; } System.out.println("Decoded buffer back into the following table:"); System.out.println(re_results); System.out.println(); System.out.println("... encoding test complete."); } | @Override public ImageData getImageData(URL url) { InputStream in = null; try { URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", "Tahiti/Alpha5x"); conn.setRequestProperty("agent-system", "aglets"); conn.setAllowUserInteraction(true); conn.connect(); in = conn.getInputStream(); String type = conn.getContentType(); int len = conn.getContentLength(); if (len < 0) { len = in.available(); } byte[] b = new byte[len]; int off = 0; int n = 0; while (n < len) { int count = in.read(b, off + n, len - n); if (count < 0) { throw new java.io.EOFException(); } n += count; } in.close(); return new AgletImageData(url, b, type); } catch (Exception ex) { ex.printStackTrace(); return null; } } | 900,474 |
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(); } } | public java.io.File gzip(java.io.File file) throws Exception { java.io.File tmp = null; InputStream is = null; OutputStream os = null; try { tmp = java.io.File.createTempFile(file.getName(), ".gz"); tmp.deleteOnExit(); is = new BufferedInputStream(new FileInputStream(file)); os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); byte[] buf = new byte[4096]; int nread = -1; while ((nread = is.read(buf)) != -1) { os.write(buf, 0, nread); } os.flush(); } finally { os.close(); is.close(); } return tmp; } | 900,475 |
0 | public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); } | public void launch(String xmlControl, String xmlDoc, long docId) { AgentLauncher l; Environment env; Properties prop; Resource res; String token; String deflt; String answ; String key; String entry; ShipService service; de.fhg.igd.util.URL url; java.net.URL wsurl; NodeList flow; InputSource xmlcontrolstream; TreeMap results; synchronized (lock_) { if (xmlControl == null || xmlControl.length() == 0 || xmlDoc == null || xmlDoc.length() == 0) { System.out.println("---- Need control AND XML document! ----"); return; } Vector v_delegations_host = new Vector(); Vector v_delegations_url = new Vector(); Vector v_delegations_method = new Vector(); xmlcontrolstream = new InputSource(new StringReader(xmlControl)); NodeList destinations = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_DELEGATE); for (int i = 0; i < destinations.getLength(); i++) { if (destinations.item(i).getTextContent() != null && destinations.item(i).getTextContent().length() > 0) { System.out.println(destinations.item(i).getTextContent()); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_HOST); v_delegations_host.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_URL); v_delegations_url.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_METHOD); v_delegations_method.add(entry); } } token = ""; results = new TreeMap(); for (int i = 0; i < TOKEN_LENGTH; i++) { token = token + (char) (Math.random() * 26 + 65); } results.put(token, null); prop = AgentStructure.defaults(); prop.setProperty(AgentStructure.PROP_AGENT_CLASS, AGENT_); prop.setProperty(AgentBehaviour.CTX_DOCID, String.valueOf(docId)); prop.setProperty(AgentBehaviour.CTX_XML, xmlDoc); prop.setProperty("token", token); deflt = prop.getProperty(AgentStructure.PROP_AGENT_EXCLUDE); prop.setProperty(AgentStructure.PROP_AGENT_EXCLUDE, deflt + ":" + ADDITIONAL_EXCLUDES); service = (ShipService) getEnvironment().lookup(WhatIs.stringValue(ShipService.WHATIS)); for (int i = 0; i < v_delegations_host.size(); i++) { System.out.println("\n-----SCANNING DELEGATES-----"); System.out.println("\n-----DELEGATE " + i + "-----"); System.out.println("-----HOST: " + i + ": " + (String) v_delegations_host.elementAt(i)); System.out.println("-----URL: " + i + ": " + (String) v_delegations_url.elementAt(i)); System.out.println("-----METHOD: " + i + ": " + (String) v_delegations_method.elementAt(i)); try { url = new de.fhg.igd.util.URL((String) v_delegations_host.elementAt(i)); boolean alive = service.isAlive(url); System.out.println("-----ALIVE: " + alive); if (alive) { wsurl = new java.net.URL((String) v_delegations_url.elementAt(i)); try { wsurl.openStream(); System.out.println("-----WEBSERVICE: ON"); if (!prop.containsKey(0 + "." + AgentBehaviour.XML_URL)) { System.out.println("-----MIGRATION: First online host found. I will migrate here:)!"); prop.setProperty(0 + "." + AgentBehaviour.XML_HOST, (String) v_delegations_host.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_URL, (String) v_delegations_url.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_METHOD, (String) v_delegations_method.elementAt(i)); } else { System.out.println("-----MIGRATION: I will not migrate here:(!"); } } catch (IOException ex) { System.out.println("-----WEBSERVICE: Could not connect to the webservice!"); System.out.println("-----MIGRATION: WEBSERVICE NOT FOUND! I will not migrate here:(!"); } } } catch (ShipException she) { System.out.println("-----ALIVE: false"); System.out.println("-----MIGRATION: HOST NOT FOUND! I will not migrate here:(!"); } catch (SecurityException see) { System.out.println("-----EXCEPTION: Access connection to remote SHIP service fails! " + "No proper ShipPermission permission to invoke lookups! " + "Ignoring this host...."); } catch (MalformedURLException murle) { System.out.println("-----EXCEPTION: The host URL is not valid! Ignoring this host...."); } } res = new MemoryResource(); env = Environment.getEnvironment(); key = WhatIs.stringValue(AgentLauncher.WHATIS); l = (AgentLauncher) env.lookup(key); if (l == null) { System.out.println("Can't find the agent launcher"); return; } try { l.launchAgent(res, prop); } catch (IllegalAgentException ex) { System.out.println(ex); } catch (GeneralSecurityException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } syncmap_.put(token, results); System.out.println("----- TOKEN = " + token + "------"); } try { synchronized (token) { token.wait(TIMEOUT); Map m_results = (Map) syncmap_.get(token); Collection c_results = m_results.values(); String[] sa_results = (String[]) c_results.toArray(new String[0]); answ = ""; for (int j = 0; j < sa_results.length; j++) { answ = answ + sa_results[j]; } syncmap_.remove(token); System.out.println("----- " + answ + " -----"); callbackWS(xmlControl, answ, docId); } } catch (InterruptedException ex) { System.out.println(ex); } } | 900,476 |
1 | public void render(Map map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE); File file = (File) map.get("targetFile"); IOUtils.copy(new FileInputStream(file), baos); httpServletResponse.setContentType(getContentType()); httpServletResponse.setContentLength(baos.size()); httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + file.getName()); ServletOutputStream out = httpServletResponse.getOutputStream(); baos.writeTo(out); out.flush(); } | 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!"); } | 900,477 |
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; } | public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } | 900,478 |
0 | private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } | public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } | 900,479 |
1 | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | private File newFile(File oldFile) throws IOException { int counter = 0; File nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName()); while (nFile.exists()) { nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName() + "_" + counter); } IOUtils.copyFile(oldFile, nFile); return nFile; } | 900,480 |
0 | protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) { List<VideoSearchResult> resultsList = new ArrayList<>(); try { // set up the HTTP request factory HttpTransport transport = new NetHttpTransport(); HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { // set the parser JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; request.addParser(parser); // set up the Google headers GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("OGLExplorer/1.0"); headers.gdataVersion = "2"; request.headers = headers; } }); // build the YouTube URL YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos"); url.maxResults = number; url.words = words; url.startIndex = offset + 1; // build HttpRequest request = factory.buildGetRequest(url); // execute HttpResponse response = request.execute(); VideoFeed feed = response.parseAs(VideoFeed.class); if (feed.items == null) { return null; } // browse result and convert them to the local generic object model for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) { Video result = feed.items.get(i); VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1); modelResult.setTitle(result.title); modelResult.setDescription(result.description); modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL)); modelResult.setPath(result.player.defaultUrl); resultsList.add(modelResult); } } catch (Exception e) { e.printStackTrace(); } if (cancelMonitor.isCanceled()) { return null; } return resultsList; } | private static void copyFile(String src, String dest) throws IOException { File destFile = new File(dest); if (destFile.exists()) { destFile.delete(); } FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } | 900,481 |
1 | public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } } | private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); } | 900,482 |
0 | public static ArrayList<Credential> importCredentials(String urlString) { ArrayList<Credential> results = new ArrayList<Credential>(); try { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); if (line.equals("-----END PGP SIGNATURE-----")) { Credential credential = ProfileParser.parseCredential(buff.toString(), true); results.add(credential); buff = new StringBuffer(); } else { buff.append(NL); } } } catch (MalformedURLException e) { } catch (IOException e) { } catch (ParsingException e) { System.err.println(e); } return results; } | void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } } | 900,483 |
1 | public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } | public static void fastBackup(File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream(file)).getChannel(); out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage()); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file input stream", e); } } if (fout != null) { try { fout.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } } } | 900,484 |
1 | private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); } | 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!"); } | 900,485 |
1 | private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } } | public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } | 900,486 |
0 | public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; } | public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; } | 900,487 |
1 | public void test() throws Exception { StorageString s = new StorageString("UTF-8"); s.addText("Test"); try { s.getOutputStream(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } try { s.getWriter(); fail("Should throw IOException as method not supported."); } catch (IOException e) { } s.addText("ing is important"); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important", writer.toString()); } | public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } } | 900,488 |
1 | static void invalidSlave(String msg, Socket sock) throws IOException { BufferedReader _sinp = null; PrintWriter _sout = null; try { _sout = new PrintWriter(sock.getOutputStream(), true); _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream())); _sout.println(msg); logger.info("NEW< " + msg); String txt = AsyncSlaveListener.readLine(_sinp, 30); String sname = ""; String spass = ""; String shash = ""; try { String[] items = txt.split(" "); sname = items[1].trim(); spass = items[2].trim(); shash = items[3].trim(); } catch (Exception e) { throw new IOException("Slave Inititalization Faailed"); } String pass = sname + spass + _pass; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(pass.getBytes()); String hash = AsyncSlaveListener.hash2hex(md5.digest()).toLowerCase(); if (!hash.equals(shash)) { throw new IOException("Slave Inititalization Faailed"); } } catch (Exception e) { } throw new IOException("Slave Inititalization Faailed"); } | public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } } | 900,489 |
1 | public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; } | @Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); } | 900,490 |
0 | 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; } | public static String checkUpdate() { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } return Buffer.substring(Buffer.lastIndexOf("Google.mE Version: ") + 19, Buffer.indexOf("||")); } catch (IOException ex) { ex.printStackTrace(); return ""; } } | 900,491 |
1 | @Override public void run() { try { FileChannel out = new FileOutputStream(outputfile).getChannel(); long pos = 0; status.setText("Slučovač: Proces Slučování spuštěn.. Prosím čekejte.."); for (int i = 1; i <= noofparts; i++) { FileChannel in = new FileInputStream(originalfilename.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Slučovač: Slučuji část " + i + ".."); this.splitsize = in.size(); out.transferFrom(in, pos, splitsize); pos += splitsize; in.close(); if (deleteOnFinish) new File(originalfilename + ".v" + i).delete(); pb.setValue(100 * i / noofparts); } out.close(); status.setText("Slučovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Sloučeno!", "Slučovač", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { } } | private void installBinaryFile(File source, File destination) { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { } catch (IOException e) { new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } | 900,492 |
1 | private static long copy(InputStream source, OutputStream sink) { try { return IOUtils.copyLarge(source, sink); } catch (IOException e) { throw new FaultException("System error copying stream", e); } finally { IOUtils.closeQuietly(source); IOUtils.closeQuietly(sink); } } | public void truncateLog(long finalZxid) throws IOException { long highestZxid = 0; for (File f : dataDir.listFiles()) { long zxid = isValidSnapshot(f); if (zxid == -1) { LOG.warn("Skipping " + f); continue; } if (zxid > highestZxid) { highestZxid = zxid; } } File[] files = getLogFiles(dataLogDir.listFiles(), highestZxid); boolean truncated = false; for (File f : files) { FileInputStream fin = new FileInputStream(f); InputArchive ia = BinaryInputArchive.getArchive(fin); FileChannel fchan = fin.getChannel(); try { while (true) { byte[] bytes = ia.readBuffer("txtEntry"); if (bytes.length == 0) { throw new EOFException(); } InputArchive iab = BinaryInputArchive.getArchive(new ByteArrayInputStream(bytes)); TxnHeader hdr = new TxnHeader(); deserializeTxn(iab, hdr); if (ia.readByte("EOF") != 'B') { throw new EOFException(); } if (hdr.getZxid() == finalZxid) { long pos = fchan.position(); fin.close(); FileOutputStream fout = new FileOutputStream(f); FileChannel fchanOut = fout.getChannel(); fchanOut.truncate(pos); truncated = true; break; } } } catch (EOFException eof) { } if (truncated == true) { break; } } if (truncated == false) { LOG.error("Not able to truncate the log " + Long.toHexString(finalZxid)); System.exit(13); } } | 900,493 |
1 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } | @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); } } | 900,494 |
1 | private CharBuffer decodeToFile(ReplayInputStream inStream, String backingFilename, String encoding) throws IOException { CharBuffer charBuffer = null; BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, encoding)); File backingFile = new File(backingFilename); this.decodedFile = File.createTempFile(backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile()); FileOutputStream fos; fos = new FileOutputStream(this.decodedFile); IOUtils.copy(reader, fos, WRITE_ENCODING); fos.close(); charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).asCharBuffer(); return charBuffer; } | private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } } | 900,495 |
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(); } | 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!"); } | 900,496 |
0 | public <E extends Exception> void doWithConnection(String httpAddress, ICallableWithParameter<Void, URLConnection, E> toDo) throws E, ConnectionException { URLConnection connection; try { URL url = new URL(httpAddress); connection = url.openConnection(); } catch (MalformedURLException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } catch (IOException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } authenticationHandler.doWithProxyAuthentication(connection, toDo); } | @Override public void onClick(View v) { Log.d(Config.SS_TAG, "Sending POST request to server..."); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { JSONObject callJson = new JSONObject(); callJson.put("method", "ping"); callJson.put("void", "null"); callsJson.put(0, callJson); requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); JSONObject result = resultsJson.getJSONObject(0); String returnValue = result.getJSONObject("data").getString("return"); Log.d(Config.SS_TAG, "Response message: " + returnValue); } else { Log.e(Config.SS_TAG, "Unsuccessful ping..."); } } catch (Exception e) { Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet"); e.printStackTrace(); } } | 900,497 |
0 | public boolean finish() { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName.getText()); try { project.create(null); project.open(null); IProjectDescription desc = project.getDescription(); desc.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(desc, null); IJavaProject javaProject = JavaCore.create(project); IPath fitLib = project.getFullPath().append(FIT_LIBRARY); javaProject.setRawClasspath(createClassPathEntries(project, fitLib), null); copyLibrary(project); javaProject.setOutputLocation(createOutputFolder(project, DEFAULT_OUTPUT_FOLDER).getFullPath(), null); createOutputFolder(project, fitTests.getText()); createOutputFolder(project, fitResults.getText()); if (!DEFAULT_OUTPUT_FOLDER.equals(fitResults.getText())) { DefaultFolderProperties.setDefinedOutputLocation(project, fitResults.getText()); } if (!DEFAULT_SOURCE_FOLDER.equals(fitFixtures.getText())) { DefaultFolderProperties.setDefinedSourceLocation(project, fitFixtures.getText()); } if (includeExamplesCheck.getSelection()) { copySamples(project); } } catch (CoreException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } catch (IOException e) { handleError(getContainer().getShell(), project, "Could not create project:" + e.getMessage()); return false; } return true; } | private void handleNodeDown(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_NODE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleNodeDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { String ipAddr = activeSvcsRS.getString(1); long serviceID = activeSvcsRS.getLong(2); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleNodeDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleNodeDown: Recording outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID); } catch (SQLException se) { log.warn("Rolling back transaction, nodeDown could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'nodeDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } } | 900,498 |
0 | static String doHttp(String postURL, String text) { String returnValue = null; StringBuffer sb = new StringBuffer(); sb.append("bsh.client=Remote"); sb.append("&bsh.script="); sb.append(URLEncoder.encode(text)); String formData = sb.toString(); try { URL url = new URL(postURL); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); urlcon.setDoOutput(true); urlcon.setDoInput(true); PrintWriter pout = new PrintWriter(new OutputStreamWriter(urlcon.getOutputStream(), "8859_1"), true); pout.print(formData); pout.flush(); int rc = urlcon.getResponseCode(); if (rc != HttpURLConnection.HTTP_OK) System.out.println("Error, HTTP response: " + rc); returnValue = urlcon.getHeaderField("Bsh-Return"); BufferedReader bin = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line; while ((line = bin.readLine()) != null) System.out.println(line); System.out.println("Return Value: " + returnValue); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e2) { System.out.println(e2); } return returnValue; } | public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); } | 900,499 |