label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: 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)); } Code Sample 2: 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(); }
11
Code Sample 1: 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]); } ; } Code Sample 2: 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; }
11
Code Sample 1: 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; } Code Sample 2: 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()); }
00
Code Sample 1: 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()); } } Code Sample 2: 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; }
00
Code Sample 1: 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(); } } Code Sample 2: 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); } }
00
Code Sample 1: 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; } Code Sample 2: 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(); }
00
Code Sample 1: 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"); } } Code Sample 2: 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 ""; }
11
Code Sample 1: 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; } Code Sample 2: @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; }
11
Code Sample 1: 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); } } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: public 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); } } Code Sample 2: 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(); } } }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: 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(); } }
11
Code Sample 1: 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(); } } } Code Sample 2: 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(); }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: 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(); }
00
Code Sample 1: 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"); } Code Sample 2: 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(); } }
00
Code Sample 1: @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); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: 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(); } Code Sample 2: 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; }
00
Code Sample 1: 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(); } } } Code Sample 2: public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: 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); } } Code Sample 2: 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; }
11
Code Sample 1: private static void copyFile(File inputFile, File outputFile) throws IOException { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public 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(); } }
00
Code Sample 1: 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); } Code Sample 2: @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(); } } }
00
Code Sample 1: @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"); } } Code Sample 2: 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; }
00
Code Sample 1: 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(); } Code Sample 2: @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; } }
00
Code Sample 1: 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(); } Code Sample 2: 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; }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: 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; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public 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; }
00
Code Sample 1: 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; } Code Sample 2: 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]; }
00
Code Sample 1: 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; } Code Sample 2: 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(); }
11
Code Sample 1: 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); } } } Code Sample 2: 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(); }
11
Code Sample 1: 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; } Code Sample 2: 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(); } } }
11
Code Sample 1: 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(); } } Code Sample 2: 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(); } }
11
Code Sample 1: 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); } Code Sample 2: 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(); } } } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void 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(); }
11
Code Sample 1: 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(); } } } } Code Sample 2: private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
11
Code Sample 1: public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; } Code Sample 2: public static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(frase.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } }
11
Code Sample 1: 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(); } } } Code Sample 2: @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; }
11
Code Sample 1: 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(); } Code Sample 2: 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(); } }
00
Code Sample 1: 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; } Code Sample 2: 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); } }
00
Code Sample 1: 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; } Code Sample 2: 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; } } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static 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; }
00
Code Sample 1: 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(); } } Code Sample 2: 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; }
11
Code Sample 1: 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); } } Code Sample 2: public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
00
Code Sample 1: public 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); } } Code Sample 2: 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; } }
11
Code Sample 1: public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: 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(); }
11
Code Sample 1: 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(); } Code Sample 2: 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; } }
00
Code Sample 1: 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()); } } Code Sample 2: 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; }
00
Code Sample 1: 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); } } Code Sample 2: 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); } }
00
Code Sample 1: 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)); } } Code Sample 2: 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); }
00
Code Sample 1: 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; } Code Sample 2: private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
11
Code Sample 1: 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); } Code Sample 2: 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(); } }
11
Code Sample 1: 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(); } } Code Sample 2: 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; }
11
Code Sample 1: 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; } Code Sample 2: @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(); }
00
Code Sample 1: 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; } Code Sample 2: 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"); }
00
Code Sample 1: @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) { } } } Code Sample 2: 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(); } }
11
Code Sample 1: public void setBckImg(String newPath) { try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = null; try { out = new FileOutputStream(outputFile); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } int c; if (out != null) { while ((c = in.read()) != -1) out.write(c); out.close(); } in.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE); } setPath(newPath); bckImg = new ImageIcon(getPath()); } Code Sample 2: 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(); }
00
Code Sample 1: 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); } Code Sample 2: 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"); }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void 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); }
00
Code Sample 1: 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); } } Code Sample 2: 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); } }
11
Code Sample 1: @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; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: @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); } } Code Sample 2: 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); } }
00
Code Sample 1: 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); } } Code Sample 2: 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(); }
11
Code Sample 1: public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: @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); }
00
Code Sample 1: 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); } } Code Sample 2: 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; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: 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) { ; } } } Code Sample 2: 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(); } }
11
Code Sample 1: 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; } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
11
Code Sample 1: 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); } Code Sample 2: 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); } }
11
Code Sample 1: 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; } } } Code Sample 2: 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(); }
11
Code Sample 1: 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) { } } Code Sample 2: 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); }
11
Code Sample 1: 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; } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }

This dataset collates three class-balanced code classification datasets in the wild, where splits have been stratified by label. The sources are:

  1. CodeXGLUE defect detection (sourced from: semeru/code-code-DefectDetection)
  2. BigCloneBench clone detection (sourced from: nchen909/bigclonebench-processed)
  3. CodeComplex code runtime complexity prediction (sourced from: codeparrot/codecomplex)
Downloads last month
80
Edit dataset card

Collection including ObscuraCoder/code-classification