id
int32
0
901k
id1
int32
74
23.7M
id2
int32
74
23.7M
func1
stringlengths
234
68.5k
func2
stringlengths
234
68.5k
label
bool
2 classes
0
13,988,825
8,660,836
private void setNodekeyInJsonResponse(String service) throws Exception { String filename = this.baseDirectory + service + ".json"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(filename + ".new")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("NODEKEY", this.key)); } s.close(); fw.close(); (new File(filename + ".new")).renameTo(new File(filename)); }
public void transform(String style, String spec, OutputStream out) throws IOException { URL url = new URL(rootURL, spec); InputStream in = new PatchXMLSymbolsStream(new StripDoctypeStream(url.openStream())); transform(style, in, out); in.close(); }
false
1
80,378
18,548,122
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
private static String loadUrlToString(String a_url) throws IOException { URL l_url1 = new URL(a_url); BufferedReader br = new BufferedReader(new InputStreamReader(l_url1.openStream())); String l_content = ""; String l_ligne = null; l_content = br.readLine(); while ((l_ligne = br.readLine()) != null) { l_content += AA.SL + l_ligne; } return l_content; }
true
2
21,354,223
7,421,563
public String kodetu(String testusoila) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(testusoila.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { new MezuLeiho("Ez da zifraketa algoritmoa aurkitu", "Ados", "Zifraketa Arazoa", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (UnsupportedEncodingException e) { new MezuLeiho("Errorea kodetzerakoan", "Ados", "Kodeketa Errorea", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
private StringBuffer encoder(String arg) { if (arg == null) { arg = ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(arg.getBytes(SysConstant.charset)); } catch (Exception e) { e.printStackTrace(); } return toHex(md5.digest()); }
true
3
15,826,299
19,728,871
public static void printResponseHeaders(String address) { logger.info("Address: " + address); try { URL url = new URL(address); URLConnection conn = url.openConnection(); for (int i = 0; ; i++) { String headerName = conn.getHeaderFieldKey(i); String headerValue = conn.getHeaderField(i); if (headerName == null && headerValue == null) { break; } if (headerName == null) { logger.info(headerValue); continue; } logger.info(headerName + " " + headerValue); } } catch (Exception e) { logger.error("Exception Message: " + e.getMessage()); } }
public static String getEncodedPassword(String buff) { if (buff == null) return null; String t = new String(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(buff.getBytes()); byte[] r = md.digest(); for (int i = 0; i < r.length; i++) { t += toHexString(r[i]); } } catch (Exception e) { e.printStackTrace(); } return t; }
false
4
9,938,081
11,517,213
public void load(String fileName) { BufferedReader bufReader; loaded = false; vector.removeAllElements(); try { if (fileName.startsWith("http:")) { URL url = new URL(fileName); bufReader = new BufferedReader(new InputStreamReader(url.openStream())); } else bufReader = new BufferedReader(new FileReader(fileName)); String inputLine; while ((inputLine = bufReader.readLine()) != null) { if (listener != null) listener.handleLine(inputLine); else vector.add(inputLine); } bufReader.close(); loaded = true; } catch (IOException e) { errorMsg = e.getMessage(); } }
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } }
false
5
18,220,543
17,366,812
private MapProperties readProperties(URL url) { @SuppressWarnings("unchecked") MapProperties properties = new MapProperties(new LinkedHashMap()); InputStream is = null; try { is = url.openStream(); properties.load(is); } catch (IOException ex) { throw new RuntimeException(ex); } finally { StreamUtils.close(is); } return properties; }
public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); }
false
6
22,328,849
17,334,846
protected void doRestoreOrganize() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TABLE; String strSelQuery = "SELECT organize_id,organize_type_id,organize_name,organize_manager," + "organize_describe,work_type,show_order,position_x,position_y " + "FROM " + Common.ORGANIZE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TABLE + " " + "(organize_id,organize_type_id,organize_name,organize_manager," + "organize_describe,work_type,show_order,position_x,position_y) " + "VALUES (?,?,?,?,?,?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_id")); ps.setString(2, result.getString("organize_type_id")); ps.setString(3, result.getString("organize_name")); ps.setString(4, result.getString("organize_manager")); ps.setString(5, result.getString("organize_describe")); ps.setString(6, result.getString("work_type")); ps.setInt(7, result.getInt("show_order")); ps.setInt(8, result.getInt("position_x")); ps.setInt(9, result.getInt("position_y")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganize(): ERROR Inserting data " + "in T_SYS_ORGANIZE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganize(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganize(): SQLException while committing or rollback"); } }
static String encodeEmailAsUserId(String email) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(email.toLowerCase().getBytes()); StringBuilder builder = new StringBuilder(); builder.append("1"); for (byte b : md5.digest()) { builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) })); } return builder.toString().substring(0, 20); } catch (NoSuchAlgorithmException ex) { } return ""; }
false
7
19,130,322
15,710,690
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
@SuppressWarnings("unused") private String getMD5(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return ""; } md5.reset(); md5.update(value.getBytes()); byte[] messageDigest = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } String hashedPassword = hexString.toString(); return hashedPassword; }
true
8
1,111,832
789,472
private void storeFieldMap(WorkingContent c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); try { if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } finally { if (ps != null) ps.close(); } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } }
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
true
9
7,046,481
18,317,332
public InlineImageChunk(URL url) { super(); this.url = url; try { URLConnection urlConn = url.openConnection(); urlConn.setReadTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis, true); this.width = reader.getWidth(0); this.ascent = reader.getHeight(0); this.descent = 0; reader.dispose(); } else System.err.println("cannot read width and height of image " + url + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot read width and height of image " + url + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } }
void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception { int noOfComponents = m_components.length; Statement statement = null; StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating "); pmNoteBuf.append(m_itemNameAbbrev); pmNoteBuf.append(" "); pmNoteBuf.append(m_itemNameValue); final String pmNote = pmNoteBuf.toString(); progressMonitor.setNote(pmNote); try { conn.setAutoCommit(false); int id = -1; if (m_update) { statement = conn.createStatement(); String sql = getUpdateSql(noOfComponents, m_id); statement.executeUpdate(sql); id = m_id; if (m_indexesChanged) deleteComponents(conn, id); } else { PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents); pStmt.executeUpdate(); Integer res = DbCommon.getAutoGenId(parent, context, pStmt); if (res == null) return; id = res.intValue(); } if (!m_update || m_indexesChanged) { PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql()); for (int i = 0; i < noOfComponents; i++) { createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt); } } conn.commit(); m_itemTable.getPrimaryId().setVal(m_item, id); m_itemCache.updateCache(m_item, id); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
false
10
190,292
978,946
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()); } }
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(); } }
true
11
19,653,581
9,312,243
public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } }
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
true
12
369,572
4,761,833
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
private void copyFileToDir(MyFile file, MyFile to, wlPanel panel) throws IOException { Utilities.print("started copying " + file.getAbsolutePath() + "\n"); FileOutputStream fos = new FileOutputStream(new File(to.getAbsolutePath())); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath())); FileChannel fic = fis.getChannel(); Date d1 = new Date(); long amount = foc.transferFrom(fic, rest, fic.size() - rest); fic.close(); foc.force(false); foc.close(); Date d2 = new Date(); long time = d2.getTime() - d1.getTime(); double secs = time / 1000.0; double rate = amount / secs; frame.getStatusArea().append(secs + "s " + "amount: " + Utilities.humanReadable(amount) + " rate: " + Utilities.humanReadable(rate) + "/s\n", "black"); panel.updateView(); }
true
13
2,285,441
16,987,999
static synchronized Person lookup(PhoneNumber number, String siteName) { Vector<Person> foundPersons = new Vector<Person>(5); if (number.isFreeCall()) { Person p = new Person("", "FreeCall"); p.addNumber(number); foundPersons.add(p); } else if (number.isSIPNumber() || number.isQuickDial()) { Person p = new Person(); p.addNumber(number); foundPersons.add(p); } else if (ReverseLookup.rlsMap.containsKey(number.getCountryCode())) { nummer = number.getAreaNumber(); rls_list = ReverseLookup.rlsMap.get(number.getCountryCode()); Debug.info("Begin reverselookup for: " + nummer); if (nummer.startsWith(number.getCountryCode())) nummer = nummer.substring(number.getCountryCode().length()); city = ""; for (int i = 0; i < rls_list.size(); i++) { yield(); rls = rls_list.get(i); if (!siteName.equals("") && !siteName.equals(rls.getName())) { Debug.warning("This lookup should be done using a specific site, skipping"); continue; } prefix = rls.getPrefix(); ac_length = rls.getAreaCodeLength(); if (!nummer.startsWith(prefix)) nummer = prefix + nummer; urlstr = rls.getURL(); if (urlstr.contains("$AREACODE")) { urlstr = urlstr.replaceAll("\\$AREACODE", nummer.substring(prefix.length(), ac_length + prefix.length())); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else if (urlstr.contains("$PFXAREACODE")) { urlstr = urlstr.replaceAll("\\$PFXAREACODE", nummer.substring(0, prefix.length() + ac_length)); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else urlstr = urlstr.replaceAll("\\$NUMBER", nummer); Debug.info("Reverse lookup using: " + urlstr); url = null; data = new String[dataLength]; try { url = new URL(urlstr); if (url != null) { try { con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(15000); con.addRequestProperty("User-Agent", userAgent); con.connect(); header = ""; charSet = ""; for (int j = 0; ; j++) { String headerName = con.getHeaderFieldKey(j); String headerValue = con.getHeaderField(j); if (headerName == null && headerValue == null) { break; } if ("content-type".equalsIgnoreCase(headerName)) { String[] split = headerValue.split(";", 2); for (int k = 0; k < split.length; k++) { if (split[k].trim().toLowerCase().startsWith("charset=")) { String[] charsetSplit = split[k].split("="); charSet = charsetSplit[1].trim(); } } } header += headerName + ": " + headerValue + " | "; } Debug.debug("Header of " + rls.getName() + ":" + header); Debug.debug("CHARSET : " + charSet); BufferedReader d; if (charSet.equals("")) { d = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); } else { d = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } int lines = 0; while (null != ((str = d.readLine()))) { data[lines] = str; yield(); if (lines >= dataLength) { System.err.println("Result > " + dataLength + " Lines"); break; } lines++; } d.close(); Debug.info("Begin processing response from " + rls.getName()); for (int j = 0; j < rls.size(); j++) { yield(); firstname = ""; lastname = ""; company = ""; street = ""; zipcode = ""; city = ""; Person p = null; patterns = rls.getEntry(j); Pattern namePattern = null; Pattern streetPattern = null; Pattern cityPattern = null; Pattern zipcodePattern = null; Pattern firstnamePattern = null; Pattern lastnamePattern = null; Matcher nameMatcher = null; Matcher streetMatcher = null; Matcher cityMatcher = null; Matcher zipcodeMatcher = null; Matcher firstnameMatcher = null; Matcher lastnameMatcher = null; if (!patterns[ReverseLookupSite.NAME].equals("") && (patterns[ReverseLookupSite.FIRSTNAME].equals("") && patterns[ReverseLookupSite.LASTNAME].equals(""))) { namePattern = Pattern.compile(patterns[ReverseLookupSite.NAME]); } if (!patterns[ReverseLookupSite.STREET].equals("")) { streetPattern = Pattern.compile(patterns[ReverseLookupSite.STREET]); } if (!patterns[ReverseLookupSite.CITY].equals("")) { cityPattern = Pattern.compile(patterns[ReverseLookupSite.CITY]); } if (!patterns[ReverseLookupSite.ZIPCODE].equals("")) { zipcodePattern = Pattern.compile(patterns[ReverseLookupSite.ZIPCODE]); } if (!patterns[ReverseLookupSite.FIRSTNAME].equals("")) { firstnamePattern = Pattern.compile(patterns[ReverseLookupSite.FIRSTNAME]); } if (!patterns[ReverseLookupSite.LASTNAME].equals("")) { lastnamePattern = Pattern.compile(patterns[ReverseLookupSite.LASTNAME]); } for (int line = 0; line < dataLength; line++) { if (data[line] != null) { int spaceAlternative = 160; data[line] = data[line].replaceAll(new Character((char) spaceAlternative).toString(), " "); if (lastnamePattern != null) { lastnameMatcher = lastnamePattern.matcher(data[line]); if (lastnameMatcher.find()) { str = ""; for (int k = 1; k <= lastnameMatcher.groupCount(); k++) { if (lastnameMatcher.group(k) != null) str = str + lastnameMatcher.group(k).trim() + " "; } lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if ("lastname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setLastName(lastname); } } } yield(); if (firstnamePattern != null) { firstnameMatcher = firstnamePattern.matcher(data[line]); if (firstnameMatcher.find()) { str = ""; for (int k = 1; k <= firstnameMatcher.groupCount(); k++) { if (firstnameMatcher.group(k) != null) str = str + firstnameMatcher.group(k).trim() + " "; } firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); firstname = firstname.trim(); firstname = firstname.replaceAll(",", ""); firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); if ("firstname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); } } } yield(); if (namePattern != null) { nameMatcher = namePattern.matcher(data[line]); if (nameMatcher.find()) { str = ""; for (int k = 1; k <= nameMatcher.groupCount(); k++) { if (nameMatcher.group(k) != null) str = str + nameMatcher.group(k).trim() + " "; } String[] split; split = str.split(" ", 2); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(split[0])); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if (split[1].length() > 0) { firstname = HTMLUtil.stripEntities(split[1]); if ((firstname.indexOf(" ") > -1) && (firstname.indexOf(" u.") == -1)) { company = JFritzUtils.removeLeadingSpaces(firstname.substring(firstname.indexOf(" ")).trim()); firstname = JFritzUtils.removeLeadingSpaces(firstname.substring(0, firstname.indexOf(" ")).trim()); } else { firstname = JFritzUtils.removeLeadingSpaces(firstname.replaceAll(" u. ", " und ")); } } firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); firstname = firstname.trim(); company = company.replaceAll("%20", " "); company = JFritzUtils.replaceSpecialCharsUTF(company); company = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(company)); company = JFritzUtils.removeDuplicateWhitespace(company); company = company.trim(); if ("name".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); if (company.length() > 0) { p.addNumber(number.getIntNumber(), "business"); } else { p.addNumber(number.getIntNumber(), "home"); } foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); p.setLastName(lastname); p.setCompany(company); } } } yield(); if (streetPattern != null) { streetMatcher = streetPattern.matcher(data[line]); if (streetMatcher.find()) { str = ""; for (int k = 1; k <= streetMatcher.groupCount(); k++) { if (streetMatcher.group(k) != null) str = str + streetMatcher.group(k).trim() + " "; } street = str.replaceAll("%20", " "); street = JFritzUtils.replaceSpecialCharsUTF(street); street = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(street)); street = JFritzUtils.removeDuplicateWhitespace(street); street = street.trim(); if ("street".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setStreet(street); } } } yield(); if (cityPattern != null) { cityMatcher = cityPattern.matcher(data[line]); if (cityMatcher.find()) { str = ""; for (int k = 1; k <= cityMatcher.groupCount(); k++) { if (cityMatcher.group(k) != null) str = str + cityMatcher.group(k).trim() + " "; } city = str.replaceAll("%20", " "); city = JFritzUtils.replaceSpecialCharsUTF(city); city = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(city)); city = JFritzUtils.removeDuplicateWhitespace(city); city = city.trim(); if ("city".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setCity(city); } } } yield(); if (zipcodePattern != null) { zipcodeMatcher = zipcodePattern.matcher(data[line]); if (zipcodeMatcher.find()) { str = ""; for (int k = 1; k <= zipcodeMatcher.groupCount(); k++) { if (zipcodeMatcher.group(k) != null) str = str + zipcodeMatcher.group(k).trim() + " "; } zipcode = str.replaceAll("%20", " "); zipcode = JFritzUtils.replaceSpecialCharsUTF(zipcode); zipcode = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(zipcode)); zipcode = JFritzUtils.removeDuplicateWhitespace(zipcode); zipcode = zipcode.trim(); if ("zipcode".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setPostalCode(zipcode); } } } } } if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) break; } yield(); if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) { if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } return foundPersons.get(0); } } catch (IOException e1) { Debug.error("Error while retrieving " + urlstr); } } } catch (MalformedURLException e) { Debug.error("URL invalid: " + urlstr); } } yield(); Debug.warning("No match for " + nummer + " found"); if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } Person p = new Person("", "", "", "", "", city, "", ""); p.addNumber(number.getAreaNumber(), "home"); return p; } else { Debug.warning("No reverse lookup sites for: " + number.getCountryCode()); Person p = new Person(); p.addNumber(number.getAreaNumber(), "home"); if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(number.getIntNumber()); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(number.getIntNumber()); p.setCity(city); return p; } return new Person("not found", "Person"); }
private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
false
14
13,041,693
116,038
@Override public void vote(String urlString, Map<String, String> headData, Map<String, String> paramData) { HttpURLConnection httpConn = null; try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); String cookies = getCookies(httpConn); System.out.println(cookies); BufferedReader post = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "GB2312")); String text = null; while ((text = post.readLine()) != null) { System.out.println(text); } } catch (MalformedURLException e) { e.printStackTrace(); throw new VoteBeanException("网址不正确", e); } catch (IOException e) { e.printStackTrace(); throw new VoteBeanException("不能打开网址", e); } }
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!"); }
false
15
14,157,859
3,791,822
static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); }
public Void doInBackground() { setProgress(0); for (int i = 0; i < uploadFiles.size(); i++) { String filePath = uploadFiles.elementAt(i).getFilePath(); String fileName = uploadFiles.elementAt(i).getFileName(); String fileMsg = "Uploading file " + (i + 1) + "/" + uploadFiles.size() + "\n"; this.publish(fileMsg); try { File inFile = new File(filePath); FileInputStream in = new FileInputStream(inFile); byte[] inBytes = new byte[(int) chunkSize]; int count = 1; int maxCount = (int) (inFile.length() / chunkSize); if (inFile.length() % chunkSize > 0) { maxCount++; } int readCount = 0; readCount = in.read(inBytes); while (readCount > 0) { File splitFile = File.createTempFile("upl", null, null); String splitName = splitFile.getPath(); FileOutputStream out = new FileOutputStream(splitFile); out.write(inBytes, 0, readCount); out.close(); boolean chunkFinal = (count == maxCount); fileMsg = " - Sending chunk " + count + "/" + maxCount + ": "; this.publish(fileMsg); boolean uploadSuccess = false; int uploadTries = 0; while (!uploadSuccess && uploadTries <= 5) { uploadTries++; boolean uploadStatus = upload(splitName, fileName, count, chunkFinal); if (uploadStatus) { fileMsg = "OK\n"; this.publish(fileMsg); uploadSuccess = true; } else { fileMsg = "ERROR\n"; this.publish(fileMsg); uploadSuccess = false; } } if (!uploadSuccess) { fileMsg = "There was an error uploading your files. Please let the pipeline administrator know about this problem. Cut and paste the messages in this box, and supply them.\n"; this.publish(fileMsg); errorFlag = true; return null; } float thisProgress = (count * 100) / (maxCount); float completeProgress = (i * (100 / uploadFiles.size())); float totalProgress = completeProgress + (thisProgress / uploadFiles.size()); setProgress((int) totalProgress); splitFile.delete(); readCount = in.read(inBytes); count++; } } catch (Exception e) { this.publish(e.toString()); } } return null; }
true
16
23,270,032
21,907,871
public void checkin(Object _document) { this.document = (Document) _document; synchronized (url) { OutputStream outputStream = null; try { if ("file".equals(url.getProtocol())) { outputStream = new FileOutputStream(url.getFile()); } else { URLConnection connection = url.openConnection(); connection.setDoOutput(true); outputStream = connection.getOutputStream(); } new XMLOutputter(" ", true).output(this.document, outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
false
17
17,586,131
14,533,184
protected void update(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(pstmt, conn); } }
public boolean delete(int id) { boolean deletionOk = false; Connection conn = null; try { conn = db.getConnection(); conn.setAutoCommit(false); String sql = "DELETE FROM keyphrases WHERE website_id=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); deletionOk = ps.executeUpdate() == 1; ps.close(); sql = "DELETE FROM websites WHERE id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); boolean success = ps.executeUpdate() == 1; deletionOk = deletionOk && success; ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException sqle) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException sex) { throw new OsseoFailure("SQL error: roll back failed. ", sex); } throw new OsseoFailure("SQL error: cannot remove website with id " + id + ".", sqle); } finally { db.putConnection(conn); } return deletionOk; }
true
18
18,865,693
1,477,578
private static void copyFile(File inputFile, File outputFile) throws IOException { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = 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(); } }
true
19
5,506,807
10,176,882
public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); }
@SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
false
20
2,746,011
5,105,540
@RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; URLConnection conn = url.openConnection(); boolean isShout = false; int toRead = 4; byte[] head = new byte[toRead]; conn.setRequestProperty("Icy-Metadata", "1"); BufferedInputStream bInputStream = new BufferedInputStream(conn.getInputStream()); bInputStream.mark(toRead); int read = bInputStream.read(head, 0, toRead); if ((read > 2) && (((head[0] == 'I') | (head[0] == 'i')) && ((head[1] == 'C') | (head[1] == 'c')) && ((head[2] == 'Y') | (head[2] == 'y')))) isShout = true; bInputStream.reset(); InputStream inputStream = null; if (isShout == true) { IcyInputStream icyStream = new IcyInputStream(bInputStream); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { String metaint = conn.getHeaderField("icy-metaint"); if (metaint != null) { IcyInputStream icyStream = new IcyInputStream(bInputStream, metaint); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { inputStream = bInputStream; } } AudioInputStream audioInputStream = null; try { audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReader.getAudioInputStream(URL): end"); } return audioInputStream; }
false
21
3,287,282
13,431,536
public void googleImageSearch(String start) { try { String u = "http://images.google.com/images?q=" + custom + start; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String text = ""; String lin = ""; while ((lin = readIn.readLine()) != null) { text += lin; } readIn.close(); if (text.contains("\n")) { text = text.replace("\n", ""); } String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E"); for (String s : array) { if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&amp;")) { String s1 = s.substring(0, s.indexOf("&amp;")); googleImages.add(s1); } } } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton4.setEnabled(true); jButton2.setEnabled(true); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); }
@Override public int updateStatus(UserInfo userInfo, String status) throws Exception { OAuthConsumer consumer = SnsConstant.getOAuthConsumer(SnsConstant.SOHU); consumer.setTokenWithSecret(userInfo.getAccessToken(), userInfo.getAccessSecret()); try { URL url = new URL(SnsConstant.SOHU_UPDATE_STATUS_URL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); HttpParameters para = new HttpParameters(); para.put("status", StringUtils.utf8Encode(status).replaceAll("\\+", "%20")); consumer.setAdditionalParameters(para); consumer.sign(request); OutputStream ot = request.getOutputStream(); ot.write(("status=" + URLEncoder.encode(status, "utf-8")).replaceAll("\\+", "%20").getBytes()); ot.flush(); ot.close(); System.out.println("Sending request..."); request.connect(); System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String b = null; while ((b = reader.readLine()) != null) { System.out.println(b); } return SnsConstant.SOHU_UPDATE_STATUS_SUCC_WHAT; } catch (Exception e) { SnsConstant.SOHU_OPERATOR_FAIL_REASON = processException(e.getMessage()); return SnsConstant.SOHU_UPDATE_STATUS_FAIL_WHAT; } }
false
22
16,744,397
18,315,736
public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); }
private List<String> getTaxaList() { List<String> taxa = new Vector<String>(); String domain = m_domain.getStringValue(); String id = ""; if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota"; try { URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; String line = ""; reader.readLine(); while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]); ENADataHolder.instance().put(ena.desc, ena); taxa.add(ena.desc); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return taxa; }
false
23
18,269,744
10,140,251
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; }
protected String contentString() { String result = null; URL url; String encoding = null; try { url = url(); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); for (Enumeration e = bindingKeys().objectEnumerator(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("?")) { connection.setRequestProperty(key.substring(1), valueForBinding(key).toString()); } } if (connection.getContentEncoding() != null) { encoding = connection.getContentEncoding(); } if (encoding == null) { encoding = (String) valueForBinding("encoding"); } if (encoding == null) { encoding = "UTF-8"; } InputStream stream = connection.getInputStream(); byte bytes[] = ERXFileUtilities.bytesFromInputStream(stream); stream.close(); result = new String(bytes, encoding); } catch (IOException ex) { throw NSForwardException._runtimeExceptionForThrowable(ex); } return result; }
false
24
14,876,163
3,260,787
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(); } }
public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).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(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
true
25
14,313,659
10,109,343
private int writeTraceFile(final File destination_file, final String trace_file_name, final String trace_file_path) { URL url = null; BufferedInputStream is = null; FileOutputStream fo = null; BufferedOutputStream os = null; int b = 0; if (destination_file == null) { return 0; } try { url = new URL("http://" + trace_file_path + "/" + trace_file_name); is = new BufferedInputStream(url.openStream()); fo = new FileOutputStream(destination_file); os = new BufferedOutputStream(fo); while ((b = is.read()) != -1) { os.write(b); } os.flush(); is.close(); os.close(); } catch (Exception e) { System.err.println(url.toString()); Utilities.unexpectedException(e, this, CONTACT); return 0; } return 1; }
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/tuneGridMaster.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); tune_x[i][j] = Double.parseDouble(st.nextToken()); gridmin = tune_x[i][j]; temp_prev = tune_x[i][j]; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } tune_x[i][j] = temp_new; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } gridmax = tune_x[i][j - 1]; }
false
26
13,745,376
10,567,003
public IStatus runInUIThread(IProgressMonitor monitor) { monitor.beginTask(Strings.MSG_CONNECT_SERVER, 3); InputStream in = null; try { URL url = createOpenUrl(resource, pref); if (url != null) { URLConnection con = url.openConnection(); monitor.worked(1); monitor.setTaskName(Strings.MSG_WAIT_FOR_SERVER); con.connect(); in = con.getInputStream(); in.read(); monitor.worked(1); monitor.setTaskName(NLS.bind(Strings.MSG_OPEN_URL, url)); open(url, resource.getProject(), pref); monitor.worked(1); } } catch (ConnectException con) { if (count < 3) { ConnectAndOpenJob job = new ConnectAndOpenJob(resource, pref, ++count); job.schedule(1000L); } else { Activator.log(con); } } catch (Exception e) { Activator.log(e); } finally { Streams.close(in); monitor.done(); } return Status.OK_STATUS; }
private InputStream loadSource(String url) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(HTTP.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)"); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return entity.getContent(); }
false
27
22,075,089
20,623,710
public static void executa(String arquivo, String filial, String ip) { String drive = arquivo.substring(0, 2); if (drive.indexOf(":") == -1) drive = ""; Properties p = Util.lerPropriedades(arquivo); String servidor = p.getProperty("servidor"); String impressora = p.getProperty("fila"); String arqRel = new String(drive + p.getProperty("arquivo")); String copias = p.getProperty("copias"); if (filial.equalsIgnoreCase(servidor)) { Socket s = null; int tentativas = 0; boolean conectado = false; while (!conectado) { try { tentativas++; System.out.println("Tentando conectar " + ip + " (" + tentativas + ")"); s = new Socket(ip, 7000); conectado = s.isConnected(); } catch (ConnectException ce) { System.err.println(ce.getMessage()); System.err.println(ce.getCause()); } catch (UnknownHostException uhe) { System.err.println(uhe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } FileInputStream in = null; BufferedOutputStream out = null; try { in = new FileInputStream(new File(arqRel)); out = new BufferedOutputStream(new GZIPOutputStream(s.getOutputStream())); } catch (FileNotFoundException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } String arqtr = arqRel.substring(2); System.out.println("Proximo arquivo: " + arqRel + " ->" + arqtr); while (arqtr.length() < 30) arqtr += " "; while (impressora.length() < 30) impressora += " "; byte aux[] = new byte[30]; byte cop[] = new byte[2]; try { aux = arqtr.getBytes("UTF8"); out.write(aux); aux = impressora.getBytes("UTF8"); out.write(aux); cop = copias.getBytes("UTF8"); out.write(cop); out.flush(); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } byte b[] = new byte[1024]; int nBytes; try { while ((nBytes = in.read(b)) != -1) out.write(b, 0, nBytes); out.flush(); out.close(); in.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("Arquivo " + arqRel + " foi transmitido. \n\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } SimpleDateFormat dfArq = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dfLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String arqLog = "log" + filial + dfArq.format(new Date()) + ".txt"; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(arqLog, true)); } catch (IOException e) { e.printStackTrace(); } pw.println("Arquivo: " + arquivo + " " + dfLog.format(new Date())); pw.flush(); pw.close(); File f = new File(arquivo); while (!f.delete()) { System.out.println("Erro apagando " + arquivo); } } }
public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
true
28
19,217,522
10,385,493
boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
29
7,681,426
11,717,079
public void extractProfile(String parentDir, String fileName, String profileName) { try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; if (createProfileDirectory(profileName, parentDir)) { debug("the profile directory created .starting the profile extraction"); String profilePath = parentDir + File.separator + fileName; zipinputstream = new ZipInputStream(new FileInputStream(profilePath)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(parentDir + File.separator + profileName + File.separator + newFile.getName()); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); debug("deleting the profile.zip file"); File newFile = new File(profilePath); if (newFile.delete()) { debug("the " + "[" + profilePath + "]" + " deleted successfully"); } else { debug("profile" + "[" + profilePath + "]" + "deletion fail"); throw new IllegalArgumentException("Error: deletion error!"); } } else { debug("error creating the profile directory"); } } catch (Exception e) { e.printStackTrace(); } }
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(); } }
true
30
8,831,301
8,365,268
public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } button.setEnabled(true); }
public static String[] readStats() throws Exception { URL url = null; BufferedReader reader = null; StringBuilder stringBuilder; try { url = new URL("http://localhost:" + port + webctx + "/shared/js/libOO/health_check.sjs"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(10 * 1000); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString().split(","); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } }
true
31
308,643
21,172,450
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 static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
true
32
11,322,573
3,224,152
private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
true
33
13,569,337
11,394,767
public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
public static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
true
34
254,039
16,016,623
protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } }
@Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id"); final File file = new File(path, filename + ".html"); logger.debug("Getting static content from: " + file.getPath()); final InputStream is = getServletContext().getResourceAsStream(file.getPath()); OutputStream out = null; if (is != null) { try { out = response.getOutputStream(); IOUtils.copy(is, out); } catch (IOException ioex) { logger.error(ioex); } finally { is.close(); if (out != null) { out.close(); } } } return null; }
true
35
4,147,990
1,663,419
public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.close(); }
private 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(); } }
true
36
16,603,670
12,576,210
private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
public static FTPClient createConnection(String hostname, int port, char[] username, char[] password, String workingDirectory, FileSystemOptions fileSystemOptions) throws FileSystemException { if (username == null) username = "anonymous".toCharArray(); if (password == null) password = "anonymous".toCharArray(); try { final FTPClient client = new FTPClient(); String key = FtpFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions); if (key != null) { FTPClientConfig config = new FTPClientConfig(key); String serverLanguageCode = FtpFileSystemConfigBuilder.getInstance().getServerLanguageCode(fileSystemOptions); if (serverLanguageCode != null) config.setServerLanguageCode(serverLanguageCode); String defaultDateFormat = FtpFileSystemConfigBuilder.getInstance().getDefaultDateFormat(fileSystemOptions); if (defaultDateFormat != null) config.setDefaultDateFormatStr(defaultDateFormat); String recentDateFormat = FtpFileSystemConfigBuilder.getInstance().getRecentDateFormat(fileSystemOptions); if (recentDateFormat != null) config.setRecentDateFormatStr(recentDateFormat); String serverTimeZoneId = FtpFileSystemConfigBuilder.getInstance().getServerTimeZoneId(fileSystemOptions); if (serverTimeZoneId != null) config.setServerTimeZoneId(serverTimeZoneId); String[] shortMonthNames = FtpFileSystemConfigBuilder.getInstance().getShortMonthNames(fileSystemOptions); if (shortMonthNames != null) { StringBuffer shortMonthNamesStr = new StringBuffer(40); for (int i = 0; i < shortMonthNames.length; i++) { if (shortMonthNamesStr.length() > 0) shortMonthNamesStr.append("|"); shortMonthNamesStr.append(shortMonthNames[i]); } config.setShortMonthNames(shortMonthNamesStr.toString()); } client.configure(config); } FTPFileEntryParserFactory myFactory = FtpFileSystemConfigBuilder.getInstance().getEntryParserFactory(fileSystemOptions); if (myFactory != null) client.setParserFactory(myFactory); try { client.connect(hostname, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname); if (!client.login(UserAuthenticatorUtils.toString(username), UserAuthenticatorUtils.toString(password))) throw new FileSystemException("vfs.provider.ftp/login.error", new Object[] { hostname, UserAuthenticatorUtils.toString(username) }, null); if (!client.setFileType(FTP.BINARY_FILE_TYPE)) throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname); Integer dataTimeout = FtpFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions); if (dataTimeout != null) client.setDataTimeout(dataTimeout.intValue()); try { FtpFileSystemConfigBuilder.getInstance().setHomeDir(fileSystemOptions, client.printWorkingDirectory()); } catch (IOException ex) { throw new FileSystemException("Error obtaining working directory!"); } Boolean userDirIsRoot = FtpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(fileSystemOptions); if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue())) if (!client.changeWorkingDirectory(workingDirectory)) throw new FileSystemException("vfs.provider.ftp/change-work-directory.error", workingDirectory); Boolean passiveMode = FtpFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions); if (passiveMode != null && passiveMode.booleanValue()) client.enterLocalPassiveMode(); } catch (final IOException e) { if (client.isConnected()) client.disconnect(); throw e; } return client; } catch (final Exception exc) { throw new FileSystemException("vfs.provider.ftp/connect.error", new Object[] { hostname }, exc); } }
false
37
19,825,038
9,385,633
public static byte[] post(String path, Map<String, String> params, String encode) throws Exception { StringBuilder parambuilder = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { parambuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } parambuilder.deleteCharAt(parambuilder.length() - 1); } byte[] data = parambuilder.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Connection", "Keep-Alive"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { return StreamTool.readInputStream(conn.getInputStream()); } return null; }
protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
false
38
810,724
22,207,815
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!"); }
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
true
39
1,643,091
23,277,837
private static void download(String urlString) throws IOException { URL url = new URL(urlString); url = handleRedirectUrl(url); URLConnection cn = url.openConnection(); Utils.setHeader(cn); long fileLength = cn.getContentLength(); Statics.getInstance().setFileLength(fileLength); long packageLength = fileLength / THREAD_COUNT; long leftLength = fileLength % THREAD_COUNT; String fileName = Utils.decodeURLFileName(url); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength)); CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1); long pos = 0; for (int i = 0; i < THREAD_COUNT; i++) { long endPos = pos + packageLength; if (leftLength > 0) { endPos++; leftLength--; } new Thread(new DownloadThread(latch, url, file, pos, endPos)).start(); pos = endPos; } new Thread(new MoniterThread(latch)).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
private File download(String filename, URL url) { int size = -1; int received = 0; try { fireDownloadStarted(filename); File file = createFile(filename); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); System.out.println("下载资源:" + filename + ", url=" + url); // BufferedInputStream bis = new // BufferedInputStream(url.openStream()); InputStream bis = url.openStream(); byte[] buf = new byte[1024]; int count = 0; long lastUpdate = 0; size = bis.available(); while ((count = bis.read(buf)) != -1) { bos.write(buf, 0, count); received += count; long now = System.currentTimeMillis(); if (now - lastUpdate > 500) { fireDownloadUpdate(filename, size, received); lastUpdate = now; } } bos.close(); System.out.println("资源下载完毕:" + filename); fireDownloadCompleted(filename); return file; } catch (IOException e) { System.out.println("下载资源失败:" + filename + ", error=" + e.getMessage()); fireDownloadInterrupted(filename); if (!(e instanceof FileNotFoundException)) { e.printStackTrace(); } } return null; }
false
40
1,214,975
21,172,450
public static void writeToFile(InputStream input, File file, ProgressListener listener, long length) { OutputStream output = null; try { output = new CountingOutputStream(new FileOutputStream(file), listener, length); IOUtils.copy(input, output); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } }
public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
true
41
9,070,085
17,832,320
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
public void run() { Pair p = null; try { while ((p = queue.pop()) != null) { GetMethod get = new GetMethod(p.getRemoteUri()); try { get.setFollowRedirects(true); get.setRequestHeader("Mariner-Application", "prerenderer"); get.setRequestHeader("Mariner-DeviceName", deviceName); int iGetResultCode = httpClient.executeMethod(get); if (iGetResultCode != 200) { throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri()); } InputStream is = get.getResponseBodyAsStream(); File localFile = new File(deviceFile, p.getLocalUri()); localFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(localFile); IOUtils.copy(is, os); os.close(); } finally { get.releaseConnection(); } } } catch (Exception ex) { result = ex; } }
false
42
10,445,018
19,295,210
public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
public static String generateHash(String value) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(value.getBytes()); } catch (NoSuchAlgorithmException e) { log.error("Could not find the requested hash method: " + e.getMessage()); } byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); }
true
43
6,988,217
701,471
public void testQueryForBinary() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + "images/photo.png"); assertNotNull(source); assertEquals(false, source.exists()); OutputStream os = source.getOutputStream(); assertNotNull(os); String content = "foo is a bar"; os.write(content.getBytes()); os.flush(); os.close(); QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + "images?/*[contains(local-name(), 'photo.png')]"); assertNotNull(qResult); Collection results = qResult.getChildren(); assertEquals(1, results.size()); Iterator it = results.iterator(); JCRNodeSource rSrc = (JCRNodeSource) it.next(); InputStream rSrcIn = rSrc.getInputStream(); ByteArrayOutputStream actualOut = new ByteArrayOutputStream(); IOUtils.copy(rSrcIn, actualOut); rSrcIn.close(); assertEquals(content, actualOut.toString()); actualOut.close(); rSrc.delete(); }
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; } }
true
44
4,855,600
12,853,333
public void schema(final Row row, TestResults testResults) throws Exception { String urlString = row.text(1); String schemaBase = null; if (row.cellExists(2)) { schemaBase = row.text(2); } try { StreamSource schemaSource; if (urlString.startsWith(CLASS_PREFIX)) { InputStream schema = XmlValidator.class.getClassLoader().getResourceAsStream(urlString.substring(CLASS_PREFIX.length())); schemaSource = new StreamSource(schema); } else { URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); schemaSource = new StreamSource(inputStream); } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if (schemaBase != null) { DefaultLSResourceResolver resolver = new DefaultLSResourceResolver(schemaBase); factory.setResourceResolver(resolver); } factory.newSchema(new URL(urlString)); Validator validator = factory.newSchema(schemaSource).newValidator(); StreamSource source = new StreamSource(new StringReader(xml)); validator.validate(source); row.pass(testResults); } catch (SAXException e) { Loggers.SERVICE_LOG.warn("schema error", e); throw new FitFailureException(e.getMessage()); } catch (IOException e) { Loggers.SERVICE_LOG.warn("schema error", e); throw new FitFailureException(e.getMessage()); } }
public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
false
45
1,989,226
11,961,013
public void actualizar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; registroActualizado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); ms = conn.prepareStatement(SENTENCIA_UPDATE); if (fechaOficio != null && !fechaOficio.equals("")) { if (fechaOficio.matches("\\d{8}")) { ms.setInt(1, Integer.parseInt(fechaOficio)); } else { int fzafent = 0; try { fechaTest = dateF.parse(fechaOficio); Calendar cal = Calendar.getInstance(); cal.setTime(fechaTest); DateFormat date1 = new SimpleDateFormat("yyyyMMdd"); fzafent = Integer.parseInt(date1.format(fechaTest)); } catch (Exception e) { } ms.setInt(1, fzafent); } } else { ms.setInt(1, 0); } ms.setString(2, descripcion); ms.setInt(3, Integer.parseInt(anoSalida)); ms.setInt(4, Integer.parseInt(oficinaSalida)); ms.setInt(5, Integer.parseInt(numeroSalida)); ms.setString(6, nulo); ms.setString(7, motivosNulo); ms.setString(8, usuarioNulo); if (fechaNulo != null && !fechaNulo.equals("")) { int fzafent = 0; try { fechaTest = dateF.parse(fechaNulo); Calendar cal = Calendar.getInstance(); cal.setTime(fechaTest); DateFormat date1 = new SimpleDateFormat("yyyyMMdd"); fzafent = Integer.parseInt(date1.format(fechaTest)); } catch (Exception e) { } ms.setInt(9, fzafent); } else { ms.setInt(9, 0); } if (fechaEntrada != null && !fechaEntrada.equals("")) { int fzafent = 0; try { fechaTest = dateF.parse(fechaEntrada); Calendar cal = Calendar.getInstance(); cal.setTime(fechaTest); DateFormat date1 = new SimpleDateFormat("yyyyMMdd"); fzafent = Integer.parseInt(date1.format(fechaTest)); } catch (Exception e) { } ms.setInt(10, fzafent); } else { ms.setInt(10, 0); } ms.setString(11, descartadoEntrada); ms.setString(12, usuarioEntrada); ms.setString(13, motivosDescarteEntrada); ms.setInt(14, anoEntrada != null ? Integer.parseInt(anoEntrada) : 0); ms.setInt(15, oficinaEntrada != null ? Integer.parseInt(oficinaEntrada) : 0); ms.setInt(16, numeroEntrada != null ? Integer.parseInt(numeroEntrada) : 0); ms.setInt(17, anoOficio != null ? Integer.parseInt(anoOficio) : 0); ms.setInt(18, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0); ms.setInt(19, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0); int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } conn.commit(); } catch (Exception ex) { System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha actualitzat la taula de gestió dels ofici de remissió.", ex); } finally { ToolsBD.closeConn(conn, ms, null); } }
public static Builder fromURL(URL url) { try { InputStream in = null; try { in = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; byte[] buf = new byte[4096]; while ((read = in.read(buf)) >= 0) { if (read > 0) { baos.write(buf, 0, read); } } StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray()); try { b.setSystemId(url.toURI().toString()); } catch (URISyntaxException use) { b.setSystemId(url.toString()); } return b; } finally { if (in != null) { in.close(); } } } catch (IOException ex) { throw new XMLUnitException(ex); } }
false
46
15,596,950
14,782,656
private static ImageIcon tryLoadImageIconFromResource(String filename, String path, int width, int height) { ImageIcon icon = null; try { URL url = cl.getResource(path + pathSeparator + fixFilename(filename)); if (url != null && url.openStream() != null) { icon = new ImageIcon(url); } } catch (Exception e) { } if (icon == null) { return null; } if ((icon.getIconWidth() == width) && (icon.getIconHeight() == height)) { return icon; } else { return new ImageIcon(icon.getImage().getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH)); } }
private static Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
false
47
249,428
6,166,363
public boolean onStart() { log("Starting up, this may take a minute..."); gui = new ApeAtollGUI(); gui.setVisible(true); while (waitGUI) { sleep(100); } URLConnection url = null; BufferedReader in = null; BufferedWriter out = null; if (checkUpdates) { try { url = new URL("http://www.voltrex.be/rsbot/VoltrexApeAtollVERSION.txt").openConnection(); in = new BufferedReader(new InputStreamReader(url.getInputStream())); if (Double.parseDouble(in.readLine()) > properties.version()) { if (JOptionPane.showConfirmDialog(null, "Update found. Do you want to update?") == 0) { JOptionPane.showMessageDialog(null, "Please choose 'VoltrexApeAtoll.java' in your scripts/sources folder."); JFileChooser fc = new JFileChooser(); if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { url = new URL("http://www.voltrex.be/rsbot/VoltrexApeAtoll.java").openConnection(); in = new BufferedReader(new InputStreamReader(url.getInputStream())); out = new BufferedWriter(new FileWriter(fc.getSelectedFile().getPath())); String inp; while ((inp = in.readLine()) != null) { out.write(inp); out.newLine(); out.flush(); } log("Script successfully downloaded. Please recompile."); return false; } else log("Update canceled"); } else log("Update canceled"); } else log("You have the latest version."); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log("Problem getting version. Please report this bug!"); } } try { BKG = ImageIO.read(new URL("http://i54.tinypic.com/2egcfaw.jpg")); } catch (final java.io.IOException e) { e.printStackTrace(); } try { final URL cursorURL = new URL("http://imgur.com/i7nMG.png"); final URL cursor80URL = new URL("http://imgur.com/8k9op.png"); normal = ImageIO.read(cursorURL); clicked = ImageIO.read(cursor80URL); } catch (MalformedURLException e) { log.info("Unable to buffer cursor."); } catch (IOException e) { log.info("Unable to open cursor image."); } scriptStartTime = System.currentTimeMillis(); mouse.setSpeed(MouseSpeed); camera.setPitch(true); log("You are using Voltrex Ape Atoll agility course."); return true; }
private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
false
48
6,751,999
18,761,618
public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); }
private FileInputStream getPackageStream(String archivePath) throws IOException, PackageManagerException { final int lastSlashInName = filename.lastIndexOf("/"); final String newFileName = filename.substring(lastSlashInName); File packageFile = new File((new StringBuilder()).append(archivePath).append(newFileName).toString()); if (null != packageFile) return new FileInputStream(packageFile); if (null != packageURL) { final InputStream urlStream = new ConnectToServer(null).getInputStream(packageURL); packageFile = new File((new StringBuilder()).append(getName()).append(".deb").toString()); final OutputStream fileStream = new FileOutputStream(packageFile); final byte buffer[] = new byte[10240]; for (int read = 0; (read = urlStream.read(buffer)) > 0; ) fileStream.write(buffer, 0, read); urlStream.close(); fileStream.close(); return new FileInputStream(packageFile); } else { final String errorMessage = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("package.getPackageStream.packageURLIsNull", "No entry found for package.getPackageStream.packageURLIsNull"); if (pm != null) { pm.addWarning(errorMessage); logger.error(errorMessage); } else logger.error(errorMessage); throw new FileNotFoundException(); } }
true
49
19,193,813
18,568,751
public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; }
true
50
418,257
21,900,384
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
@Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); String attributeIdentifier = request.getParameter("identifier"); if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) { try { BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } catch (DataRetrievalFailureException e) { addGlobalError(request, "errors.notFound"); } catch (Exception e) { addGlobalError(request, e); } } return mapping.getInputForward(); }
true
51
10,793,825
2,247,987
public String getRec(String attribute, String url) { String arr[] = new String[3]; String[] subarr = new String[6]; String mdPrefix = ""; String mdPrefixValue = ""; String iden = ""; String idenValue = ""; String s = ""; String arguments = attribute.substring(attribute.indexOf("?") + 1); System.out.println("attributes" + arguments); java.util.StringTokenizer st = new java.util.StringTokenizer(arguments, "&"); int i = 0; int j = 0; int count = 0; int argCount = 0; java.util.Vector v1 = new java.util.Vector(1, 1); java.util.Vector v901 = new java.util.Vector(1, 1); java.util.Vector v902 = new java.util.Vector(1, 1); java.util.Vector v903 = new java.util.Vector(1, 1); java.util.Vector v904 = new java.util.Vector(1, 1); java.util.Vector v905 = new java.util.Vector(1, 1); java.util.Vector v906 = new java.util.Vector(1, 1); java.util.Vector v907 = new java.util.Vector(1, 1); java.util.Vector v908 = new java.util.Vector(1, 1); java.util.Vector v3 = new java.util.Vector(1, 1); java.util.Vector vData = new java.util.Vector(1, 1); java.util.Vector vSet = new java.util.Vector(1, 1); java.util.Vector v856 = new java.util.Vector(1, 1); Resdate dt = new Resdate(); try { while (st.hasMoreElements()) { arr[i] = st.nextElement().toString(); java.util.StringTokenizer subSt = new java.util.StringTokenizer(arr[i], "="); while (subSt.hasMoreElements()) { subarr[j] = subSt.nextElement().toString(); System.out.println(" arga are... " + subarr[j]); j++; } i++; count++; } } catch (Exception e) { e.printStackTrace(); } Namespace oains = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/"); Element root = new Element("OAI-PMH", oains); Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); Attribute schemaLocation = new Attribute("schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd", xsi); root.setAttribute(schemaLocation); root.addNamespaceDeclaration(xsi); Document doc = new Document(root); Element responseDate = new Element("responseDate", oains); root.addContent(responseDate); responseDate.setText(dt.getDate()); Element request = new Element("request", oains); request.setAttribute("verb", "GetRecord"); int idenCount = 0, mdfCount = 0; for (int k = 2; k < j; k += 2) { System.out.println(" arg key " + subarr[k]); if (subarr[k].equals("metadataPrefix")) { mdPrefix = "metadataPrefix"; mdfCount++; mdPrefixValue = subarr[k + 1]; request.setAttribute(mdPrefix, mdPrefixValue); System.out.println(subarr[k] + "="); System.out.println(mdPrefixValue); argCount++; } else if (subarr[k].equals("identifier")) { iden = "identifier"; idenCount++; idenValue = subarr[k + 1]; request.setAttribute(iden, idenValue); System.out.println(subarr[k] + "="); System.out.println(idenValue); argCount++; } } request.setText(url); root.addContent(request); System.out.println("count" + argCount); if (mdfCount == 1 && idenCount == 1 && (mdPrefixValue.equals("marc21") || mdPrefixValue.equals("oai_dc") || mdPrefixValue.equals("mods"))) { try { v1 = ((ejb.bprocess.OAIPMH.ListGetRecordsHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("ListGetRecords")).create().getRecord(idenValue, mdPrefixValue); } catch (Exception ex) { ex.printStackTrace(); } if (v1.size() == 0) { System.out.println("vector size is empty"); Errors e1 = new Errors(); Element errorXML = e1.describeError(3, attribute, url, "GetRecord"); root.addContent(errorXML); } else { Element GetRecord = new Element("GetRecord", oains); root.addContent(GetRecord); Element Record = new Element("record", oains); Element metadata = new Element("metadata", oains); Element head = new Element("header", oains); System.out.println("size i s " + v1.size()); for (int v = 0; v < v1.size(); v = v + 13) { vSet = (java.util.Vector) v1.elementAt(v + 1); Element ident = new Element("identifier", oains); ident.setText(idenValue); head.addContent(ident); Element dates = new Element("datestamp", oains); dates.setText(v1.elementAt(v).toString().substring(0, 10)); head.addContent(dates); for (int t = 0; t < vSet.size(); t++) { Element setSpec = new Element("setSpec", oains); System.out.println("set elem" + vSet.elementAt(t).toString()); setSpec.setText(vSet.elementAt(t).toString()); head.addContent(setSpec); } Element marcroot = new Element("record", "marc", "http://www.loc.gov/MARC21/slim"); Namespace xsimarc = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); marcroot.addNamespaceDeclaration(xsimarc); Attribute schemaLocationmarc = new Attribute("schemaLocation", "http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd", xsimarc); marcroot.setAttribute(schemaLocationmarc); marcroot.setAttribute("type", "Bibliographic"); v3 = (java.util.Vector) v1.elementAt(v + 10); java.util.Vector vL = (java.util.Vector) v3.elementAt(0); org.jdom.Element lead = new org.jdom.Element("leader", "marc", "http://www.loc.gov/MARC21/slim"); lead.setText(vL.elementAt(0).toString()); marcroot.addContent(lead); java.util.Vector vC = (java.util.Vector) v3.elementAt(1); for (int u = 0; u < vC.size(); u = u + 2) { org.jdom.Element ct = new org.jdom.Element("controlfield", "marc", "http://www.loc.gov/MARC21/slim"); ct.setAttribute("tag", vC.elementAt(u).toString()); ct.setText(vC.elementAt(u + 1).toString()); marcroot.addContent(ct); } v901 = (java.util.Vector) v1.elementAt(v + 2); for (int k = 0; k < v901.size(); k++) { org.jdom.Element datafield = new org.jdom.Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield.setAttribute("tag", "901"); datafield.setAttribute("ind1", "0"); datafield.setAttribute("ind2", "0"); java.util.Vector vecSub = new java.util.Vector(1, 1); vecSub = (java.util.Vector) v901.elementAt(k); System.out.println("in getrec sub "); System.out.println("sub 901 size" + vecSub.size()); for (int k1 = 0; k1 < vecSub.size(); k1 = k1 + 2) { org.jdom.Element subfield = new org.jdom.Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub.elementAt(k1).toString()); subfield.setText(vecSub.elementAt(k1 + 1).toString()); datafield.addContent(subfield); } marcroot.addContent(datafield); } v902 = (java.util.Vector) v1.elementAt(v + 3); for (int l = 0; l < v902.size(); l++) { Element datafield1 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield1.setAttribute("tag", "902"); datafield1.setAttribute("ind1", "0"); datafield1.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v902.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield1.addContent(subfield); } marcroot.addContent(datafield1); } v903 = (java.util.Vector) v1.elementAt(v + 4); Element datafield1 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield1.setAttribute("tag", "903"); datafield1.setAttribute("ind1", "0"); datafield1.setAttribute("ind2", "0"); for (int l = 0; l < v903.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v903.elementAt(l).toString()); datafield1.addContent(subfield); } marcroot.addContent(datafield1); v904 = (java.util.Vector) v1.elementAt(v + 5); Element datafield21 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield21.setAttribute("tag", "904"); datafield21.setAttribute("ind1", "0"); datafield21.setAttribute("ind2", "0"); for (int l = 0; l < v904.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v904.elementAt(l).toString()); datafield21.addContent(subfield); } marcroot.addContent(datafield21); v905 = (java.util.Vector) v1.elementAt(v + 6); Element datafield31 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield31.setAttribute("tag", "905"); datafield31.setAttribute("ind1", "0"); datafield31.setAttribute("ind2", "0"); for (int l = 0; l < v905.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v905.elementAt(l).toString()); datafield31.addContent(subfield); } marcroot.addContent(datafield31); v906 = (java.util.Vector) v1.elementAt(v + 7); Element datafield4 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield4.setAttribute("tag", "906"); datafield4.setAttribute("ind1", "0"); datafield4.setAttribute("ind2", "0"); for (int l = 0; l < v906.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v906.elementAt(l).toString()); datafield4.addContent(subfield); } marcroot.addContent(datafield4); v907 = (java.util.Vector) v1.elementAt(v + 8); for (int l = 0; l < v907.size(); l++) { Element datafield5 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield5.setAttribute("tag", "907"); datafield5.setAttribute("ind1", "0"); datafield5.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v907.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield5.addContent(subfield); } marcroot.addContent(datafield5); } v908 = (java.util.Vector) v1.elementAt(v + 9); for (int l = 0; l < v908.size(); l++) { Element datafield6 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield6.setAttribute("tag", "908"); datafield6.setAttribute("ind1", "0"); datafield6.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v908.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield6.addContent(subfield); } marcroot.addContent(datafield6); } vData = (java.util.Vector) v1.elementAt(v + 11); for (int m = 0; m < vData.size(); m = m + 2) { Element datafield2 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield2.setAttribute("tag", vData.elementAt(m).toString()); datafield2.setAttribute("ind1", "0"); datafield2.setAttribute("ind2", "0"); java.util.Vector vSub = new java.util.Vector(1, 1); vSub = (java.util.Vector) vData.elementAt(m + 1); for (int n = 0; n < vSub.size(); n = n + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vSub.elementAt(n).toString()); subfield.setText(vSub.elementAt(n + 1).toString()); datafield2.addContent(subfield); } marcroot.addContent(datafield2); } v856 = (java.util.Vector) v1.elementAt(v + 12); for (int l = 0; l < v856.size(); l = l + 2) { Element datafield3 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield3.setAttribute("tag", "856"); datafield3.setAttribute("ind1", "0"); datafield3.setAttribute("ind2", "0"); Element subfield1 = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield1.setAttribute("code", v856.elementAt(l).toString()); subfield1.setText(v856.elementAt(l + 1).toString()); datafield3.addContent(subfield1); marcroot.addContent(datafield3); } if (mdPrefixValue.equals("oai_dc")) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "StyleSheets" + java.io.File.separator + "MARC21slim2OAIDC.xsl")); Document docmarc = new Document(marcroot); JDOMSource in = new JDOMSource(docmarc); JDOMResult out = new JDOMResult(); transformer.transform(in, out); Document doc2 = out.getDocument(); org.jdom.output.XMLOutputter out1 = new org.jdom.output.XMLOutputter(); out1.setTextTrim(true); out1.setIndent(" "); out1.setNewlines(true); String s1 = out1.outputString(doc2); System.out.println("dublin core is" + s1); Element dcroot1 = doc2.getRootElement(); Namespace xsi1 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); Namespace oainsdc = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/oai_dc/"); Element dcroot = new Element("dc", "oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/"); Namespace dcns = Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/"); dcroot.addNamespaceDeclaration(dcns); dcroot.addNamespaceDeclaration(xsi1); Attribute schemaLocationdc = new Attribute("schemaLocation", "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", xsi1); dcroot.setAttribute(schemaLocationdc); java.util.List dcList = doc2.getRootElement().getChildren(); for (int g = 0; g < dcList.size(); g++) { Element dcElem1 = (org.jdom.Element) dcList.get(g); Element dcElem = new Element(dcElem1.getName(), "dc", "http://purl.org/dc/elements/1.1/"); dcElem.setText(dcElem1.getText()); dcroot.addContent(dcElem); } metadata.addContent(dcroot); } catch (TransformerException e) { e.printStackTrace(); } } else if (mdPrefixValue.equals("mods")) { try { java.util.Properties systemSettings = System.getProperties(); java.util.prefs.Preferences prefs = java.util.prefs.Preferences.systemRoot(); if (prefs.getBoolean("useproxy", false)) { systemSettings.put("proxySet", "true"); systemSettings.put("proxyHost", prefs.get("proxyservername", "")); systemSettings.put("proxyPort", prefs.get("proxyport", "")); systemSettings.put("http.proxyHost", prefs.get("proxyservername", "")); systemSettings.put("http.proxyPort", prefs.get("proxyport", "")); } String urltext = ""; Transformer transformer = null; urltext = "http://www.loc.gov/standards/mods/v3/MARC21slim2MODS3.xsl"; java.net.URL url1 = new java.net.URL(urltext); java.net.URLConnection urlconn = url1.openConnection(); urlconn.setDoInput(true); transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(urlconn.getInputStream())); Document docmarc = new Document(marcroot); JDOMSource in = new JDOMSource(docmarc); JDOMResult out = new JDOMResult(); transformer.transform(in, out); Document doc2 = out.getDocument(); org.jdom.output.XMLOutputter out1 = new org.jdom.output.XMLOutputter(); out1.setTextTrim(true); out1.setIndent(" "); out1.setNewlines(true); String s1 = out1.outputString(doc2); Namespace xsi1 = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); Namespace oainsdc = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/oai_dc/"); Element mroot = new Element("mods", "http://www.loc.gov/mods/v3"); Namespace dcns = Namespace.getNamespace("http://www.loc.gov/mods/v3"); mroot.addNamespaceDeclaration(xsi1); Attribute schemaLocationdc = new Attribute("schemaLocation", "http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd", xsi1); mroot.setAttribute(schemaLocationdc); java.util.List dcList = doc2.getRootElement().getChildren(); for (int g = 0; g < dcList.size(); g++) { Element mElem1 = (org.jdom.Element) dcList.get(g); Element mElem = new Element(mElem1.getName(), "http://www.loc.gov/mods/v3"); if (mElem1.hasChildren()) { java.util.List mList1 = mElem1.getChildren(); for (int f = 0; f < mList1.size(); f++) { Element mElem2 = (org.jdom.Element) mList1.get(f); Element mElem3 = new Element(mElem2.getName(), "http://www.loc.gov/mods/v3"); if (mElem2.hasChildren()) { java.util.List mList2 = mElem2.getChildren(); for (int h = 0; h < mList2.size(); h++) { Element mElem4 = (org.jdom.Element) mList1.get(h); Element mElem5 = new Element(mElem4.getName(), "http://www.loc.gov/mods/v3"); mElem5.setText(mElem4.getText()); mElem3.addContent(mElem5); } } if (mElem2.hasChildren() == false) { mElem3.setText(mElem2.getText()); } mElem.addContent(mElem3); } } if (mElem1.hasChildren() == false) { mElem.setText(mElem1.getText()); } mroot.addContent(mElem); } metadata.addContent(mroot); } catch (Exception e) { e.printStackTrace(); } } if (mdPrefixValue.equals("marc21")) { metadata.addContent(marcroot); } else if (mdPrefixValue.equals("oai_dc")) { } } Record.addContent(head); Record.addContent(metadata); GetRecord.addContent(Record); } } else if (argCount <= 2) { if (idenCount < 1 && mdfCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing arguments: identifier,metadataprefix", url, "GetRecord"); root.addContent(errorXML); } else if (idenCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing argument: identifier", url, "GetRecord"); root.addContent(errorXML); } else if (mdfCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing argument: metadataprefix", url, "GetRecord"); root.addContent(errorXML); } else if (argCount > 2) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "more number of arguments", url, "GetRecord"); root.addContent(errorXML); } else { System.out.println("no format"); Errors e1 = new Errors(); Element errorXML = e1.describeError(6, "", url, "GetRecord"); root.addContent(errorXML); } } XMLOutputter out = new XMLOutputter(); out.setIndent(" "); out.setNewlines(true); s = out.outputString(doc); return s; }
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 4., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
false
52
3,262,458
8,452,564
@Override public void run() { while (run) { try { URL url = new URL("http://" + server.getIp() + "/" + tomcat.getName() + "/ui/pva/version.jsp?RT=" + System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName("UTF-8"))); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("currentversion")) { String s = inputLine.substring(inputLine.indexOf("=") + 1, inputLine.length()); tomcat.setDetailInfo(s.trim()); } } in.close(); tomcat.setIsAlive(true); } catch (Exception e) { tomcat.setIsAlive(false); } try { Thread.sleep(60000); } catch (InterruptedException e) { } } }
public void run() { try { HttpPost httpPostRequest = new HttpPost(Feesh.device_URL); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("c", "feed")); nameValuePairs.add(new BasicNameValuePair("amount", String.valueOf(foodAmount))); nameValuePairs.add(new BasicNameValuePair("type", String.valueOf(foodType))); httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse httpResponse = (HttpResponse) new DefaultHttpClient().execute(httpPostRequest); HttpEntity entity = httpResponse.getEntity(); String resultString = ""; if (entity != null) { InputStream instream = entity.getContent(); resultString = convertStreamToString(instream); instream.close(); } Message msg_toast = new Message(); msg_toast.obj = resultString; toast_handler.sendMessage(msg_toast); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
false
53
17,267,601
20,336,463
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()); }
private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); }
true
54
21,704,695
9,385,030
public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); XSLTBuddy buddy = new XSLTBuddy(); buddy.parseArgs(args); XSLTransformer transformer = new XSLTransformer(); if (buddy.templateDir != null) { transformer.setTemplateDir(buddy.templateDir); } FileReader xslReader = new FileReader(buddy.xsl); Templates xslTemplate = transformer.getXSLTemplate(buddy.xsl, xslReader); for (Enumeration e = buddy.params.keys(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); transformer.addParam(key, buddy.params.get(key)); } Reader reader = null; if (buddy.src == null) { reader = new StringReader(XSLTBuddy.BLANK_XML); } else { reader = new FileReader(buddy.src); } if (buddy.out == null) { String result = transformer.doTransform(reader, xslTemplate, buddy.xsl); buddy.getLogger().info("\n\nXSLT Result:\n\n" + result + "\n"); } else { File file = new File(buddy.out); File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } FileWriter writer = new FileWriter(buddy.out); transformer.doTransform(reader, xslTemplate, buddy.xsl, writer); writer.flush(); writer.close(); } buddy.getLogger().info("Transform done successfully in " + (System.currentTimeMillis() - start) + " milliseconds"); }
false
55
18,513,921
430,971
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
true
56
15,982,225
23,285,410
private static String getDigest(String srcStr, String alg) { Assert.notNull(srcStr); Assert.notNull(alg); try { MessageDigest alga = MessageDigest.getInstance(alg); alga.update(srcStr.getBytes()); byte[] digesta = alga.digest(); return byte2hex(digesta); } catch (Exception e) { throw new RuntimeException(e); } }
public void displayItems() throws IOException { URL url = new URL(SNIPPETS_FEED + "?bq=" + URLEncoder.encode(QUERY, "UTF-8") + "&key=" + DEVELOPER_KEY); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = httpConnection.getInputStream(); int ch; while ((ch = inputStream.read()) > 0) { System.out.print((char) ch); } }
false
57
7,398,604
820,905
@Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
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!"); }
true
58
19,584,493
4,076,629
@Override public String toString() { if (byteArrayOutputStream == null) return "<Unparsed binary data: Content-Type=" + getHeader("Content-Type") + " >"; String charsetName = getCharsetName(); if (charsetName == null) charsetName = "ISO-8859-1"; try { if (unzip) { GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())); ByteArrayOutputStream unzippedResult = new ByteArrayOutputStream(); IOUtils.copy(gzipInputStream, unzippedResult); return unzippedResult.toString(charsetName); } else { return byteArrayOutputStream.toString(charsetName); } } catch (UnsupportedEncodingException e) { throw new OutputException(e); } catch (IOException e) { throw new OutputException(e); } }
public void uploadFile(String filename) throws RQLException { checkFtpClient(); OutputStream out = null; try { out = ftpClient.storeFileStream(filename); IOUtils.copy(new FileReader(filename), out); out.close(); ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Upload of local file with name " + filename + " via FTP to server " + server + " failed.", ex); } }
true
59
1,888,878
7,665,877
protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } }
public SCFFile(URL url) throws IOException { URLConnection connection = url.openConnection(); byte[] content = new byte[connection.getContentLength()]; DataInputStream dis = new DataInputStream(connection.getInputStream()); dis.readFully(content); dis.close(); dis = new DataInputStream(new ByteArrayInputStream(content)); header = new SCFHeader(dis); if (!header.magicNumber.equals(".scf")) throw new RuntimeException(url + " is not an SCF file"); A = new int[header.samples]; C = new int[header.samples]; G = new int[header.samples]; T = new int[header.samples]; max = Integer.MIN_VALUE; dis.reset(); dis.skipBytes(header.samplesOffset); if (header.sampleSize == 1) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedByte(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedByte(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedByte(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedByte(); if (T[i] > max) max = T[i]; } } } else if (header.sampleSize == 2) { if (header.version < 3.00) { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } else { for (int i = 0; i < header.samples; ++i) { A[i] = dis.readUnsignedShort(); if (A[i] > max) max = A[i]; } for (int i = 0; i < header.samples; ++i) { C[i] = dis.readUnsignedShort(); if (C[i] > max) max = C[i]; } for (int i = 0; i < header.samples; ++i) { G[i] = dis.readUnsignedShort(); if (G[i] > max) max = G[i]; } for (int i = 0; i < header.samples; ++i) { T[i] = dis.readUnsignedShort(); if (T[i] > max) max = T[i]; } } } centers = new int[header.bases]; byte[] buf = new byte[header.bases]; dis.reset(); dis.skipBytes(header.basesOffset); if (header.version < 3.00) { for (int i = 0; i < header.bases; ++i) { centers[i] = dis.readInt(); dis.skipBytes(4); buf[i] = dis.readByte(); dis.skipBytes(3); } } else { for (int i = 0; i < header.bases; ++i) centers[i] = dis.readInt(); dis.skipBytes(4 * header.bases); dis.readFully(buf); } sequence = new String(buf); dis.close(); }
false
60
11,044,947
16,851,953
public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
@Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
true
61
19,693,561
22,137,813
public Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } }
public static ObjectID[] sortDecending(ObjectID[] oids) { for (int i = 1; i < oids.length; i++) { ObjectID iId = oids[i]; for (int j = 0; j < oids.length - i; j++) { if (oids[j].getTypePrefix() > oids[j + 1].getTypePrefix()) { ObjectID temp = oids[j]; oids[j] = oids[j + 1]; oids[j + 1] = temp; } } } return oids; }
false
62
601,908
12,678,589
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!"); }
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; }
true
63
18,293,811
7,303,337
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } }
true
64
13,863,615
15,593,678
protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; }
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
true
65
16,298,029
3,931,480
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); }
public final String encrypt(final String plaintext, final String salt) { if (plaintext == null) { throw new NullPointerException(); } if (salt == null) { throw new NullPointerException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update((plaintext + salt).getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
true
66
20,691,789
2,467,221
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } }
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(); }
true
67
2,232,619
7,577,030
public void testStorageStringWriter() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { Writer w = r.getWriter(); w.write("This is an example"); w.write(" and another one."); w.flush(); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } try { r.getOutputStream(); fail("Is not allowed as you already called getWriter()."); } catch (IOException e) { } { Writer output = r.getWriter(); output.write(" and another line"); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and some more."); assertEquals("This is an example and another one. and another line and write some more and some more.", r.getText()); } r.setEndState(ResponseStateOk.getInstance()); assertEquals(ResponseStateOk.getInstance(), r.getEndState()); try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
private void zipFiles(File file, File[] fa) throws Exception { File f = new File(file, ALL_FILES_NAME); if (f.exists()) { f.delete(); f = new File(file, ALL_FILES_NAME); } ZipOutputStream zoutstrm = new ZipOutputStream(new FileOutputStream(f)); for (int i = 0; i < fa.length; i++) { ZipEntry zipEntry = new ZipEntry(fa[i].getName()); zoutstrm.putNextEntry(zipEntry); FileInputStream fr = new FileInputStream(fa[i]); byte[] buffer = new byte[1024]; int readCount = 0; while ((readCount = fr.read(buffer)) > 0) { zoutstrm.write(buffer, 0, readCount); } fr.close(); zoutstrm.closeEntry(); } zoutstrm.close(); log("created zip file: " + file.getName() + "/" + ALL_FILES_NAME); }
true
68
7,066,835
1,966,262
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = new ArrayList<Datastream>(); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); tDatastreams.add(tDatastream); tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName)); return tDatastreams; }
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; }
true
69
17,217,414
17,984,312
public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException { File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile(); if (!target.exists()) { target.createNewFile(); } if ((new File(this.source.toURI())).isDirectory()) { File sourceEntry = new File(this.source.getPath() + entry.getName()); FileInputStream fis = new FileInputStream(sourceEntry); byte[] classBytes = new byte[fis.available()]; fis.read(classBytes); (new FileOutputStream(target)).write(classBytes); } else { readwriteStreams(jis, (new FileOutputStream(target))); } }
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(); } }
true
70
7,396,680
5,856,886
public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } }
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
true
71
6,908,554
20,669,450
static void reopen(MJIEnv env, int objref) throws IOException { int fd = env.getIntField(objref, "fd"); long off = env.getLongField(objref, "off"); if (content.get(fd) == null) { int mode = env.getIntField(objref, "mode"); int fnRef = env.getReferenceField(objref, "fileName"); String fname = env.getStringObject(fnRef); if (mode == FD_READ) { FileInputStream fis = new FileInputStream(fname); FileChannel fc = fis.getChannel(); fc.position(off); content.set(fd, fis); } else if (mode == FD_WRITE) { FileOutputStream fos = new FileOutputStream(fname); FileChannel fc = fos.getChannel(); fc.position(off); content.set(fd, fos); } else { env.throwException("java.io.IOException", "illegal mode: " + mode); } } }
private void auth() throws IOException { authorized = false; seqNumber = 0; DatagramSocket ds = new DatagramSocket(); ds.setSoTimeout(UDPHID_DEFAULT_TIMEOUT); ds.connect(addr, port); DatagramPacket p = new DatagramPacket(buffer.array(), buffer.capacity()); for (int i = 0; i < UDPHID_DEFAULT_ATTEMPTS; i++) { buffer.clear(); buffer.put((byte) REQ_CHALLENGE); buffer.put(htons((short) UDPHID_PROTO)); buffer.put(name.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_CHALLENGE: break; case ANS_FAILURE: throw new IOException("REQ_FAILURE"); default: throw new IOException("invalid packet"); } byte challenge_id = buffer.get(); int challenge_len = (int) buffer.get(); byte[] challenge = new byte[challenge_len]; buffer.get(challenge, 0, p.getLength() - buffer.position()); byte[] response; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(challenge_id); md.update(password.getBytes(), 0, password.length()); md.update(challenge, 0, challenge.length); response = md.digest(); } catch (NoSuchAlgorithmException e) { throw new IOException("NoSuchAlgorithmException: " + e.toString()); } buffer.clear(); buffer.put((byte) REQ_RESPONSE); buffer.put(challenge_id); buffer.put((byte) response.length); buffer.put(response); buffer.put(login.getBytes()); ds.send(new DatagramPacket(buffer.array(), buffer.position())); buffer.clear(); try { ds.receive(p); } catch (SocketTimeoutException e) { continue; } switch(buffer.get()) { case ANS_SUCCESS: int sidLength = buffer.get(); sid = new byte[sidLength]; buffer.get(sid, 0, sidLength); authorized = true; return; case ANS_FAILURE: throw new IOException("access deny"); default: throw new IOException("invalid packet"); } } throw new IOException("operation time out"); }
false
72
1,966,263
18,600,188
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; }
private void copyFile(String fileName, String messageID, boolean isError) { try { File inputFile = new File(fileName); File outputFile = null; if (isError) { outputFile = new File(provider.getErrorDataLocation(folderName) + messageID + ".xml"); } else { outputFile = new File(provider.getDataProcessedLocation(folderName) + messageID + ".xml"); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
true
73
8,330,064
12,524,253
@Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
true
74
4,376,758
22,249,465
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
public static String getWebPage(URL urlObj) { try { String content = ""; InputStreamReader is = new InputStreamReader(urlObj.openStream()); BufferedReader reader = new BufferedReader(is); String line; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (IOException e) { throw new Error("The page " + quote(urlObj.toString()) + "could not be retrieved." + "\nThis is could be caused by a number of things:" + "\n" + "\n - the computer hosting the web page you want is down, or has returned an error" + "\n - your computer does not have Internet access" + "\n - the heat death of the universe has occurred, taking down all web servers with it"); } }
false
75
105,319
16,341,721
private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } }
true
76
7,839,811
4,056,440
public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); }
public final String hashPassword(final String password) { try { if (salt == null) { salt = new byte[16]; SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(System.currentTimeMillis()); sr.nextBytes(salt); } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] hash = md.digest(); for (int i = 0; i < (1999); i++) { md.reset(); hash = md.digest(hash); } return byteToString(hash, 60); } catch (Exception exception) { log.error(exception); return null; } }
true
77
4,207,693
5,713,525
private synchronized boolean saveU(URL url, String typeFlag, byte[] arrByte) { BufferedReader buffReader = null; BufferedOutputStream buffOS = null; URLConnection urlconnection = null; char flagChar = '0'; boolean flag = true; try { urlconnection = url.openConnection(); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); urlconnection.setUseCaches(false); urlconnection.setRequestProperty("Content-type", "application/octet-stream"); buffOS = new BufferedOutputStream(urlconnection.getOutputStream()); buffOS.write((byte[]) typeFlag.getBytes()); buffOS.write(arrByte); buffOS.flush(); if (Config.DEBUG) System.out.println("Applet output file successfully! "); buffReader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream())); StringBuffer stringBuff = new StringBuffer(); String serReturnMess = buffReader.readLine(); if (Config.DEBUG) System.out.println("Applet check status successfully! " + serReturnMess); flagChar = '2'; if (serReturnMess != null) { stringBuff.append(serReturnMess); serReturnMess = serReturnMess.substring(serReturnMess.indexOf(32)).trim() + '2'; flagChar = serReturnMess.charAt(0); } while ((serReturnMess = buffReader.readLine()) != null) { if (serReturnMess.length() <= 0) break; } } catch (Throwable e) { e.printStackTrace(); return false; } finally { try { if (buffOS != null) buffOS.close(); if (buffReader != null) buffReader.close(); } catch (Throwable e) { e.printStackTrace(); } if (flagChar == '2' || flagChar == '3') flag = true; else flag = false; } return flag; }
private byte[] getFileFromFtp(String remote) throws Exception { ftp = new FTPClient(); int reply; ftp.connect(ftpServer); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("FTP server refused connection."); } if (!ftp.login(ftpUsername, ftpPassword)) { ftp.logout(); throw new Exception("Cann't login to ftp."); } ftp.enterLocalPassiveMode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ftp.retrieveFile(remote, baos); ftp.logout(); if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } return baos.toByteArray(); }
false
78
12,678,588
952,242
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 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(); } }
true
79
21,395,181
22,135,738
@Test public void test20_badSmtp() throws Exception { Db db = DbConnection.defaultCieDbRW(); try { db.begin(); oldSmtp = Config.getProperty(db, "com.entelience.mail.MailHelper.hostName", "localhost"); oldSupport = Config.getProperty(db, "com.entelience.esis.feature.SupportNotifier", false); Config.setProperty(db, "com.entelience.mail.MailHelper.hostName", "127.0.10.1", 1); Config.setProperty(db, "com.entelience.esis.feature.SupportNotifier", "true", 1); PreparedStatement pst = db.prepareStatement("DELETE FROM t_client_errors"); db.executeUpdate(pst); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.safeClose(); } }
protected void sort(double[] a) throws Exception { for (int i = a.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) { if (a[j] > a[j + 1]) { double d = a[j]; a[j] = a[j + 1]; a[j + 1] = d; swapped = true; } } if (!swapped) return; } }
false
80
19,338,729
19,898,737
public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); }
private void updateSystem() throws IOException { String stringUrl="http://code.google.com/p/senai-pe-cronos/downloads/list"; try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String linha = br.readLine(); while (linha != null) { linha = br.readLine(); if(linha.contains("/files/updateCronos-0-")){ String[] s=linha.split("-"); String[] v=s[4].split(".exe"); versao=v[0]; println("----"+versao); break; } } stringUrl="http://senai-pe-cronos.googlecode.com/files/updateCronos-0-"+versao+".exe"; UpdateCronos update=new UpdateCronos(); try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } System.out.println("versão:"+versao); if(Integer.parseInt(versao)>version){ File f = update.gravaArquivoDeURL(url,System.getProperty("user.dir"),String.valueOf(version),versao); if(update.isS()) { Runtime.getRuntime().exec(location+"\\update.exe"); System.exit(0); } } }
false
81
16,845,107
7,321,949
public boolean copyFile(File destinationFolder, File fromFile) { boolean result = false; String toFileName = destinationFolder.getAbsolutePath() + "/" + fromFile.getName(); File toFile = new File(toFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) { try { from.close(); } catch (IOException e2) { e2.printStackTrace(); } if (to != null) { try { to.close(); result = true; } catch (IOException e3) { e3.printStackTrace(); } } } } return result; }
private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; }
true
82
8,661,929
2,446,253
public int addLocationInfo(int id, double lattitude, double longitude) { int ret = 0; Connection conn = null; PreparedStatement psmt = null; try { String sql = "insert into kddb.location_info (user_id, latitude, longitude) values(?, ?, ?)"; conn = getConnection(); psmt = conn.prepareStatement(sql); psmt.setInt(1, id); psmt.setDouble(2, lattitude); psmt.setDouble(3, longitude); ret = psmt.executeUpdate(); if (ret == 1) { conn.commit(); } else { conn.rollback(); } } catch (SQLException ex) { log.error("[addLocationInfo]", ex); } finally { endProsess(conn, psmt, null, null); } return ret; }
private int renumberOrderBy(long tableID) throws SnapInException { int count = 0; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getDataSource().getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); StringBuffer query = new StringBuffer(); query.append("SELECT ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" FROM ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_TABLEID).append(" = ").append(tableID).append(" ORDER BY ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY); Vector rowIDVector = new Vector(); rs = stmt.executeQuery(query.toString()); while (rs.next()) { count++; rowIDVector.add(rs.getLong(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID) + ""); } StringBuffer updateString = new StringBuffer(); updateString.append("UPDATE ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" SET ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY).append(" = ? WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" = ?"); PreparedStatement pstmt = con.prepareStatement(updateString.toString()); int orderByValue = ORDERBY_BY_DELTA_VALUE; Enumeration en = rowIDVector.elements(); while (en.hasMoreElements()) { pstmt.setInt(1, orderByValue); pstmt.setString(2, en.nextElement().toString()); orderByValue += ORDERBY_BY_DELTA_VALUE; pstmt.executeUpdate(); } con.setAutoCommit(true); if (pstmt != null) { pstmt.close(); } } catch (java.sql.SQLException e) { if (con == null) { logger.error("java.sql.SQLException", e); } else { try { logger.error("Transaction is being rolled back."); con.rollback(); con.setAutoCommit(true); } catch (java.sql.SQLException e2) { logger.error("java.sql.SQLException", e2); } } } catch (Exception e) { logger.error("Error occured during RenumberOrderBy", e); } finally { getDataSourceHelper().releaseResources(con, stmt, rs); } return count; }
true
83
21,293,476
716,032
public void addGames(List<Game> games) throws StadiumException, SQLException { Connection conn = ConnectionManager.getManager().getConnection(); conn.setAutoCommit(false); PreparedStatement stm = null; ResultSet rs = null; try { for (Game game : games) { stm = conn.prepareStatement(Statements.SELECT_STADIUM); stm.setString(1, game.getStadiumName()); stm.setString(2, game.getStadiumCity()); rs = stm.executeQuery(); int stadiumId = -1; while (rs.next()) { stadiumId = rs.getInt("stadiumID"); } if (stadiumId == -1) throw new StadiumException("No such stadium"); stm = conn.prepareStatement(Statements.INSERT_GAME); stm.setInt(1, stadiumId); stm.setDate(2, game.getGameDate()); stm.setTime(3, game.getGameTime()); stm.setString(4, game.getTeamA()); stm.setString(5, game.getTeamB()); stm.executeUpdate(); int gameId = getMaxId(); List<SectorPrice> sectorPrices = game.getSectorPrices(); for (SectorPrice price : sectorPrices) { stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE); stm.setInt(1, gameId); stm.setInt(2, price.getSectorId()); stm.setInt(3, price.getPrice()); stm.executeUpdate(); } } } catch (SQLException e) { conn.rollback(); throw e; } finally { rs.close(); stm.close(); } conn.commit(); conn.setAutoCommit(true); }
public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } }
false
84
1,244,216
3,078,767
public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (queue == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); getQueue().post(eventObj); return eventDoc.getEvent().getEventId(); }
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
true
85
22,328,848
4,411,141
protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } }
private void addDocToDB(String action, DataSource database) { String typeOfDoc = findTypeOfDoc(action).trim().toLowerCase(); Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); checkDupDoc(typeOfDoc, con); String add = "insert into " + typeOfDoc + " values( ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getCourseId()); prepStatement.setString(2, selectedCourse.getAdmin()); prepStatement.setTimestamp(3, getTimeStamp()); prepStatement.setString(4, getLink()); prepStatement.setString(5, homePage.getUser()); prepStatement.setString(6, getText()); prepStatement.setString(7, getTitle()); prepStatement.executeUpdate(); prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } }
true
86
17,001,260
8,364,547
public static void getGPX(String gpxURL, String fName) { try { URL url = new URL(gpxURL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File storage = mContext.getExternalFilesDir(null); File file = new File(storage, fName); FileOutputStream os = new FileOutputStream(file); InputStream is = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = is.read(buffer)) > 0) { os.write(buffer, 0, bufferLength); } os.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } }
false
87
11,594,590
4,860,089
public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); }
public int[] sort() { int i, tmp; int[] newIndex = new int[nrows]; for (i = 0; i < nrows; i++) { newIndex[i] = i; } boolean change = true; if (this.ascending) { if (data[0][column] instanceof Comparable) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if (((Comparable) data[newIndex[i]][column]).compareTo((Comparable) data[newIndex[i + 1]][column]) > 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } return newIndex; } if (data[0][column] instanceof String || data[0][column] instanceof ClassLabel) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if ((data[newIndex[i]][column].toString()).compareTo(data[newIndex[i + 1]][column].toString()) > 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } } return newIndex; } if (!this.ascending) { if (data[0][column] instanceof Comparable) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if (((Comparable) data[newIndex[i]][column]).compareTo((Comparable) data[newIndex[i + 1]][column]) < 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } return newIndex; } if (data[0][column] instanceof String || data[0][column] instanceof ClassLabel) { while (change) { change = false; for (i = 0; i < nrows - 1; i++) { if ((data[newIndex[i]][column].toString()).compareTo(data[newIndex[i + 1]][column].toString()) < 0) { tmp = newIndex[i]; newIndex[i] = newIndex[i + 1]; newIndex[i + 1] = tmp; change = true; } } } } return newIndex; } else return newIndex; }
false
88
1,637,147
547,576
protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) { String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.'); String methodName = getMethodName(par); String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName; PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey); if (gr != null) { _sharedAddData.cacheInfo.incCombinePredicateCacheHit(); return gr; } else { _sharedAddData.cacheInfo.incCombinePredicateCacheMiss(); } String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred"; ClassFile predicateCF = null; File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class"); if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) { try { predicateCF = new ClassFile(new FileInputStream(clonedFile)); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { _templatePredicateClassFile.write(baos); predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate template class file", ioe); } } clonedFile.getParentFile().mkdirs(); final ArrayList<String> paramNames = new ArrayList<String>(); final HashMap<String, String> paramTypes = new HashMap<String, String>(); performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() { public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) { paramNames.add(param1); paramTypes.put(param1, param2); return null; } }, ""); ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>(); for (String key : par.combinedPredicates.keySet()) { for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) { if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) { memberPARs.add(memberPAR); } else { memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor)); } } } AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool()); int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem }); predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem }); predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null); predicateCF.setThisClass(predicateClassItem); StringBuilder sb = new StringBuilder(); sb.append("(Ljava/lang/Object;"); if (par.passArguments) { sb.append("[Ljava/lang/Object;"); } for (String key : paramNames) { sb.append(paramTypes.get(key)); } sb.append(")Z"); String methodDesc = sb.toString(); MethodInfo templateMI = null; MethodInfo predicateMI = null; for (MethodInfo mi : predicateCF.getMethods()) { if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) { predicateMI = mi; break; } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) { templateMI = mi; } } if ((templateMI == null) && (predicateMI == null)) { throw new ThreadCheckException("Could not find template predicate method in class file"); } if (predicateMI == null) { AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi }); namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi }); descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>(); for (AAttributeInfo a : templateMI.getAttributes()) { try { AAttributeInfo clonedA = (AAttributeInfo) a.clone(); list.add(clonedA); } catch (CloneNotSupportedException e) { throw new InstrumentorException("Could not clone method attributes"); } } predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {})); predicateCF.getMethods().add(predicateMI); CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties(); props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0); InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode()); if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) { il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); } else { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); } boolean res; res = il.advanceIndex(); assert res == true; int accumVarIndex = props.maxLocals - 1; AInstruction loadAccumInstr; AInstruction storeAccumInstr; if (accumVarIndex < 256) { loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex); storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex); } else { byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 }; Types.bytesFromShort((short) accumVarIndex, bytes, 1); loadAccumInstr = new WideInstruction(bytes); bytes[0] = Opcode.ISTORE; storeAccumInstr = new WideInstruction(bytes); } il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int maxStack = 0; int paramIndex = 1; int lvIndex = 1; if (par.passArguments) { lvIndex += 1; } int memberCount = 0; for (PredicateAnnotationRecord memberPAR : memberPARs) { ++memberCount; il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int curStack = 1; if (memberPAR.passArguments) { if (par.passArguments) { il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; curStack += 1; } } for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) { String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex)); if (t.length() == 0) { throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } byte opcode; int nextLVIndex = lvIndex; switch(t.charAt(0)) { case 'I': case 'B': case 'C': case 'S': case 'Z': opcode = Opcode.ILOAD; nextLVIndex += 1; curStack += 1; break; case 'F': opcode = Opcode.FLOAD; nextLVIndex += 1; curStack += 1; break; case '[': case 'L': opcode = Opcode.ALOAD; nextLVIndex += 1; curStack += 1; break; case 'J': opcode = Opcode.LLOAD; nextLVIndex += 2; curStack += 2; break; case 'D': opcode = Opcode.DLOAD; nextLVIndex += 2; curStack += 2; break; default: throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex); il.insertInstr(load, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; ++paramIndex; lvIndex = nextLVIndex; } if (curStack > maxStack) { maxStack = curStack; } ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0); int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString()); predicateCallInstr.setReference(predicateCallIndex); il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if (par.combineMode == Combine.Mode.OR) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) { il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.IMPLIES) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else { assert false; } res = il.advanceIndex(); assert res == true; il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1); il.insertInstr(br2, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int jumpIndex = il.getIndex(); il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; res = il.rewindIndex(3); assert res == true; BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex); il.insertInstr(br1, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(4); assert res == true; } else { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.deleteInstr(predicateMI.getCodeAttributeInfo()); predicateMI.getCodeAttributeInfo().setCode(il.getCode()); props.maxStack = Math.max(maxStack, 2); predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals); try { FileOutputStream fos = new FileOutputStream(clonedFile); predicateCF.write(fos); fos.close(); } catch (IOException e) { throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile); } } gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>()); _generatedPredicateRecords.put(hashKey, gr); return gr; }
public static void main(String argv[]) { System.out.println("Starting URL tests"); System.out.println("Test 1: Simple URL test"); try { URL url = new URL("http", "www.fsf.org", 80, "/"); if (!url.getProtocol().equals("http") || !url.getHost().equals("www.fsf.org") || url.getPort() != 80 || !url.getFile().equals("/")) System.out.println("FAILED: Simple URL test"); System.out.println("URL is: " + url.toString()); URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) System.out.println("Got the expected connection type"); HttpURLConnection hc = (HttpURLConnection) uc; hc.connect(); System.out.flush(); System.out.println("Dumping response headers"); for (int i = 0; ; i++) { String key = hc.getHeaderFieldKey(i); if (key == null) break; System.out.println(key + ": " + hc.getHeaderField(i)); } System.out.flush(); System.out.println("Dumping contents"); BufferedReader br = new BufferedReader(new InputStreamReader(hc.getInputStream())); for (String str = br.readLine(); str != null; str = br.readLine()) { System.out.println(str); } System.out.flush(); hc.disconnect(); System.out.println("Content Type: " + hc.getContentType()); System.out.println("Content Encoding: " + hc.getContentEncoding()); System.out.println("Content Length: " + hc.getContentLength()); System.out.println("Date: " + hc.getDate()); System.out.println("Expiration: " + hc.getExpiration()); System.out.println("Last Modified: " + hc.getLastModified()); System.out.println("PASSED: Simple URL test"); } catch (IOException e) { System.out.println("FAILED: Simple URL test: " + e); } System.out.println("Test 2: URL parsing test"); try { URL url = new URL("http://www.urbanophile.com/arenn/trans/trans.html#mis"); if (!url.toString().equals("http://www.urbanophile.com/arenn/trans/trans.html#mis")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.foo.com:8080/#"); if (!url.toString().equals("http://www.foo.com:8080/#")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.bar.com/test:file/"); if (!url.toString().equals("http://www.bar.com/test:file/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("http://www.gnu.org"); if (!url.toString().equals("http://www.gnu.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); url = new URL("HTTP://www.fsf.org/"); if (!url.toString().equals("http://www.fsf.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else { System.out.println("Parsed ok: " + url.toString()); System.out.println("PASSED: URL parse test"); } } } } } } catch (IOException e) { System.out.println("FAILED: URL parsing test: " + e); } System.out.println("Test 3: getContent test"); try { URL url = new URL("http://localhost/~arenn/services.txt"); Object obj = url.getContent(); System.out.println("Object type is: " + obj.getClass().getName()); if (obj instanceof InputStream) { System.out.println("Got InputStream, so dumping contents"); BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) obj)); for (String str = br.readLine(); str != null; str = br.readLine()) System.out.println(str); br.close(); } else { System.out.println("FAILED: Object is not an InputStream"); } System.out.println("PASSED: getContent test"); } catch (IOException e) { System.out.println("FAILED: getContent test: " + e); } System.out.println("URL test complete"); }
false
89
189,777
21,224,683
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 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); } }
false
90
5,935,063
19,462,026
public String generateKey(Message msg) { String text = msg.getDefaultMessage(); String meaning = msg.getMeaning(); if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
public void copy(final File source, final File dest) throws IOException { final FileInputStream in = new FileInputStream(source); try { final FileOutputStream out = new FileOutputStream(dest); try { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { out.close(); } } finally { in.close(); } }
false
91
13,626,014
23,247,146
public void createPartControl(Composite parent) { FormToolkit toolkit; toolkit = new FormToolkit(parent.getDisplay()); form = toolkit.createForm(parent); form.setText("Apple Inc."); toolkit.decorateFormHeading(form); form.getBody().setLayout(new GridLayout()); chart = createChart(); final DateAxis dateAxis = new DateAxis(); viewer = new GraphicalViewerImpl(); viewer.setRootEditPart(new ScalableRootEditPart()); viewer.setEditPartFactory(new ChartEditPartFactory(dateAxis)); viewer.createControl(form.getBody()); viewer.setContents(chart); viewer.setEditDomain(new EditDomain()); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { System.err.println("selectionChanged " + event.getSelection()); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { deleteAction.update(); } }); ActionRegistry actionRegistry = new ActionRegistry(); createActions(actionRegistry); ContextMenuProvider cmProvider = new BlockContextMenuProvider(viewer, actionRegistry); viewer.setContextMenu(cmProvider); getSite().setSelectionProvider(viewer); deleteAction.setSelectionProvider(viewer); viewer.getEditDomain().getCommandStack().addCommandStackEventListener(new CommandStackEventListener() { public void stackChanged(CommandStackEvent event) { undoAction.setEnabled(viewer.getEditDomain().getCommandStack().canUndo()); redoAction.setEnabled(viewer.getEditDomain().getCommandStack().canRedo()); } }); Data data = Data.getData(); chart.setInput(data); DateRange dateRange = new DateRange(0, 50); dateAxis.setDates(data.date); dateAxis.setSelectedRange(dateRange); slider = new Slider(form.getBody(), SWT.NONE); slider.setMinimum(0); slider.setMaximum(data.close.length - 1); slider.setSelection(dateRange.start); slider.setThumb(dateRange.length); slider.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { DateRange r = new DateRange(slider.getSelection(), slider.getThumb()); dateAxis.setSelectedRange(r); } }); final Scale spinner = new Scale(form.getBody(), SWT.NONE); spinner.setMinimum(5); spinner.setMaximum(data.close.length - 1); spinner.setSelection(dateRange.length); spinner.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { slider.setThumb(spinner.getSelection()); DateRange r = new DateRange(slider.getSelection(), slider.getThumb()); dateAxis.setSelectedRange(r); } }); GridDataFactory.defaultsFor(viewer.getControl()).grab(true, true).align(GridData.FILL, GridData.FILL).applyTo(viewer.getControl()); GridDataFactory.defaultsFor(slider).grab(true, false).align(GridData.FILL, GridData.FILL).grab(true, false).applyTo(slider); GridDataFactory.defaultsFor(spinner).grab(true, false).align(GridData.FILL, GridData.FILL).grab(true, false).applyTo(spinner); getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this); }
@Override public synchronized HttpURLConnection getTileUrlConnection(int zoom, int tilex, int tiley) throws IOException { HttpURLConnection conn = null; try { String url = getTileUrl(zoom, tilex, tiley); conn = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { throw e; } catch (Exception e) { log.error("", e); throw new IOException(e); } try { i.set("conn", conn); i.eval("addHeaders(conn);"); } catch (EvalError e) { String msg = e.getMessage(); if (!AH_ERROR.equals(msg)) { log.error(e.getClass() + ": " + e.getMessage(), e); throw new IOException(e); } } return conn; }
false
92
1,663,419
22,642,186
private 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(); } }
@Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("summarysort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("summarysort :: INPATH not given."); return 3; } final String outS = (String) parser.getOptionValue(outputDirOpt); final Path wrkDir = new Path(args.get(0)), in = new Path(args.get(1)), out = outS == null ? null : new Path(outS); final boolean verbose = parser.getBoolean(verboseOpt); final Configuration conf = getConf(); final Timer t = new Timer(); try { @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = sortOne(conf, in, wrkDir, "summarysort", ""); System.out.printf("summarysort :: Waiting for job completion...\n"); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("summarysort :: Job failed."); return 4; } System.out.printf("summarysort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("summarysort :: Merging output..."); t.start(); final FileSystem srcFS = wrkDir.getFileSystem(conf); final FileSystem dstFS = out.getFileSystem(conf); final OutputStream outs = dstFS.create(out); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, in.getName() + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("summarysort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarysort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Output merging failed: %s\n", e); return 5; } return 0; }
true
93
17,267,680
11,103,449
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; }
@Override public void run() { try { IOUtils.copy(_is, processOutStr); } catch (final IOException ioe) { proc.destroy(); } finally { IOUtils.closeQuietly(_is); IOUtils.closeQuietly(processOutStr); } }
true
94
11,245,902
11,334,494
public static void uploadFile(File in, String out, String host, int port, String path, String login, String password, boolean renameIfExist) throws IOException { FTPClient ftp = null; try { m_logCat.info("Uploading " + in + " to " + host + ":" + port + " at " + path); ftp = new FTPClient(); int reply; ftp.connect(host, port); m_logCat.info("Connected to " + host + "... Trying to authenticate"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); m_logCat.error("FTP server " + host + " refused connection."); throw new IOException("Cannot connect to the FTP Server: connection refused."); } if (!ftp.login(login, password)) { ftp.logout(); throw new IOException("Cannot connect to the FTP Server: login / password is invalid!"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.changeWorkingDirectory(path)) { m_logCat.warn("Remote working directory: " + path + "does not exist on the FTP Server ..."); m_logCat.info("Trying to create remote directory: " + path); if (!ftp.makeDirectory(path)) { m_logCat.error("Failed to create remote directory: " + path); throw new IOException("Failed to store " + in + " in the remote directory: " + path); } if (!ftp.changeWorkingDirectory(path)) { m_logCat.error("Failed to change directory. Unexpected error"); throw new IOException("Failed to change to remote directory : " + path); } } if (out == null) { out = in.getName(); if (out.startsWith("/")) { out = out.substring(1); } } if (renameIfExist) { String[] files = ftp.listNames(); String f = in + out; for (int i = 0; i < files.length; i++) { if (files[i].equals(out)) { m_logCat.debug("Found existing file on the server: " + out); boolean rename_ok = false; String bak = "_bak"; int j = 0; String newExt = null; while (!rename_ok) { if (j == 0) newExt = bak; else newExt = bak + j; if (ftp.rename(out, out + newExt)) { m_logCat.info(out + " renamed to " + out + newExt); rename_ok = true; } else { m_logCat.warn("Renaming to " + out + newExt + " has failed!, trying again ..."); j++; } } break; } } } InputStream input = new FileInputStream(in); m_logCat.info("Starting transfert of " + in); ftp.storeFile(out, input); m_logCat.info(in + " uploaded successfully"); input.close(); ftp.logout(); } catch (FTPConnectionClosedException e) { m_logCat.error("Server closed connection.", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } } }
public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
false
95
7,344,728
15,286,502
public static String hash(String plainText) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(plainText.getBytes(), 0, plainText.length()); String hash = new BigInteger(1, m.digest()).toString(16); if (hash.length() == 31) { hash = "0" + hash; } return hash; }
public static String md5(String senha) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Ocorreu NoSuchAlgorithmException"); } md.update(senha.getBytes()); byte[] xx = md.digest(); String n2 = null; StringBuffer resposta = new StringBuffer(); for (int i = 0; i < xx.length; i++) { n2 = Integer.toHexString(0XFF & ((int) (xx[i]))); if (n2.length() < 2) { n2 = "0" + n2; } resposta.append(n2); } return resposta.toString(); }
true
96
13,521,323
346,058
public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
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!"); }
true
97
708,766
557,734
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!"); }
public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } }
true
98
7,346,958
16,005,909
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
public static byte[] hash(String identifier) { if (function.equals("SHA-1")) { try { MessageDigest md = MessageDigest.getInstance(function); md.reset(); byte[] code = md.digest(identifier.getBytes()); byte[] value = new byte[KEY_LENGTH / 8]; int shrink = code.length / value.length; int bitCount = 1; for (int j = 0; j < code.length * 8; j++) { int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8); if (currBit == 1) bitCount++; if (((j + 1) % shrink) == 0) { int shrinkBit = (bitCount % 2 == 0) ? 0 : 1; value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8)); bitCount = 1; } } return value; } catch (Exception e) { e.printStackTrace(); } } if (function.equals("CRC32")) { CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(identifier.getBytes()); long code = crc32.getValue(); code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } if (function.equals("Java")) { int code = identifier.hashCode(); code &= (0xffffffff >>> (32 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } return null; }
true
99
8,023,601
10,896,362
protected static List<Pattern> getBotPatterns() { List<Pattern> patterns = new ArrayList<Pattern>(); try { Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { Pattern pattern = Pattern.compile(line); patterns.add(pattern); } } in.close(); } } catch (IOException e) { throw new RuntimeException("Error reading bot user-agent configuration", e); } return patterns; }
private HttpResponse executePutPost(HttpEntityEnclosingRequestBase request, String content) { try { if (LOG.isTraceEnabled()) { LOG.trace("Content: {}", content); } StringEntity e = new StringEntity(content, "UTF-8"); e.setContentType("application/json"); request.setEntity(e); return executeRequest(request); } catch (Exception e) { throw Exceptions.propagate(e); } }
false