label
int64 0
1
| func1
stringlengths 173
53.1k
| func2
stringlengths 173
53.1k
| id
int64 0
901k
|
---|---|---|---|
1 | private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } } | public static void main(String[] args) { try { int encodeFlag = 0; if (args[0].equals("-e")) { encodeFlag = Base64.ENCODE; } else if (args[0].equals("-d")) { encodeFlag = Base64.DECODE; } String infile = args[1]; String outfile = args[2]; File fin = new File(infile); FileInputStream fis = new FileInputStream(fin); BufferedInputStream bis = new BufferedInputStream(fis); Base64.InputStream b64in = new Base64.InputStream(bis, encodeFlag | Base64.DO_BREAK_LINES); File fout = new File(outfile); FileOutputStream fos = new FileOutputStream(fout); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buff = new byte[1024]; int read = -1; while ((read = b64in.read(buff)) >= 0) { bos.write(buff, 0, read); } bos.close(); b64in.close(); } catch (Exception e) { e.printStackTrace(); } } | 800 |
0 | @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); } | public static String machineInfo() { StringBuilder machineInfo = new StringBuilder(); try { Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); if ("eth0".equals(networkInterface.getDisplayName())) { for (byte b : networkInterface.getHardwareAddress()) { StringTools.appendWithDelimiter(machineInfo, String.format("%02x", b).toUpperCase(), ":"); } machineInfo.append("\n"); break; } } } catch (IOException x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } if (machineInfo.length() == 0) { return null; } String info = machineInfo.toString(); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5", "SUN"); messageDigest.update(info.getBytes()); byte[] md5 = messageDigest.digest(info.getBytes()); return new String(Base64.encodeBase64(md5)); } catch (Exception x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } return null; } | 801 |
1 | public final void copyFile(final File fromFile, final File toFile) throws IOException { this.createParentPathIfNeeded(toFile); final FileChannel sourceChannel = new FileInputStream(fromFile).getChannel(); final FileChannel targetChannel = new FileOutputStream(toFile).getChannel(); final long sourceFileSize = sourceChannel.size(); sourceChannel.transferTo(0, sourceFileSize, targetChannel); } | protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } } | 802 |
1 | public void insertRealm(final List<NewRealms> newRealms) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.add")); Iterator<NewRealms> iter = newRealms.iterator(); NewRealms newRealm; String realm; Iterator<String> iter2; while (iter.hasNext()) { newRealm = iter.next(); psImpl.setInt(3, newRealm.domainId); iter2 = newRealm.realms.iterator(); while (iter2.hasNext()) { realm = iter2.next(); psImpl.setString(1, realm); psImpl.setString(2, realm.toLowerCase(locale)); psImpl.executeUpdate(); } } } }); connection.commit(); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } | public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } | 803 |
0 | public void doUpdate(String version) { try { final String hyperlink_url = "http://xnavigator.sourceforge.net/dist/"; JFrame updateInfoFrame = null; try { JPanel panel = new JPanel(); panel.setLayout(null); panel.setBackground(new java.awt.Color(255, 255, 255)); panel.setBorder(new TitledBorder("")); ClassLoader cl = this.getClass().getClassLoader(); int BORDER_TOP = 10; int PANEL_WIDTH = 400; int TEXT_WIDTH = 360; int TEXT_HEIGHT = 50; int TEXT_LEFT = 20; int y = BORDER_TOP; I3Label title = new I3Label("XNavigator Update"); title.setBounds(30, y, 350, 25); panel.add(title); ImageIcon splash3 = new ImageIcon(Toolkit.getDefaultToolkit().getImage(cl.getResource("resources/splash3.jpg"))); JButton left = new JButton(splash3); left.setBounds(20, y += 30, 350, 235); left.setBorder(null); left.setFocusPainted(false); panel.add(left); JTextPane informText = new JTextPane(); informText.setLayout(null); informText.setBounds(TEXT_LEFT, y += 235, TEXT_WIDTH, TEXT_HEIGHT); informText.setBackground(new java.awt.Color(255, 255, 255)); informText.setEditable(false); informText.setFocusable(false); panel.add(informText); JTextPane progressText = new JTextPane(); progressText.setLayout(null); progressText.setBounds(TEXT_LEFT, y += TEXT_HEIGHT, TEXT_WIDTH, TEXT_HEIGHT); progressText.setBackground(new java.awt.Color(255, 255, 255)); progressText.setEditable(false); progressText.setFocusable(false); panel.add(progressText); updateInfoFrame = new JFrame(); updateInfoFrame.setUndecorated(false); updateInfoFrame.setTitle("XNavigator Update"); updateInfoFrame.setSize(400, 430); updateInfoFrame.getContentPane().add(panel); updateInfoFrame.setVisible(true); updateInfoFrame.setEnabled(true); updateInfoFrame.setResizable(false); updateInfoFrame.setLocation(300, 150); updateInfoFrame.addWindowListener(this); panel.repaint(); informText.setText(i18n.getString("UPDATE_CHECK_INSTANCES")); String message0 = i18n.getString("UPDATE_INSTANCES"); JLabel label01 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">XNavigator Update</span></body></html>"); JLabel label02 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message0 + " " + "</span></body></html>"); Object[] objects0 = { label01, label02 }; Object[] options0 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int option = JOptionPane.showOptionDialog(null, objects0, "Update", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options0, options0[0]); if (option == 0) { } else { updateInfoFrame.dispose(); return; } informText.setText(i18n.getString("UPDATE_CHECK_ENVIRONMENT")); if ((new File(".project")).exists()) { Object[] objects = { "Im Eclipse Projekt solltest Du besser die neueste Version aus dem SVN ziehen -Arne-", "Update abgebrochen" }; JOptionPane.showMessageDialog(null, objects, "Update Error", JOptionPane.ERROR_MESSAGE); updateInfoFrame.dispose(); return; } Object[] objects1 = { i18n.getString("UPDATE_WARNING") }; Object[] options1 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int opt = JOptionPane.showOptionDialog(null, objects1, i18n.getString("WARNING"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options1, options1[0]); if (opt == 1) { updateInfoFrame.dispose(); return; } updateInfoFrame.requestFocus(); updateInfoFrame.requestFocusInWindow(); informText.setText(i18n.getString("UPDATE_DOWNLOADING")); String updateFile = "XNavigator-" + version + ".zip"; URL url = new URL(hyperlink_url + updateFile); URLConnection conn = url.openConnection(); int fileSize = conn.getContentLength(); String urlString = url.toString(); progressText.setText("Download " + urlString + " ... 0%"); java.io.BufferedInputStream in = new java.io.BufferedInputStream(url.openStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(updateFile); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); int BUFFER_SIZE = 1024; byte data[] = new byte[BUFFER_SIZE]; int count = 0; int size = 0; int prev_perc = 0; while ((count = in.read(data, 0, BUFFER_SIZE)) > 0) { bout.write(data, 0, count); size += count; int perc = (100 * size) / fileSize; if (perc > prev_perc) { progressText.setText("Download " + urlString + " ... " + perc + "%"); prev_perc = perc; } } bout.close(); fos.close(); in.close(); progressText.setText("Download " + url.toString() + " ... ok."); informText.setText(i18n.getString("UPDATE_EXTRACTING")); boolean deleted = deleteFiles(new File("./lib"), false); if (!deleted) { updateInfoFrame.dispose(); return; } extractZipFile(updateFile, progressText); progressText.setText(i18n.getString("UPDATE_COMPLETE")); Object[] objects = { i18n.getString("UPDATE_COMPLETE") }; Object[] options = { i18n.getString("OK") }; JOptionPane.showOptionDialog(null, objects, "Success", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); System.exit(0); } catch (Exception e) { e.printStackTrace(); String message = ""; String hyperlink = ""; message = i18n.getString("UPDATE_FAILED"); hyperlink = "<a href='" + hyperlink_url + "'>" + hyperlink_url + "</a>"; JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message + " " + "</span></body></html>"); JLabel label3 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + hyperlink + "<br>" + "</span></body></html>"); JLabel label4 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + version + "</span></body></html>"); label3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); label3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 0) { try { javax.jnlp.BasicService basicService; basicService = (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService"); basicService.showDocument(new URL(hyperlink_url)); } catch (Exception e1) { e1.printStackTrace(); try { Runtime.getRuntime().exec("cmd.exe /c start " + hyperlink_url); } catch (IOException e2) { e2.printStackTrace(); } } } } }); Object[] objects = { label2, label3, label4 }; Object[] options = { i18n.getString("OK") }; updateInfoFrame.dispose(); JOptionPane.showOptionDialog(null, objects, "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); } updateInfoFrame.setVisible(false); updateInfoFrame.dispose(); } catch (Exception e) { e.printStackTrace(); } } | void write() throws IOException { if (!allowUnlimitedArgs && args != null && args.length > 1) throw new IllegalArgumentException("Only one argument allowed unless allowUnlimitedArgs is enabled"); String shebang = "#!" + interpretter; for (int i = 0; i < args.length; i++) { shebang += " " + args[i]; } shebang += '\n'; IOUtils.copy(new StringReader(shebang), outputStream); } | 804 |
1 | public void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } | public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } | 805 |
1 | public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } | @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); } } | 806 |
1 | public static int gzipFile(File file_input, String file_output) { File gzip_output = new File(file_output); GZIPOutputStream gzip_out_stream; try { FileOutputStream out = new FileOutputStream(gzip_output); gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_GZIP_FAIL; } try { gzip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; } | public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } | 807 |
1 | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | public String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { } return digest; } | 808 |
0 | public static void main(String[] args) { CookieManager cm = new CookieManager(); try { URL url = new URL("http://www.hccp.org/test/cookieTest.jsp"); URLConnection conn = url.openConnection(); conn.connect(); cm.storeCookies(conn); System.out.println(cm); cm.setCookies(url.openConnection()); } catch (IOException ioe) { ioe.printStackTrace(); } } | private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } } | 809 |
0 | @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } | public void render(HttpServletRequest request, HttpServletResponse response, File file, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } if (file.length() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Cannot send file greater than 2GB"); } response.setContentLength((int) file.length()); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); } | 810 |
0 | public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } | public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); PreparedStatement ps = con.prepareStatement("INSERT INTO USERS (id,firstname,lastname,username) VALUES (?,?,?,?)"); ps.setInt(1, 5); ps.setString(2, entry.getEntry().getAttribute(db2ldap.get("firstname")).getStringValue()); ps.setString(3, entry.getEntry().getAttribute(db2ldap.get("lastname")).getStringValue()); ps.setString(4, entry.getEntry().getAttribute(db2ldap.get("username")).getStringValue()); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); PreparedStatement inst = con.prepareStatement("INSERT INTO LOCATIONMAP (person,location) VALUES (?,?)"); LDAPAttribute l = entry.getEntry().getAttribute(db2ldap.get("name")); if (l == null) { con.rollback(); throw new LDAPException("Location is required", LDAPException.OBJECT_CLASS_VIOLATION, "Location is required"); } String[] vals = l.getStringValueArray(); for (int i = 0; i < vals.length; i++) { ps.setString(1, vals[i]); ResultSet rs = ps.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } inst.setInt(1, 5); inst.setInt(2, rs.getInt("id")); inst.executeUpdate(); } ps.close(); inst.close(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not add entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not add entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } | 811 |
1 | private void transformFile(File input, File output, Cipher cipher, boolean compress, String progressMessage) throws IOException { FileInputStream fileInputStream = new FileInputStream(input); InputStream inputStream; if (progressMessage != null) { inputStream = new ProgressMonitorInputStream(null, progressMessage, fileInputStream); } else { inputStream = fileInputStream; } FilterInputStream is = new BufferedInputStream(inputStream); FilterOutputStream os = new BufferedOutputStream(new FileOutputStream(output)); FilterInputStream fis; FilterOutputStream fos; if (compress) { fis = is; fos = new GZIPOutputStream(new CipherOutputStream(os, cipher)); } else { fis = new GZIPInputStream(new CipherInputStream(is, cipher)); fos = os; } byte[] buffer = new byte[cipher.getBlockSize() * blocksInBuffer]; int readLength = fis.read(buffer); while (readLength != -1) { fos.write(buffer, 0, readLength); readLength = fis.read(buffer); } if (compress) { GZIPOutputStream gos = (GZIPOutputStream) fos; gos.finish(); } fos.close(); fis.close(); } | public static void copyFile(File sourceFile, File destFile) throws IOException { 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(); } } } | 812 |
1 | public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } | 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; } | 813 |
0 | public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); if (login) { postURL = "http://upload.badongo.com/mpu_upload.php"; } HttpPost httppost = new HttpPost(postURL); file = new File("g:/S2SClient.7z"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); if (login) { mpEntity.addPart("PHPSESSID", new StringBody(dataid)); } mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into badongo.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("Upload response : " + uploadresponse); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("res " + uploadresponse); httpclient.getConnectionManager().shutdown(); } | 814 |
0 | protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } if (LOCAL_LOGV) { Log.v(TAG, "httpConnection: params list"); Log.v(TAG, "\ttoken\t\t= " + token); Log.v(TAG, "\turl\t\t= " + url); Log.v(TAG, "\tUser-Agent\t\t=" + mUserAgent); Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.v(TAG, "\tisProxySet\t= " + isProxySet); Log.v(TAG, "\tproxyHost\t= " + proxyHost); Log.v(TAG, "\tproxyPort\t= " + proxyPort); } AndroidHttpClient client = null; try { URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch(method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileUrl = MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } } String extraHttpParams = MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number(); String line1Key = MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; } | public static Document getResponse(HttpClient client, HttpRequestBase request) { try { HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); System.err.println(statusLine.getStatusCode() + " data: " + statusLine.getReasonPhrase()); System.err.println("executing request " + request.getURI()); HttpEntity entity = response.getEntity(); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(entity.getContent()); return doc; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } | 815 |
0 | @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } } | public static void copy(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(); } | 816 |
1 | public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } } | public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; } | 817 |
1 | public File convert(URI uri) throws DjatokaException { processing.add(uri.toString()); File urlLocal = null; try { logger.info("processingRemoteURI: " + uri.toURL()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream(uri.toURL()); String ext = uri.toURL().toString().substring(uri.toURL().toString().lastIndexOf(".") + 1).toLowerCase(); if (ext.equals(FORMAT_ID_TIF) || ext.equals(FORMAT_ID_TIFF)) { urlLocal = File.createTempFile("convert" + uri.hashCode(), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey(ext) && (formatMap.get(ext).equals(FORMAT_MIMEYPE_JP2) || formatMap.get(ext).equals(FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + ext); isJp2 = true; } else { if (src.markSupported()) src.mark(15); if (ImageProcessingUtils.checkIfJp2(src)) urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + FORMAT_ID_JP2); if (src.markSupported()) src.reset(); else { src.close(); src = IOUtils.getInputStream(uri.toURL()); } } if (urlLocal == null) { urlLocal = File.createTempFile("convert" + uri.hashCode(), ".img"); } urlLocal.deleteOnExit(); FileOutputStream dest = new FileOutputStream(urlLocal); IOUtils.copyStream(src, dest); if (!isJp2) urlLocal = processImage(urlLocal, uri); src.close(); dest.close(); return urlLocal; } catch (Exception e) { urlLocal.delete(); throw new DjatokaException(e); } finally { if (processing.contains(uri.toString())) processing.remove(uri.toString()); } } | public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } } | 818 |
1 | void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } | private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } } | 819 |
1 | public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); } | public boolean checkPassword(String password, String digest) { boolean passwordMatch = false; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); } byte[][] hs = split(Base64.decode(digest.getBytes()), 20); byte[] hash = hs[0]; byte[] salt = hs[1]; sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); if (MessageDigest.isEqual(hash, pwhash)) { passwordMatch = true; } } catch (NoSuchAlgorithmException nsae) { CofaxToolsUtil.log("Algorithme SHA-1 non supporte a la verification du password" + nsae + id); } return passwordMatch; } | 820 |
1 | public static void _he3Decode(String in_file) { try { File out = new File(in_file + dec_extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); InputStreamReader inputReader = new InputStreamReader(in_stream, "ISO8859_1"); OutputStreamWriter outputWriter = new OutputStreamWriter(out_stream, "ISO8859_1"); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; char char_arr[] = new char[8]; int buff_size = char_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + dec_mode + ": " + in_file + "\n" + dec_mode + " to: " + in_file + dec_extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = inputReader.read(char_arr, 0, buff_size); if (_chars_read == -1) break; for (int i = 0; i < _chars_read; i++) byte_arr[i] = (byte) char_arr[i]; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\n" + dec_mode + ": "); outputWriter.write(new String(_decode((ByteArrayOutputStream) os), "ISO-8859-1")); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } } | public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); } | 821 |
1 | public void alterar(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "update cliente set nome = ?, sexo = ?, cod_cidade = ? where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); stmt.setLong(4, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } } | public synchronized void checkout() throws SQLException, InterruptedException { Connection con = this.session.open(); con.setAutoCommit(false); String sql_stmt = DB2SQLStatements.shopping_cart_getAll(this.customer_id); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sql_stmt); res.last(); int rowcount = res.getRow(); res.beforeFirst(); ShoppingCartItem[] resArray = new ShoppingCartItem[rowcount]; int i = 0; while (res.next()) { resArray[i] = new ShoppingCartItem(); resArray[i].setCustomer_id(res.getInt("customer_id")); resArray[i].setDate_start(res.getDate("date_start")); resArray[i].setDate_stop(res.getDate("date_stop")); resArray[i].setRoom_type_id(res.getInt("room_type_id")); resArray[i].setNumtaken(res.getInt("numtaken")); resArray[i].setTotal_price(res.getInt("total_price")); i++; } this.wait(4000); try { for (int j = 0; j < rowcount; j++) { sql_stmt = DB2SQLStatements.room_date_update(resArray[j]); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } } catch (SQLException e) { e.printStackTrace(); con.rollback(); } for (int j = 0; j < rowcount; j++) { System.out.println(j); sql_stmt = DB2SQLStatements.booked_insert(resArray[j], 2); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } sql_stmt = DB2SQLStatements.shopping_cart_deleteAll(this.customer_id); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); con.commit(); this.session.close(con); } | 822 |
1 | private void copy(File from, File to) throws IOException { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } | public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } } | 823 |
0 | public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException { boolean parsed = false; try { InputStream data_stream = url.openStream(); parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp); } catch (OutputMalFormatException ex) { throw new OutputMalFormatException(ex.getMessage(), ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } return parsed; } | public void updateProfile() throws ClassNotFoundException, SQLException { Connection connection = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(this.url); connection.setAutoCommit(false); String query2 = "UPDATE customers SET password=? WHERE name=?"; String query3 = "UPDATE customers_profile " + "SET first_name=?,middle_name=?,last_name=?,address1=?" + ",address2=?,city=?,post_box=?,email=?,country=? WHERE name=?"; ps1 = connection.prepareStatement(query3); ps2 = connection.prepareStatement(query2); ps1.setString(1, this.firstName); ps1.setString(2, this.middleName); ps1.setString(3, this.lastName); ps1.setString(4, this.address1); ps1.setString(5, this.address2); ps1.setString(6, this.city); ps1.setString(7, this.postBox); ps1.setString(8, this.email); ps1.setString(9, this.country); ps1.setString(10, this.name); ps2.setString(1, this.password); ps2.setString(2, this.name); ps1.executeUpdate(); ps2.executeUpdate(); } catch (Exception ex) { connection.rollback(); } finally { try { this.connection.close(); } catch (Exception ex) { } try { ps1.close(); } catch (Exception ex) { } try { ps2.close(); } catch (Exception ex) { } } } | 824 |
0 | public void putChunk(String chunk) throws JacsonException { try { URL url = new URL(chunk); InputStream is = url.openStream(); if (inverse) drain.putChunk(chunk); is.close(); } catch (IOException broken) { if (!inverse) drain.putChunk(chunk); } } | void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } } | 825 |
0 | public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; } | private static byte[] createHash(EHashType hashType, String string) { MessageDigest md; try { md = MessageDigest.getInstance(hashType.getJavaHashType()); md.reset(); md.update(string.getBytes()); byte[] byteResult = md.digest(); return byteResult; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } | 826 |
1 | public long copyDirAllFilesToDirectory(String baseDirStr, String destDirStr) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } | public static void copy(File sourceFile, File destFile) throws IOException { 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(); } } } | 827 |
0 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | 828 |
0 | public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } | private static void stampaFoglioRisposte(HttpSession httpSess, Appelli appello, Elaborati el, StringBuffer retVal, boolean primaVolta, String url, boolean anonimo) { InputStream is = null; String html = null; final int MAX_RIGHE_PER_PAGINA = 25; long totaleDomande = EsamiDAO.trovaQuanteDomandeElaborato(el.getID()); long numPagine = 0, totalePagine = (long) Math.ceil(totaleDomande / 50.0); String urlBarcode = null; while (numPagine < totalePagine) { try { urlBarcode = URLEncoder.encode(HtmlCodeForPrint.creaBarcode("" + appello.getID() + "-" + el.getID() + "-" + (numPagine + 1), url), "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } String jsp = url + "jsp/StampaRisposte.jsp?base=" + (numPagine * MAX_RIGHE_PER_PAGINA) + "&urlbarcode=" + urlBarcode; try { URL urlJSP = new URL(jsp); is = urlJSP.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int letto = is.read(); while (letto != -1) { baos.write(letto); letto = is.read(); } html = baos.toString(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } finally { try { is.close(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } numPagine++; } } retVal.append(html); } | 829 |
0 | public boolean getAuth(String content) throws IOException { String resp_remote; try { URL url = new URL(remoteurl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("md5sum=" + content); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); resp_remote = response.toString(); wd.del(); wd.setKey(resp_remote); return true; } else { return false; } } catch (MalformedURLException e) { } catch (IOException e) { } return false; } | public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } } | 830 |
1 | public static String base64HashedString(String v) { String base64HashedPassword = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(v.getBytes()); String hashedPassword = new String(md.digest()); sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); base64HashedPassword = enc.encode(hashedPassword.getBytes()); } catch (java.security.NoSuchAlgorithmException e) { throw new NSForwardException(e, "Couldn't find the SHA hash algorithm; perhaps you do not have the SunJCE security provider installed properly?"); } return base64HashedPassword; } | public String getLongToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.toString(); } | 831 |
1 | public static boolean copyDataToNewTable(EboContext p_eboctx, String srcTableName, String destTableName, String where, boolean log, int mode) throws boRuntimeException { srcTableName = srcTableName.toUpperCase(); destTableName = destTableName.toUpperCase(); Connection cn = null; Connection cndef = null; boolean ret = false; try { boolean srcexists = false; boolean destexists = false; final InitialContext ic = new InitialContext(); cn = p_eboctx.getConnectionData(); cndef = p_eboctx.getConnectionDef(); PreparedStatement pstm = cn.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES WHERE TABLE_NAME=?"); pstm.setString(1, srcTableName); ResultSet rslt = pstm.executeQuery(); if (rslt.next()) { srcexists = true; } rslt.close(); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { destexists = true; } if (!destexists) { rslt.close(); pstm.close(); pstm = cn.prepareStatement("SELECT VIEW_NAME FROM USER_VIEWS WHERE VIEW_NAME=?"); pstm.setString(1, destTableName); rslt = pstm.executeQuery(); if (rslt.next()) { CallableStatement cstm = cn.prepareCall("DROP VIEW " + destTableName); cstm.execute(); cstm.close(); } } rslt.close(); pstm.close(); if (srcexists && !destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("CREATING_AND_COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } CallableStatement cstm = cn.prepareCall("CREATE TABLE " + destTableName + " AS SELECT * FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "")); cstm.execute(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("UPDATING_NGTDIC")); } cn.commit(); ret = true; } else if (srcexists && destexists) { if (log) { logger.finest(LoggerMessageLocalizer.getMessage("COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]"); } PreparedStatement pstm2 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? "); pstm2.setString(1, destTableName); ResultSet rslt2 = pstm2.executeQuery(); StringBuffer fields = new StringBuffer(); PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? and COLUMN_NAME=?"); while (rslt2.next()) { pstm3.setString(1, srcTableName); pstm3.setString(2, rslt2.getString(1)); ResultSet rslt3 = pstm3.executeQuery(); if (rslt3.next()) { if (fields.length() > 0) { fields.append(','); } fields.append('"').append(rslt2.getString(1)).append('"'); } rslt3.close(); } pstm3.close(); rslt2.close(); pstm2.close(); CallableStatement cstm; int recs = 0; if ((mode == 0) || (mode == 1)) { cstm = cn.prepareCall("INSERT INTO " + destTableName + "( " + fields.toString() + " ) ( SELECT " + fields.toString() + " FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "") + ")"); recs = cstm.executeUpdate(); cstm.close(); if (log) { logger.finest(LoggerMessageLocalizer.getMessage("DONE") + " [" + recs + "] " + LoggerMessageLocalizer.getMessage("RECORDS_COPIED")); } } cn.commit(); ret = true; } } catch (Exception e) { try { cn.rollback(); } catch (Exception z) { throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", z); } throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", e); } finally { try { cn.close(); } catch (Exception e) { } try { cndef.close(); } catch (Exception e) { } } return ret; } | public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); } | 832 |
0 | public static int deleteExecution(String likePatten) { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_EXCEPTION ").append(" WHERE ORDER_ID LIKE ? "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); psmt.setString(1, "%" + likePatten + "%"); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; } | protected GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); GraphicalViewerKeyHandler graphicalViewerKeyHandler = new GraphicalViewerKeyHandler(viewer); KeyHandler parentKeyHandler = graphicalViewerKeyHandler.setParent(getCommonKeyHandler()); viewer.setKeyHandler(parentKeyHandler); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); ContextMenuProvider provider = new TestContextMenuProvider(viewer, getActionRegistry()); viewer.setContextMenu(provider); getSite().registerContextMenu("cubicTestPlugin.editor.contextmenu", provider, viewer); viewer.addDropTargetListener(new DataEditDropTargetListner(((IFileEditorInput) getEditorInput()).getFile().getProject(), viewer)); viewer.addDropTargetListener(new FileTransferDropTargetListener(viewer)); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; } | 833 |
0 | public void unzip(String resource) { File f = new File(resource); if (!f.exists()) throw new RuntimeException("The specified resources does not exist (" + resource + ")"); String parent = f.getParent().toString(); try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(resource); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { log.info("Extracting archive entry: " + entry); String entryPath = new StringBuilder(parent).append(System.getProperty("file.separator")).append(entry.getName()).toString(); if (entry.isDirectory()) { log.info("Creating directory: " + entryPath); (new File(entryPath)).mkdir(); continue; } int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(entryPath); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); } } | public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } | 834 |
0 | 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!"); } | @Override public List<SheetFullName> importSheets(INetxiliaSystem workbookProcessor, WorkbookId workbookName, URL url, IProcessingConsole console) throws ImportException { try { return importSheets(workbookProcessor, workbookName, url.openStream(), console); } catch (IOException e) { throw new ImportException(url, "Cannot open workbook:" + e, e); } } | 835 |
1 | private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } | public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException { if (out != null) { close(); } FileChannel fch = new FileInputStream(from).getChannel(); FileChannel rollch = new FileOutputStream(to).getChannel(); long size = mark; int count = 0; try { while ((count += rollch.transferFrom(fch, count, size - count)) < size) { } } finally { fch.close(); rollch.close(); } out = create(to); return out; } | 836 |
1 | public String generateDigest(String password, String saltHex, String algorithm) throws NoSuchAlgorithmException { if (algorithm.equalsIgnoreCase("crypt")) { return "{CRYPT}" + UnixCrypt.crypt(password); } else if (algorithm.equalsIgnoreCase("sha")) { algorithm = "SHA-1"; } else if (algorithm.equalsIgnoreCase("md5")) { algorithm = "MD5"; } MessageDigest msgDigest = MessageDigest.getInstance(algorithm); byte[] salt = {}; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (algorithm.startsWith("SHA")) { label = (salt.length > 0) ? "{SSHA}" : "{SHA}"; } else if (algorithm.startsWith("MD5")) { label = (salt.length > 0) ? "{SMD5}" : "{MD5}"; } msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt))); return digest.toString(); } | public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; } | 837 |
1 | public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } | public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } } | 838 |
1 | public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } | public String encryptPassword(String clearPassword) throws NullPointerException { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new NullPointerException("NoSuchAlgorithmException: " + e.toString()); } sha.update(clearPassword.getBytes()); byte encryptedPassword[] = sha.digest(); sha = null; StringBuffer result = new StringBuffer(); for (int i = 0; i < encryptedPassword.length; i++) { result.append(Byte.toString(encryptedPassword[i])); } return (result.toString()); } | 839 |
0 | public static File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } | public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; } | 840 |
0 | public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; } | public static void downloadFile(String htmlUrl, String dirUrl) { try { URL url = new URL(htmlUrl); System.out.println("Opening connection to " + htmlUrl + "..."); URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); Date date = new Date(urlC.getLastModified()); System.out.println(", modified on: " + date.toLocaleString() + ")..."); System.out.flush(); FileOutputStream fos = null; String localFile = null; StringTokenizer st = new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()) localFile = st.nextToken(); fos = new FileOutputStream(dirUrl + "/" + localFile); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); System.out.println(count + " byte(s) copied"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (IOException e) { System.err.println(e.toString()); } } | 841 |
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(); } } | protected static IFile createTempFile(CodeFile codeFile) { IPath path = Util.getAbsolutePathFromCodeFile(codeFile); File file = new File(path.toOSString()); String[] parts = codeFile.getName().split("\\."); String extension = parts[parts.length - 1]; IPath ext = path.addFileExtension(extension); File tempFile = new File(ext.toOSString()); if (tempFile.exists()) { boolean deleted = tempFile.delete(); System.out.println("deleted: " + deleted); } try { boolean created = tempFile.createNewFile(); if (created) { FileOutputStream fos = new FileOutputStream(tempFile); FileInputStream fis = new FileInputStream(file); while (fis.available() > 0) { fos.write(fis.read()); } fis.close(); fos.close(); IFile iFile = Util.getFileFromPath(ext); return iFile; } } catch (IOException e) { e.printStackTrace(); } return null; } | 842 |
0 | static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } | @Override protected String doInBackground(String... params) { HttpURLConnection conn = null; String localFilePath = params[0]; if (localFilePath == null) { return null; } try { URL url = new URL(ConnectionHandler.getServerURL() + ":" + ConnectionHandler.getServerPort() + "/"); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); DataInputStream fileReader = new DataInputStream(new FileInputStream(localFilePath)); dos.write(toByte(twoHyphens + boundary + lineEnd)); dos.write(toByte("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"redpinfile\"" + lineEnd)); dos.write(toByte("Content-Type: application/octet-stream" + lineEnd)); dos.write(toByte("Content-Length: " + fileReader.available() + lineEnd)); dos.write(toByte(lineEnd)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileReader.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } dos.write(toByte(lineEnd)); dos.write(toByte(twoHyphens + boundary + twoHyphens + lineEnd)); dos.flush(); dos.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } return b.toString(); } } catch (MalformedURLException ex) { Log.w(TAG, "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.w(TAG, "error: " + ioe.getMessage(), ioe); } finally { if (conn != null) { conn.disconnect(); } } return null; } | 843 |
0 | public void loadFromFile() { if (filename == null) return; try { BufferedReader reader; try { File file = new File(filename); if (!file.exists()) return; reader = new BufferedReader(new FileReader(file)); } catch (java.security.AccessControlException e) { URL url = new URL(filename); reader = new BufferedReader(new InputStreamReader(url.openStream())); } String line; while (true) { line = reader.readLine(); if (line == null) break; String name = line.substring(0, line.indexOf("\t")); String rest1 = line.substring(line.indexOf("\t") + 1); String guiname = rest1.substring(0, rest1.indexOf("\t")); String rest2 = rest1.substring(rest1.indexOf("\t") + 1); String type = rest2.substring(0, rest2.indexOf("\t")); String value = rest2.substring(rest2.indexOf("\t") + 1); defineField(name, guiname, type); setField(name, value, true); } reader.close(); } catch (IOException e) { throw new JGameError("Error reading file '" + filename + "'.", false); } } | public static void ExtraeArchivoJAR(String Archivo, String DirJAR, String DirDestino) { FileInputStream entrada = null; FileOutputStream salida = null; try { File f = new File(DirDestino + separador + Archivo); try { f.createNewFile(); } catch (Exception sad) { sad.printStackTrace(); } InputStream source = OP_Proced.class.getResourceAsStream(DirJAR + "/" + Archivo); BufferedInputStream in = new BufferedInputStream(source); FileOutputStream out = new FileOutputStream(f); int ch; while ((ch = in.read()) != -1) out.write(ch); in.close(); out.close(); } catch (IOException ex) { System.out.println(ex); } finally { if (entrada != null) { try { entrada.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (salida != null) { try { salida.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } | 844 |
0 | public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } | public ProgramSymbol createNewProgramSymbol(int programID, String module, String symbol, int address, int size) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO ProgramSymbols " + "(programID, module, symbol, address, size)" + " VALUES (" + programID + ", '" + module + "', '" + symbol + "', " + address + ", " + size + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM ProgramSymbols WHERE " + "programID = " + programID + " AND " + "module = '" + module + "' AND " + "symbol = '" + symbol + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; } | 845 |
1 | private void copyFromZip(File zipFile) throws GLMRessourceManagerException { if (zipFile == null) throw new GLMRessourceZIPException(1); if (!zipFile.exists()) throw new GLMRessourceZIPException(2); int len = 0; byte[] buffer = ContentManager.getDefaultBuffer(); try { ZipInputStream zip_in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); ZipEntry zipEntry; File rootDir = null; while ((zipEntry = zip_in.getNextEntry()) != null) { File destFile = new File(tempDirectory, zipEntry.getName()); if (rootDir == null) rootDir = destFile.getParentFile(); if (!zipEntry.isDirectory() && destFile.getParentFile().equals(rootDir)) { if (!zipEntry.getName().equals(ContentManager.IMS_MANIFEST_FILENAME)) { FileOutputStream file_out = new FileOutputStream(new File(tempDirectory, zipEntry.getName())); while ((len = zip_in.read(buffer)) > 0) file_out.write(buffer, 0, len); file_out.flush(); file_out.close(); } } } zip_in.close(); } catch (Exception e) { throw new GLMRessourceZIPException(3); } } | private void copyFile(File from, File to) throws IOException { FileUtils.ensureParentDirectoryExists(to); byte[] buffer = new byte[1024]; int read; FileInputStream is = new FileInputStream(from); FileOutputStream os = new FileOutputStream(to); while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } is.close(); os.close(); } | 846 |
0 | public void candidatarAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade_has_recurso_humano " + "(atividade_idatividade, usuario_idusuario, ativo) " + "values " + "(" + atividade.getIdAtividade() + ", " + "" + atividade.getRecursoHumano().getIdUsuario() + ", " + "'false')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } } | private InputStream callService(String text) { InputStream in = null; try { URL url = new URL(SERVLET_URL); URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.connect(); DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); dataStream.writeBytes(text); dataStream.flush(); dataStream.close(); int responseCode = httpConn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); } return in; } | 847 |
1 | public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); } | public static void copyTo(File src, File dest) throws IOException { if (src.equals(dest)) throw new IOException("copyTo src==dest file"); FileOutputStream fout = new FileOutputStream(dest); InputStream in = new FileInputStream(src); IOUtils.copyTo(in, fout); fout.flush(); fout.close(); in.close(); } | 848 |
0 | @SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } } | public boolean createUser(String username, String password, String name) throws Exception { boolean user_created = false; try { statement = connect.prepareStatement("SELECT COUNT(*) from toepen.users WHERE username = ? LIMIT 1"); statement.setString(1, username); resultSet = statement.executeQuery(); resultSet.next(); if (resultSet.getInt(1) == 0) { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); long ctime = System.currentTimeMillis() / 1000; statement = connect.prepareStatement("INSERT INTO toepen.users " + "(username, password, name, ctime) " + "VALUES (?, ?, ?, ?)"); statement.setString(1, username); statement.setString(2, password_hash); statement.setString(3, name); statement.setLong(4, ctime); if (statement.executeUpdate() > 0) { user_created = true; } } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_created; } } | 849 |
0 | public static String md5It(String data) { MessageDigest digest; String output = ""; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); for (byte b : hash) { output = output + String.format("%02X", b); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Authenticator.class.getName()).log(Level.SEVERE, null, ex); } return output; } | private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; } | 850 |
1 | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.debug("Random GUID error: " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | public byte[] evaluateResponse(byte[] responseBytes) throws SaslException { if (firstEvaluation) { firstEvaluation = false; StringBuilder challenge = new StringBuilder(100); Iterator iter = configurationManager.getRealms().values().iterator(); Realm aRealm; while (iter.hasNext()) { aRealm = (Realm) iter.next(); if (aRealm.getFullRealmName().equals("null")) continue; challenge.append("realm=\"" + aRealm.getFullRealmName() + "\""); challenge.append(","); } String nonceUUID = UUID.randomUUID().toString(); String nonce = null; try { nonce = new String(Base64.encodeBase64(MD5Digest(String.valueOf(System.nanoTime() + ":" + nonceUUID))), "US-ASCII"); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } catch (GeneralSecurityException uee) { throw new SaslException(uee.getMessage(), uee); } nonces.put(nonce, new ArrayList()); nonces.get(nonce).add(Integer.valueOf(1)); challenge.append("nonce=\"" + nonce + "\""); challenge.append(","); challenge.append("qop=\"" + configurationManager.getSaslQOP() + "\""); challenge.append(","); challenge.append("charset=\"utf-8\""); challenge.append(","); challenge.append("algorithm=\"md5-sess\""); if (configurationManager.getSaslQOP().indexOf("auth-conf") != -1) { challenge.append(","); challenge.append("cipher-opts=\"" + configurationManager.getDigestMD5Ciphers() + "\""); } try { return Base64.encodeBase64(challenge.toString().getBytes("US-ASCII")); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } } else { String nonce = null; if (!Base64.isArrayByteBase64(responseBytes)) { throw new SaslException("Can not decode Base64 Content", new MalformedBase64ContentException()); } responseBytes = Base64.decodeBase64(responseBytes); List<byte[]> splittedBytes = splitByteArray(responseBytes, (byte) 0x3d); int tokenCountMinus1 = splittedBytes.size() - 1, lastCommaPos; Map rawDirectives = new HashMap(); String key = null; Map<String, String> directives; try { key = new String(splittedBytes.get(0), "US-ASCII"); for (int i = 1; i < tokenCountMinus1; i++) { key = responseTokenProcessor(splittedBytes, rawDirectives, key, i, tokenCountMinus1); } responseTokenProcessor(splittedBytes, rawDirectives, key, tokenCountMinus1, tokenCountMinus1); if (rawDirectives.containsKey("charset")) { String value = new String((byte[]) rawDirectives.get("charset"), "US-ASCII").toLowerCase(locale); if (value.equals("utf-8")) { encoding = "UTF-8"; } } if (encoding.equals("ISO-8859-1")) { decodeAllAs8859(rawDirectives); } else { decodeMixed(rawDirectives); } directives = rawDirectives; } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage()); } if (!directives.containsKey("username") || !directives.containsKey("nonce") || !directives.containsKey("nc") || !directives.containsKey("cnonce") || !directives.containsKey("response")) { throw new SaslException("Digest-Response lacks at least one neccesery key-value pair"); } if (directives.get("username").indexOf('@') != -1) { throw new SaslException("digest-response username field must not include domain name", new AuthenticationException()); } if (!directives.containsKey("qop")) { directives.put("qop", QOP_AUTH); } if (!directives.containsKey("realm") || ((String) directives.get("realm")).equals("")) { directives.put("realm", "null"); } nonce = (String) directives.get("nonce"); if (!nonces.containsKey(nonce)) { throw new SaslException("Illegal nonce value"); } List<Integer> nonceListInMap = nonces.get(nonce); int nc = Integer.parseInt((String) directives.get("nc"), 16); if (nonceListInMap.get(nonceListInMap.size() - 1).equals(Integer.valueOf(nc))) { nonceListInMap.add(Integer.valueOf(++nc)); } else { throw new SaslException("Illegal nc value"); } nonceListInMap = null; if (directives.get("qop").equals(QOP_AUTH_INT)) integrity = true; else if (directives.get("qop").equals(QOP_AUTH_CONF)) privacy = true; if (privacy) { if (!directives.containsKey("cipher")) { throw new SaslException("Message confidentially required but cipher entry is missing"); } sessionCipher = directives.get("cipher").toLowerCase(locale); if ("3des,des,rc4-40,rc4,rc4-56".indexOf(sessionCipher) == -1) { throw new SaslException("Unsupported cipher for message confidentiality"); } } String realm = directives.get("realm").toLowerCase(Locale.getDefault()); String username = directives.get("username").toLowerCase(locale); if (username.indexOf('@') == -1) { if (!directives.get("realm").equals("null")) { username += directives.get("realm").substring(directives.get("realm").indexOf('@')); } else if (directives.get("authzid").indexOf('@') != -1) { username += directives.get("authzid").substring(directives.get("authzid").indexOf('@')); } } DomainWithPassword domainWithPassword = configurationManager.getRealmPassword(realm, username); if (domainWithPassword == null || domainWithPassword.getPassword() == null) { log.warn("The supplied username and/or realm do(es) not match a registered entry"); return null; } if (realm.equals("null") && username.indexOf('@') == -1) { username += "@" + domainWithPassword.getDomain(); } byte[] HA1 = toByteArray(domainWithPassword.getPassword()); for (int i = domainWithPassword.getPassword().length - 1; i >= 0; i--) { domainWithPassword.getPassword()[i] = 0xff; } domainWithPassword = null; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (GeneralSecurityException gse) { throw new SaslException(gse.getMessage()); } md.update(HA1); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); if (directives.containsKey("authzid")) { md.update(":".getBytes()); md.update((directives.get("authzid")).getBytes()); } MD5DigestSessionKey = HA1 = md.digest(); String MD5DigestSessionKeyToHex = toHex(HA1, HA1.length); md.update("AUTHENTICATE".getBytes()); md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } byte[] HA2 = md.digest(); String HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); byte[] responseHash = md.digest(); String HexResponseHash = toHex(responseHash, responseHash.length); if (HexResponseHash.equals(directives.get("response"))) { md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } HA2 = md.digest(); HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); responseHash = md.digest(); return finalizeAuthentication.finalize(responseHash, username); } else { log.warn("Improper credentials"); return null; } } } | 851 |
0 | private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; } | public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } | 852 |
0 | protected void runTests(URL pBaseURL, String pName, String pHref) throws Exception { URL url = new URL(pBaseURL, pHref); InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); Document document = getDocumentBuilder().parse(isource); NodeList schemas = document.getElementsByTagNameNS(null, "Schema"); for (int i = 0; i < schemas.getLength(); i++) { Element schema = (Element) schemas.item(i); runTest(url, schema.getAttribute("name"), schema.getAttribute("href")); } } | public static void loginSkyDrive() throws Exception { System.out.println("login "); u = new URL(loginurl); uc = (HttpURLConnection) u.openConnection(); uc.setRequestProperty("Cookie", msprcookie + ";" + mspokcookie); uc.setDoOutput(true); uc.setRequestMethod("POST"); uc.setInstanceFollowRedirects(false); pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true); pw.print("login=dinesh007007%40hotmail.com&passwd=&SI=Sign+in&type=11&LoginOptions=3&NewUser=1&MEST=&PPSX=Passpor&PPFT=" + ppft + "&PwdPad=&sso=&i1=&i2=1&i3=10524&i4=&i12=1&i13=&i14=437&i15=624&i16=3438"); pw.flush(); pw.close(); System.out.println(uc.getResponseCode()); Map<String, List<String>> headerFields = uc.getHeaderFields(); if (headerFields.containsKey("Set-Cookie")) { List<String> header = headerFields.get("Set-Cookie"); for (int i = 0; i < header.size(); i++) { tmp = header.get(i); System.out.println(tmp); } } location = uc.getHeaderField("Location"); System.out.println("Location : " + location); System.out.println("going to open paaport page"); DefaultHttpClient d = new DefaultHttpClient(); HttpGet hg = new HttpGet("https://skydrive.live.com"); hg.setHeader("Cookie", msprcookie + ";" + mspokcookie); HttpResponse execute = d.execute(hg); HttpEntity entity = execute.getEntity(); System.out.println(EntityUtils.toString(entity)); System.out.println(execute.getStatusLine()); Header[] allHeaders = execute.getAllHeaders(); for (int i = 0; i < allHeaders.length; i++) { System.out.println(allHeaders[i].getName() + " : " + allHeaders[i].getValue()); } } | 853 |
1 | private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); } | public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel srcChannel = new FileInputStream(inputFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outputFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } | 854 |
1 | private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } } | public int executeUpdate(String query, QueryParameter params) throws DAOException { PreparedStatement ps = null; Query queryObj = getModel().getQuery(query); if (conditionalQueries != null && conditionalQueries.containsKey(query)) { queryObj = (Query) conditionalQueries.get(query); } String sql = queryObj.getStatement(params.getVariables()); logger.debug(sql); try { if (con == null || con.isClosed()) { con = DataSource.getInstance().getConnection(getModel().getDataSource()); } ps = con.prepareStatement(sql); setParameters(ps, queryObj, params); return ps.executeUpdate(); } catch (SQLException e) { logger.error("DataBase Error :", e); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } catch (Exception ex) { logger.error("Error :", ex); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", ex.getMessage()); } finally { try { if (!transactionMode) con.commit(); if (ps != null) ps.close(); if (!transactionMode && con != null) con.close(); } catch (SQLException e) { throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } } } | 855 |
1 | public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); } | private String hash(String clearPassword) { if (salt == 0) return null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(salt); md.update(saltString.getBytes()); md.update(clearPassword.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString(); return digestStr; } | 856 |
1 | public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); } | private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } } | 857 |
1 | public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } | private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } } | 858 |
1 | @Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } } | public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } | 859 |
1 | public static void copyFile(File in, File out, long maxCount) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); if (maxCount == 0) maxCount = sourceChannel.size(); try { final long size = sourceChannel.size(); long position = 0; while (position < size) { position += sourceChannel.transferTo(position, maxCount, destinationChannel); } } finally { sourceChannel.close(); destinationChannel.close(); } } | 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(); } } } | 860 |
0 | public static void main(String[] args) throws Exception { URL url = new URL("http://www.sohu.com"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, Charset.forName("GB18030")); FileOutputStream fos = new FileOutputStream("gen/sohu2.html"); OutputStreamWriter osw = new OutputStreamWriter(fos); char[] b = new char[2048]; int temp; while (-1 != (temp = isr.read(b, 0, b.length))) { osw.write(b); } osw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; } | public void update() { if (url == null) { throw new IllegalArgumentException("URL cannot be null!"); } try { URLConnection urlConnection = url.openConnection(); urlConnection.setRequestProperty("User-Agent", Settings.INSTANCE.getUserAgent()); SyndFeedInput input = new SyndFeedInput(); SyndFeed syndFeed = input.build(new XmlReader(url)); Channel channel = (Channel) syndFeed.createWireFeed(syndFeed.getFeedType()); long lastModified = urlConnection.getLastModified(); if (feed.getLastModified() != lastModified) { Server.print("Updating: " + feed.getName()); feed.setLastModified(lastModified); ArrayList<String> cachedItems = getCachedItems(); List<Item> items = channel.getItems(); if (items.isEmpty()) { return; } if (cachedItems.isEmpty()) { Database.INSTANCE.addItems(feed, items); } else { for (Item item : items) { if (!cachedItems.contains(item.getTitle())) { Database.INSTANCE.addItem(feed, item); } } } cacheItems(items); Settings.INSTANCE.persist(); Server.print("Done updating: " + feed.getName()); } } catch (ConnectException e) { Server.print("Could not connect to \"" + feed.getName() + "\""); } catch (SocketException e) { Server.print("Could not connect to \"" + feed.getName() + "\""); } catch (Exception e) { e.printStackTrace(); } } | 861 |
0 | public String postData(String result, DefaultHttpClient httpclient) { try { HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create"); StringEntity se = new StringEntity(result); se.setContentEncoding(HTTP.UTF_8); se.setContentType("application/json"); post.setEntity(se); post.setHeader("Content-Type", "application/json"); post.setHeader("Accept", "*/*"); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); InputStream instream; instream = entity.getContent(); responseMessage = read(instream); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseMessage; } | private String calculateMD5(String value) { String finalString; try { MessageDigest md5Alg = MessageDigest.getInstance("MD5"); md5Alg.reset(); md5Alg.update(value.getBytes()); byte messageDigest[] = md5Alg.digest(); StringBuilder hexString = new StringBuilder(256); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } finalString = hexString.toString(); } catch (NoSuchAlgorithmException exc) { throw new RuntimeException("Hashing error happened:", exc); } return finalString; } | 862 |
0 | private String getRenderedBody(String spec) throws Exception { log.entering(Rss2MailTask.class.getName(), "getRenderedBody"); final URL url = new URL(spec); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); final InputStream inputStream = connection.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; final StringBuffer bf = new StringBuffer(); while (line != null) { line = reader.readLine(); if (line != null) { bf.append(line); } } log.exiting(Rss2MailTask.class.getName(), "getRenderedBody"); return bf.toString(); } | public void initialize(AtomPropsMenu menu) { propertiesMenu = menu; if (shieldings == null) { try { URL url = this.getClass().getClassLoader().getResource(RF); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); SharcReader sr1 = new SharcReader(br); shieldings = new Hashtable(); while (sr1.hasNext()) { SharcShielding ss1 = sr1.next(); shieldings.put(ss1.getMethod(), ss1); } String[] shieldingNames = new String[shieldings.size()]; int i = 0; Enumeration k = shieldings.keys(); while (k.hasMoreElements()) { shieldingNames[i] = (String) k.nextElement(); i++; } dialog = new SelectSharcReference(null, shieldingNames, true); } catch (Exception ex) { shieldings = null; } } } | 863 |
1 | public static void copy(File file, File dir, boolean overwrite) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); File out = new File(dir, file.getName()); if (out.exists() && !overwrite) { throw new IOException("File: " + out + " already exists."); } FileOutputStream fos = new FileOutputStream(out, false); byte[] block = new byte[4096]; int read = bis.read(block); while (read != -1) { fos.write(block, 0, read); read = bis.read(block); } } | @Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); } | 864 |
1 | public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } | protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } } | 865 |
1 | public AbstractASiCSignatureService(InputStream documentInputStream, DigestAlgo digestAlgo, RevocationDataService revocationDataService, TimeStampService timeStampService, String claimedRole, IdentityDTO identity, byte[] photo, TemporaryDataStorage temporaryDataStorage, OutputStream documentOutputStream) throws IOException { super(digestAlgo); this.temporaryDataStorage = temporaryDataStorage; this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".asice"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ASiCSignatureFacet(this.tmpFile, digestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(claimedRole); xadesSignatureFacet.setXadesNamespacePrefix("xades"); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } | private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; } | 866 |
0 | public static String hashMD5(String entrada) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(entrada.getBytes(), 0, entrada.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } | @Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; } | 867 |
1 | public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } | public AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; } | 868 |
1 | public ArrayList parseFile(File newfile) throws IOException { String s; String firstname; String secondname; String direction; String header; String name = null; String[] tokens; boolean readingHArrays = false; boolean readingVArrays = false; boolean readingAArrays = false; ArrayList xturndat = new ArrayList(); ArrayList yturndat = new ArrayList(); ArrayList ampturndat = new ArrayList(); int nvalues; URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues < 1) continue; firstname = tokens[0]; secondname = tokens[1]; if (secondname.startsWith("BPM")) { if (readingHArrays) dumpxData(name, xturndat); else if (readingVArrays) dumpyData(name, yturndat); else if (readingAArrays) dumpampData(name, ampturndat); direction = tokens[4]; if (direction.equals("HORIZONTAL")) { readingHArrays = true; readingVArrays = false; readingAArrays = false; } if (direction.equals("VERTICAL")) { readingVArrays = true; readingHArrays = false; readingAArrays = false; } if (direction.equals("AMPLITUDE")) { readingVArrays = false; readingHArrays = false; readingAArrays = true; } name = tokens[3]; xturndat.clear(); yturndat.clear(); ampturndat.clear(); } if (secondname.startsWith("WAVEFORM")) continue; if (nvalues == 3) { if (readingHArrays) xturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingVArrays) yturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingAArrays) ampturndat.add(new Double(Double.parseDouble(tokens[2]))); } } dumpampData(name, ampturndat); data.add(xdatamap); data.add(ydatamap); data.add(ampdatamap); return data; } | public Vector Get() throws Exception { String query_str = BuildYahooQueryString(); if (query_str == null) return null; Vector result = new Vector(); HttpURLConnection urlc = null; try { URL url = new URL(URL_YAHOO_QUOTE + "?" + query_str + "&" + FORMAT); urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/html;charset=UTF-8"); if (urlc.getResponseCode() == 200) { InputStream in = urlc.getInputStream(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String msg = null; while ((msg = reader.readLine()) != null) { ExchangeRate rate = ParseYahooData(msg); if (rate != null) result.add(rate); } } finally { if (reader != null) try { reader.close(); } catch (Exception e1) { } if (in != null) try { in.close(); } catch (Exception e1) { } } return result; } } finally { if (urlc != null) try { urlc.disconnect(); } catch (Exception e) { } } return null; } | 869 |
0 | protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } } | public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } } | 870 |
0 | private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } | public static void invokeServlet(String op, String user) throws Exception { boolean isSayHi = true; try { if (!"sayHi".equals(op)) { isSayHi = false; } URL url = new URL("http://localhost:9080/helloworld/*.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); out.write("Operation=" + op); if (!isSayHi) { out.write("&User=" + user); } out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); boolean correctReturn = false; String response; if (isSayHi) { while ((response = in.readLine()) != null) { if (response.contains("Bonjour")) { System.out.println(" sayHi server return: Bonjour"); correctReturn = true; break; } } } else { while ((response = in.readLine()) != null) { if (response.contains("Hello CXF")) { System.out.println(" greetMe server return: Hello CXF"); correctReturn = true; break; } } } if (!correctReturn) { System.out.println("Can't got correct return from server."); } in.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } | 871 |
0 | public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } | public void alterarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException { PreparedStatement stmt = null; String sql = "UPDATE discursiva SET gabarito=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setString(1, q.getGabarito()); stmt.setInt(2, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } | 872 |
1 | public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } } | 873 |
0 | InputStream createInputStream(FileInfo fi) throws IOException, MalformedURLException { if (fi.inputStream != null) return fi.inputStream; else if (fi.url != null && !fi.url.equals("")) return new URL(fi.url + fi.fileName).openStream(); else { File f = new File(fi.directory + fi.fileName); if (f == null || f.isDirectory()) return null; else { InputStream is = new FileInputStream(f); if (fi.compression >= FileInfo.LZW) is = new RandomAccessStream(is); return is; } } } | public static ArrayList[] imageSearch(String imageQuery, int startingIndex) { try { imageQuery = URLEncoder.encode(imageQuery, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String queryS = new String(); queryS += "http://images.google.com/images?gbv=1&start=" + startingIndex + "&q=" + imageQuery; String result = ""; try { URL query = new URL(queryS); HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); urlc.setInstanceFollowRedirects(true); urlc.setRequestProperty("User-Agent", ""); urlc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); StringBuffer response = new StringBuffer(); char[] buffer = new char[1024]; while (true) { int charsRead = in.read(buffer); if (charsRead == -1) { break; } response.append(buffer, 0, charsRead); } in.close(); result = response.toString(); } catch (Exception e) { e.printStackTrace(); } ArrayList<String> thumbs = new ArrayList<String>(); ArrayList<String> imgs = new ArrayList<String>(); Matcher m = imgBlock.matcher(result); while (m.find()) { String s = m.group(); Matcher imgM = imgurl.matcher(s); imgM.find(); String url = imgM.group(1); Matcher srcM = imgsrc.matcher(s); srcM.find(); String thumb = srcM.group(1); thumbs.add(thumb); imgs.add(url); } return new ArrayList[] { thumbs, imgs }; } | 874 |
1 | private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException { Stack sourceStack = new Stack(); Stack destinationStack = new Stack(); sourceStack.push(source); destinationStack.push(destination); while (!sourceStack.isEmpty()) { source = (File) sourceStack.pop(); destination = (File) destinationStack.pop(); if (!destination.exists()) destination.mkdirs(); File[] files = source.listFiles(); for (int i = 0; i < files.length; i++) { File current = (File) files[i]; if (current.isDirectory()) { sourceStack.push(current); destinationStack.push(new File(destination, current.getName())); } else if (current.getName().endsWith(".class")) { ClassWriter writer = new ClassWriter(); InputStream is = new BufferedInputStream(new FileInputStream(current)); writer.readClass(is); is.close(); if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) { ClassWriter[] auxWriter = new ClassWriter[1]; transformClass(writer, auxWriter); File output = new File(destination, current.getName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); writer.writeClass(os); os.close(); if (auxWriter[0] != null) { String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex()); className = className.substring(className.lastIndexOf('.') + 1, className.length()); output = new File(destination, className + ".class"); os = new BufferedOutputStream(new FileOutputStream(output)); auxWriter[0].writeClass(os); os.close(); } } } } } } | public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } | 875 |
1 | public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; } | public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } | 876 |
1 | private static byte[] finalizeStringHash(String loginHash) throws NoSuchAlgorithmException { MessageDigest md5Hasher; md5Hasher = MessageDigest.getInstance("MD5"); md5Hasher.update(loginHash.getBytes()); md5Hasher.update(LOGIN_FINAL_SALT); return md5Hasher.digest(); } | public static String createNormalizedJarDescriptorDigest(String path) throws Exception { String descriptor = createNormalizedDescriptor(new JarFile2(path)); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(descriptor.getBytes()); byte[] messageDigest = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } | 877 |
0 | public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; } | private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection con = null; if (proxyHost != null && !proxyHost.equals("")) { if (proxyAuthUser != null && !proxyAuthUser.equals("")) { log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType().equals(RequestorType.PROXY)) { return new PasswordAuthentication(proxyAuthUser, proxyAuthPassword.toCharArray()); } else { return null; } } }); } final Proxy proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort)); if (DEBUG) { log("Opening proxied connection(" + proxyHost + ":" + proxyPort + ")"); } con = (HttpURLConnection) new URL(url).openConnection(proxy); } else { con = (HttpURLConnection) new URL(url).openConnection(); } if (connectionTimeout > 0 && !isJDK14orEarlier) { con.setConnectTimeout(connectionTimeout); } if (readTimeout > 0 && !isJDK14orEarlier) { con.setReadTimeout(readTimeout); } return con; } | 878 |
0 | public Result search(Object object) { if (object == null || !(object instanceof String)) { return null; } String query = (String) object; Result hitResult = new Result(); Set<Hit> hits = new HashSet<Hit>(8); try { query = URLEncoder.encode(query, "UTF-8"); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); String line; StringBuilder builder = new StringBuilder(); InputStream input = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while ((line = reader.readLine()) != null) { builder.append(line); } input.close(); String response = builder.toString(); JSONObject json = new JSONObject(response); LOGGER.debug(json.getString("responseData")); int count = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount"); hitResult.setEstimatedCount(count); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); Hit hit = new Hit(); String result = j.getString("titleNoFormatting"); hit.setTitle(result == null || result.equals("") ? "${EMPTY}" : result); result = j.getString("url"); hit.setUrl(new URL(result)); hits.add(hit); } } catch (Exception e) { e.printStackTrace(); LOGGER.error("Something went wrong..." + e.getMessage()); } hitResult.setHits(hits); return hitResult; } | public void xtestFile1() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } | 879 |
0 | public void initGet() throws Exception { cl = new DefaultHttpClient(); GetAuthPromter hp = new GetAuthPromter(); cl.setCredentialsProvider(hp); get = new HttpGet(getURL()); get.setHeader("User-Agent", "test"); get.setHeader("Accept", "*/*"); get.setHeader("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); HttpResponse resp = cl.execute(get); ent = resp.getEntity(); setInputStream(ent.getContent()); } | public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); } | 880 |
0 | private void loadConfig(ServletContext ctx, String configFileName) { Digester digester = new Digester(); digester.push(this); digester.addFactoryCreate("pagespy/server", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetProperty("pagespy/server/param", "name", "value"); digester.addSetNext("pagespy/server", "setServer", PageSpyServer.class.getName()); digester.addCallMethod("pagespy/ignored-patterns", "setIgnorePattern", 1); digester.addCallParam("pagespy/ignored-patterns", 0); digester.addFactoryCreate("pagespy/property-setters/setter", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/property-setters/setter", "addPropertySetter", PagePropertySetter.class.getName()); digester.addFactoryCreate("pagespy/page-replacers/replacer", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/page-replacers/replacer", "addPageReplacer", PageReplacer.class.getName()); digester.addFactoryCreate("pagespy/properties-panel", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/properties-panel", "setPropertiesPanel", PagePanel.class.getName()); try { this.getLogger().info("Initializing " + configFileName); URL url = ctx.getResource(configFileName); if (url == null) { url = this.getClass().getResource(configFileName); } digester.parse(url.openStream()); } catch (Exception e) { this.getLogger().error("Error parsing configuration file.", e); throw new RuntimeException(e); } } | private boolean get(String surl, File dst, Get get) throws IOException { boolean ret = false; InputStream is = null; OutputStream os = null; try { try { if (surl.startsWith("file://")) { is = new FileInputStream(surl.substring(7)); } else { URL url = new URL(surl); is = url.openStream(); } if (is != null) { os = new FileOutputStream(dst); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } } catch (ConnectException ex) { log("Connect exception " + ex.getMessage(), ex, 3); if (dst.exists()) dst.delete(); } catch (UnknownHostException ex) { log("Unknown host " + ex.getMessage(), ex, 3); } catch (FileNotFoundException ex) { log("File not found: " + ex.getMessage(), 3); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } if (ret) { try { is = new FileInputStream(dst); os = new FileOutputStream(getCachedFile(get)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } | 881 |
1 | public static String compute(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nax) { RuntimeException rx = new IllegalStateException(); rx.initCause(rx); throw rx; } catch (UnsupportedEncodingException uex) { RuntimeException rx = new IllegalStateException(); rx.initCause(uex); throw rx; } } | public static synchronized String Encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception error) { throw new Exception(error.getMessage()); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (Exception e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | 882 |
0 | public static byte[] downloadHttpFile(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) throw new IOException("Invalid HTTP response: " + responseCode + " for url " + conn.getURL()); InputStream in = conn.getInputStream(); try { return Utilities.getInputBytes(in); } finally { in.close(); } } | public void sendMessageToServer(String msg, Map<String, String> args, StringCallback cb, URLConstructor ctor) { try { int tmpPort = port; for (; tmpPort < port + 10; tmpPort++) { Socket tmpSock; try { tmpSock = socketsManager.connect(new InetSocketAddress(host, port), 5000); tmpSock.close(); break; } catch (IOException e) { } } Map<String, String> newArgs = new HashMap<String, String>(args); newArgs.put("_f", String.valueOf(System.currentTimeMillis())); String request = ctor.constructURL(msg, newArgs); HttpClient client = new SimpleLimeHttpClient(); HttpGet get = new HttpGet("http://" + host + ":" + port + "/" + request); HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1); HttpResponse response = client.execute(get); String res = ""; if (response.getEntity() != null) { String result; if (response.getEntity() != null) { result = EntityUtils.toString(response.getEntity()); } else { result = null; } res = result; } cb.process(res); } catch (IOException e) { fail(e); } catch (HttpException e) { fail(e); } catch (URISyntaxException e) { fail(e); } catch (InterruptedException e) { fail(e); } } | 883 |
0 | private void announce(String trackerURL, byte[] hash, byte[] peerId, int port) { try { String strUrl = trackerURL + "?info_hash=" + URLEncoder.encode(new String(hash, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&peer_id=" + URLEncoder.encode(new String(peerId, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING).replaceAll("\\+", "%20") + "&port=" + port + "&uploaded=0&downloaded=0&left=0&numwant=50&no_peer_id=1&compact=1"; URL url = new URL(strUrl); URLConnection con = url.openConnection(); con.connect(); con.getContent(); } catch (Exception e) { e.printStackTrace(); } } | @Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; } | 884 |
1 | public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; } | public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } | 885 |
0 | public HttpResponse executeWithoutRewriting(HttpUriRequest request, HttpContext context) throws IOException { int code = -1; long start = SystemClock.elapsedRealtime(); try { HttpResponse response; mConnectionAllocated.set(null); if (NetworkStatsEntity.shouldLogNetworkStats()) { int uid = android.os.Process.myUid(); long startTx = NetStat.getUidTxBytes(uid); long startRx = NetStat.getUidRxBytes(uid); response = mClient.execute(request, context); HttpEntity origEntity = response == null ? null : response.getEntity(); if (origEntity != null) { long now = SystemClock.elapsedRealtime(); long elapsed = now - start; NetworkStatsEntity entity = new NetworkStatsEntity(origEntity, mAppName, uid, startTx, startRx, elapsed, now); response.setEntity(entity); } } else { response = mClient.execute(request, context); } code = response.getStatusLine().getStatusCode(); return response; } finally { try { long elapsed = SystemClock.elapsedRealtime() - start; ContentValues values = new ContentValues(); values.put(Checkin.Stats.COUNT, 1); values.put(Checkin.Stats.SUM, elapsed / 1000.0); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REQUEST + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); if (mConnectionAllocated.get() == null && code >= 0) { values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_REUSED + ":" + mAppName); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } String status = code < 0 ? "IOException" : Integer.toString(code); values.put(Checkin.Stats.TAG, Checkin.Stats.Tag.HTTP_STATUS + ":" + mAppName + ":" + status); mResolver.insert(Checkin.Stats.CONTENT_URI, values); } catch (Exception e) { Log.e(TAG, "Error recording stats", e); } } } | @Override public void setOntology1Document(URL url1) throws IllegalArgumentException { if (url1 == null) throw new IllegalArgumentException("Input parameter URL for ontology 1 is null."); try { ont1 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url1.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 1 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 1 from given URL."); } } | 886 |
1 | private void loadNumberFormats() { String fileToLocate = "/" + FILENAME_NUMBER_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new DecimalFormat(parts[1])); } } | private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; } | 887 |
0 | public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } } | private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } | 888 |
0 | public static Image getImage(String urlChartString) throws IOException, JGoogleChartException { Image image = null; HttpURLConnection urlConn = null; URL url = new URL(urlChartString); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("GET"); urlConn.setAllowUserInteraction(false); urlConn.setRequestProperty("HTTP-Version", "HTTP/1.1"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); int responseCode = urlConn.getResponseCode(); if (responseCode != 200) { throw new JGoogleChartException(JGoogleChartException.MSG_HTTP_ERROR_CODE + responseCode + " (" + urlConn.getResponseMessage()); } InputStream istream = urlConn.getInputStream(); image = ImageIO.read(istream); return image; } | private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); } | 889 |
0 | public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String limitsSet = ""; String synstatus = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS", "OFF"); String synncode = SystemFilesLoader.getInstance().getNewgenlibProperties().getProperty("SYNDETICS_CLIENT_CODE", ""); try { if (request.getSession().getAttribute("searchLimits") != null) { System.out.println("searchLimits set"); limitsSet = "SET"; java.util.Hashtable htLimits = new java.util.Hashtable(); htLimits = (java.util.Hashtable) request.getSession().getAttribute("searchLimits"); } else { limitsSet = "UNSET"; System.out.println("searchLimits not set"); } java.util.Properties prop = System.getProperties(); prop.load(new FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt")); System.out.println("SEARCH MODE IS " + searchmode + " FILE PATH " + ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "SystemFiles" + java.io.File.separator + "ENV_VAR.txt"); } catch (Exception e) { } javax.servlet.http.HttpSession session = request.getSession(); String forward = "searchView"; int link = 0, singleLink = 0; java.util.Vector vecThisPage = new java.util.Vector(); aportal.form.cataloguing.SearchViewForm svF = (aportal.form.cataloguing.SearchViewForm) form; svF.setSyndeticsStatus(synstatus); svF.setSyndeticsClientCode(synncode); opacHm = (ejb.bprocess.opac.xcql.OPACUtilitiesHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("OPACUtilities"); ejb.bprocess.opac.xcql.OPACUtilities opacUt = opacHm.create(); System.out.println("CLASS NO " + request.getParameter("ClassNo") + " ClassNoForwarded " + session.getAttribute("ClassNoForwarded")); if (svF.getExportRec() == null || !(svF.getExportRec().equals("export"))) { if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null && request.getParameter("relation") != null && !(session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").toString().equals("false"))) { home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue"); ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create(); String catId1 = request.getParameter("CatId"); String ownId1 = request.getParameter("OwnerId"); System.out.println("*********************CatId1: " + catId1); svF.setCatalogueRecordId(catId1); svF.setOwnerLibraryId(ownId1); String rel = request.getParameter("relation"); java.util.Vector vecL = searchCat.getRelatedCatalogueRecords(null, catId1, ownId1, rel); request.setAttribute("LuceneVector", vecL); session.setAttribute("searchVec", vecL); singleLink = 1; session.setAttribute("HostItemDisplay", "false"); link = 1; forward = "searchRes"; vecThisPage.addElement(catId1); vecThisPage.addElement(ownId1); } else if (link == 0 || singleLink == 1) { System.out.println("LINK AND SINGLE LINK " + link + " single " + singleLink); if ((request.getParameter("ClassNo") != null) && session.getAttribute("ClassNoForwarded") == null) { System.out.println("action called for class no."); String classificNo = request.getParameter("ClassNo"); System.out.println("TITLE WORDS "); home = (ejb.bprocess.opac.xcql.SearchSRUWCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchSRUWCatalogue"); ejb.bprocess.opac.xcql.SearchSRUWCatalogue searchCat = home.create(); String rawSearchText = (new beans.miscellaneous.RequestStringProcessor()).processString("*" + classificNo + "*"); System.out.println("raw search Text" + rawSearchText); String searchText = "classificationNumber=" + rawSearchText; System.out.println("search text is " + searchText); String xmlRes = (new org.z3950.zing.cql.CQLParser()).parse(searchText).toXCQL(0); java.util.Hashtable hs = new java.util.Hashtable(); java.util.Vector v1 = new java.util.Vector(); if (session.getAttribute("searchLimits") != null) { hs = (java.util.Hashtable) session.getAttribute("searchLimits"); } Vector vec = new Vector(); String solrQuery = Utility.getInstance().simplifiedSolrQuery(classificNo, "classificationNumber"); if (limitsSet.equalsIgnoreCase("SET")) { String limitsQuery = limitsSolrQuery(hs); solrQuery += limitsQuery; } solrQuery += " & "; Vector newRetvec = searchCat.processSolrQuery(1, 25, solrQuery, "245_Tag", "asc"); Hashtable ht = (Hashtable) newRetvec.get(0); String totrec = (String) ht.get("HITS"); session.setAttribute("TOTALREC", Integer.parseInt(totrec)); v1 = (Vector) ht.get("RESULTS"); hs.put("Query", solrQuery); if (v1.size() > 0) { hs.put("searchText", rawSearchText); hs.put("noOfRecords", 25); hs.put("browseType", "Classification Number"); session.setAttribute("searchEntry", hs); session.setAttribute("searchVec", v1); forward = "searchRes"; } else { forward = "home"; } } else { System.out.println("ELSE CALLED "); String record = request.getParameter("record"); String recNo = request.getParameter("recNo"); Integer catId = 0, ownerId = 0; String title = ""; if (request.getParameter("CatId") != null && request.getParameter("OwnerId") != null) { catId = new Integer(request.getParameter("CatId")).intValue(); ownerId = new Integer(request.getParameter("OwnerId")).intValue(); System.out.println("catId is +++=" + catId); System.out.println("OwnerId is +++=" + ownerId); title = request.getParameter("title"); svF.setCatalogueRecordId(request.getParameter("CatId")); svF.setOwnerLibraryId(request.getParameter("OwnerId")); } System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%VVVVVVVVVVVVVVVVVVVVVV"); ArrayList alOtherBooks = ((ejb.bprocess.opac.SearchCatalogue) ejb.bprocess.util.HomeFactory.getInstance().getHome("SearchCatalogue")).getOtherBooksInTheRack(null, catId.toString(), ownerId.toString(), ownerId.toString()); System.out.println("alOtherBooks size is " + alOtherBooks.size()); Vector vOtherBooks = new Vector(); Session catrecsession = DBConnector.getInstance().getSession(); utility = ejb.bprocess.util.Utility.getInstance(catrecsession); for (int i = 0; i < alOtherBooks.size(); i++) { String[] scData = (String[]) (alOtherBooks.get(i)); String catalogueId = scData[0]; String ownerLibId = scData[1]; System.out.println("catId is +++=" + catalogueId); System.out.println("OwnerId is +++=" + ownerLibId); String xmlWholeRecord = ""; String titleD = ""; String titleV = ""; String authorV = ""; String isbnNumber = ""; if (catalogueId != null && ownerLibId != null) { try { System.out.println("***************************** 0"); Hashtable htDetails = utility.getCatalogueRecord(new Integer(catalogueId), new Integer(ownerLibId)); System.out.println("***************************** 1"); if (htDetails != null && !htDetails.isEmpty()) { System.out.println("htDetails" + htDetails.toString()); titleV = utility.getTestedString(htDetails.get("Title")); authorV = utility.getTestedString(htDetails.get("Author")); isbnNumber = utility.getTestedString(htDetails.get("ISBN")); String[] str1 = titleV.split("/"); if (str1.length > 0) { titleD = str1[0]; if (titleD.length() > 45) { titleD = titleD.substring(0, 45) + "..."; } } String[] str = new String[5]; str[0] = titleD; str[1] = authorV; str[2] = isbnNumber; str[3] = catalogueId; str[4] = ownerLibId; vOtherBooks.add(str); System.out.println("Other Books size is " + vOtherBooks.size()); } } catch (Exception e) { e.printStackTrace(); } } } System.out.println("Other Books vector is *************************** \n "); for (int i = 0; i < vOtherBooks.size(); i++) { String[] str = (String[]) vOtherBooks.get(i); System.out.println("title :" + str[0].toString()); System.out.println("author :" + str[1].toString()); System.out.println("isbn :" + str[2].toString()); System.out.println("catID :" + str[3].toString()); System.out.println("ownerLibId :" + str[4].toString()); } System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); request.setAttribute("fisheyedata", vOtherBooks); catrecsession.close(); session.setAttribute("SingleViewExport", vecThisPage); if (session.getAttribute("OnlySingleRec") != null && session.getAttribute("OnlySingleRec").toString().equals("true")) { java.util.Vector v1 = new java.util.Vector(); System.out.println("SEARCH MODE " + searchmode); if (searchmode.equalsIgnoreCase("a")) { System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (IF) " + searchmode); v1 = (java.util.Vector) request.getAttribute("LuceneVector"); System.out.println("VECTOR V1 " + v1); } else { System.out.println("SEARCHMODE IN SEARCH VIEW ACTION (ELSE)" + searchmode); v1 = (java.util.Vector) session.getAttribute("searchVec"); } Object[] obj = (Object[]) v1.elementAt(0); String str[] = (String[]) obj[0]; java.util.Hashtable h = new java.util.Hashtable(); String tit = ""; h = (java.util.Hashtable) obj[1]; System.out.println("HASH TABLE in view action " + h); catId = new Integer(str[0]).intValue(); ownerId = new Integer(str[1]).intValue(); title = h.get("TITLE").toString(); svF.setAttachmentsAndUrl(""); if ((h.get("ATTACHMENTS") != null && h.get("ATTACHMENTS").equals("AVAILABLE"))) { svF.setAttachmentsAndUrl("available"); } record = "full"; recNo = "1"; session.removeAttribute("OnlySingleRec"); } if (session.getAttribute("HostItemDisplay") != null && session.getAttribute("HostItemDisplay").equals("false")) { session.removeAttribute("HostItemDisplay"); } session.setAttribute("Title", title); java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(catId, ownerId); vecThisPage.addElement(String.valueOf(catId)); vecThisPage.addElement(String.valueOf(ownerId)); svF.setAttachmentsAndUrl(""); if (hash1.get("ATTACHMENTS") != null && hash1.get("ATTACHMENTS").toString().equals("AVAILABLE")) { svF.setAttachmentsAndUrl("available"); } svF.setRecordNo(recNo); session.setAttribute("record", record); java.util.Vector vecCO = (java.util.Vector) session.getAttribute("CatAndOwner"); svF.setCatCur(catId); svF.setOwnerCur(ownerId); svF.setPrevExists("no"); svF.setNextExists("no"); if (vecCO != null) { for (int j = 0; j < vecCO.size(); j = j + 4) { int c = new Integer(vecCO.elementAt(j).toString()).intValue(); int o = new Integer(vecCO.elementAt(j + 1).toString()).intValue(); if (c == catId && o == ownerId) { if (j != 0) { int catPrev = new Integer(vecCO.elementAt(j - 4).toString()).intValue(); int ownerPrev = new Integer(vecCO.elementAt(j - 3).toString()).intValue(); svF.setCatPrev(catPrev); svF.setOwnerPrev(ownerPrev); svF.setTitlePrev(vecCO.elementAt(j - 2).toString()); svF.setRecPrev(vecCO.elementAt(j - 1).toString()); svF.setPrevExists("yes"); } if (j < vecCO.size() - 4) { int catNext = new Integer(vecCO.elementAt(j + 4).toString()).intValue(); int ownerNext = new Integer(vecCO.elementAt(j + 5).toString()).intValue(); svF.setCatNext(catNext); svF.setOwnerNext(ownerNext); svF.setTitleNext(vecCO.elementAt(j + 6).toString()); svF.setRecNext(vecCO.elementAt(j + 7).toString()); svF.setNextExists("yes"); } } } } String str[] = (String[]) hash1.get("Biblo_Mat"); int bib_id = new Integer(str[0]).intValue(); int mat_id = new Integer(str[1]).intValue(); aportal.view.RecordView rv = new aportal.view.DesignFactory().getCorView(bib_id, mat_id, record); String type = ""; if (bib_id == 3 && mat_id == 1) { type = "Book"; } else if (bib_id == 4 && mat_id == 1) { type = "Serial"; } else if (bib_id == 1 && mat_id == 1) { type = "Book Chapter"; } else if (bib_id == 2 && mat_id == 1) { type = "Serial Article"; } else { type = ejb.bprocess.util.TypeDefinition.getInstance().getTypeDefinition(String.valueOf(bib_id), String.valueOf(mat_id)); } java.util.Hashtable hMono = (java.util.Hashtable) hash1.get("MonoGraphRecords"); java.util.Hashtable h4 = rv.getView(hash1); h4.put("Type", type); Hashtable ht = (Hashtable) h4.get("NoLink"); if (ht != null && ht.get("URLS_856") != null) { Vector urls856 = (Vector) ht.get("URLS_856"); if (urls856.size() > 0) { Hashtable linksAndText = new Hashtable(); Hashtable url856 = new Hashtable(); for (int i = 0; i < urls856.size(); i += 2) { url856.put(urls856.elementAt(i), urls856.elementAt(i + 1)); } linksAndText.put("URL", url856); h4.put("URLS_856", linksAndText); } } try { String sessionid = request.getSession().getId(); ejb.bprocess.holdings.HoldingsStatement holdingsStatement = ((ejb.bprocess.holdings.HoldingsStatementHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("HoldingsStatement")).create(); java.util.Vector vecLib = new java.util.Vector(); vecLib.addElement("1"); if (session.getAttribute("Libraries") != null) { vecLib = (java.util.Vector) session.getAttribute("Libraries"); } String libIds = ""; for (int p = 0; p < vecLib.size(); p++) { if (p != 0) { libIds += ","; } String libName = vecLib.elementAt(p).toString(); Session session1 = DBConnector.getInstance().getSession(); libIds += ejb.bprocess.util.Utility.getInstance(session1).getLibraryId(libName); session1.close(); } request.setAttribute("catRecId", String.valueOf(catId)); request.setAttribute("ownLibId", String.valueOf(ownerId)); request.setAttribute("libIds", String.valueOf(libIds)); Hashtable onerecordattach = new Hashtable(); JSONObject jsonCatOwnId = new JSONObject().put("Id", catId).put("LibId", ownerId); ejb.bprocess.opac.SearchCatalogue searchCatAttach = ((ejb.bprocess.opac.SearchCatalogueHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("SearchCatalogue")).create(); String strAttach = searchCatAttach.getAttachmentDetails(jsonCatOwnId.toString()); if (!strAttach.equals("")) { JSONObject jsonAttach = new JSONObject(strAttach); if (jsonAttach != null) { if (!jsonAttach.isNull("BookCover")) { ArrayList albookcover = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("BookCover"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { albookcover.add(jsonarr.getString(j)); } onerecordattach.put("BookCover", albookcover); } } if (!jsonAttach.isNull("TOC")) { ArrayList alTOC = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("TOC"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alTOC.add(jsonarr.getString(j)); } onerecordattach.put("TOC", alTOC); } } if (!jsonAttach.isNull("Preview")) { ArrayList alPreview = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("Preview"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alPreview.add(jsonarr.getString(j)); } onerecordattach.put("Preview", alPreview); } } if (!jsonAttach.isNull("FullView")) { ArrayList alFullView = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("FullView"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alFullView.add(jsonarr.getString(j)); } onerecordattach.put("FullView", alFullView); } } if (!jsonAttach.isNull("Attachment")) { ArrayList alAttachment = new ArrayList(); JSONArray jsonarr = (JSONArray) jsonAttach.get("Attachment"); if (jsonarr != null) { for (int j = 0; j < jsonarr.length(); j++) { alAttachment.add(jsonarr.getString(j)); } onerecordattach.put("Attachment", alAttachment); } } if (onerecordattach != null && !onerecordattach.isEmpty()) { h4.put("dAttachment", onerecordattach); } } } svF.setHashSing(h4); System.out.println("hash tabel values*************************"); Enumeration enumx = h4.keys(); while (enumx.hasMoreElements()) { String key = enumx.nextElement().toString(); System.out.println("Key: " + key + "-----value: " + h4.get(key)); } System.out.println("********************************************"); } catch (Exception e) { e.printStackTrace(); } } } } else if (svF.getExportRec() != null && svF.getExportRec().equals("export")) { svF.setExportRec(null); vecThisPage = (java.util.Vector) session.getAttribute("SingleViewExport"); String format = svF.getSf(); if (format.equals("marc")) { String marc = opacUt.getDetailsForMultiRecordViewMARC(vecThisPage); svF.setDisplayFormat(marc); session.setAttribute("RecordDisplay", marc); forward = "RecordFormat"; } else if (format.equals("marcXml")) { String marcXML = opacUt.getDetailsForMultiRecordViewMARCXML(vecThisPage); svF.setDisplayFormat(marcXML); response.setContentType("text/xml"); session.setAttribute("RecordDisplay", marcXML); forward = "RecordFormat"; } else if (format.equals("mods")) { String mods = opacUt.getDetailsForMultiRecordViewMODS(vecThisPage); svF.setDisplayFormat(mods); session.setAttribute("RecordDisplay", mods); forward = "RecordFormat"; } else if (format.equals("dc")) { String dc = opacUt.getDetailsForMultiRecordViewDublinCore(vecThisPage); svF.setDisplayFormat(dc); session.setAttribute("RecordDisplay", dc); forward = "RecordFormat"; } else if (format.equals("agris")) { String agr = opacUt.getDetailsForMultiRecordViewAgris(vecThisPage); svF.setDisplayFormat(agr); session.setAttribute("RecordDisplay", agr); forward = "RecordFormat"; } else if (format.equals("text")) { java.util.Vector vecTextDis = new java.util.Vector(); for (int i2 = 0; i2 < vecThisPage.size(); i2 = i2 + 2) { java.util.Hashtable hash1 = opacUt.getDetailsForSingleCatalogueRecord(new Integer(vecThisPage.elementAt(i2).toString()).intValue(), new Integer(vecThisPage.elementAt(i2 + 1).toString()).intValue()); aportal.view.ISBDView fullView = new aportal.view.ISBDView(); java.util.Hashtable hashCit = fullView.getView(hash1); vecTextDis.addElement(hashCit); forward = "RecordFormatText"; } session.setAttribute("RecordTextDisplay", vecTextDis); if (svF.getPs() != null && svF.getPs().equals("email")) { boolean flag = false; if (svF.getEmail() != null && !(svF.getEmail().equals(""))) { String emailId = svF.getEmail(); try { String sessionid = request.getSession().getId(); java.net.URL url = new java.net.URL("http://localhost:" + request.getServerPort() + "/newgenlibctxt/jsp/aportal/cataloguing/RecordDisplayText.jsp;jsessionid=" + sessionid); java.net.URLConnection urlCon = url.openConnection(); java.io.InputStream is = urlCon.getInputStream(); String htmlContent = ""; java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(is)); String line = ""; while ((line = br.readLine()) != null) { htmlContent = htmlContent + line; } String[] emailids = { emailId }; int status = SendEmail.getInstance().sendMail(emailids, "OPAC results", htmlContent, "html"); if (status == 0) flag = true; else flag = false; } catch (Exception exp) { exp.printStackTrace(); } } String mailMessage = "The selected records have been successfully mailed to " + svF.getEmail(); if (flag == false) { mailMessage = "<h4><p>The selected records could not be mailed to " + svF.getEmail() + " These might be the possible reasons.</p></h4>" + "<h5><ol> <li>The email id entered is not a valid one</font></li>" + "<li>The email id domain might not be in the list of allowed recipient hosts</li>" + "<li>There might a error in connectivity to the mail server</li></ol></h5>" + "<h4><p>Please contact the Network Administrator </p></h4>"; } session.setAttribute("MailStatus", mailMessage); forward = "SendEmail"; } } } String version = ejb.bprocess.util.StaticValues.getInstance().getVersion(); if (version != null && !version.equals("")) { svF.setVersion(version); } if (session.getAttribute("ClassNoForwarded") != null) { session.removeAttribute("ClassNoForwarded"); } return mapping.findForward(forward); } | 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); } } | 890 |
1 | protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; } | private static void loadFromZip() { InputStream in = Resources.class.getResourceAsStream("data.zip"); if (in == null) { return; } ZipInputStream zipIn = new ZipInputStream(in); try { while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String entryName = entry.getName(); if (!entryName.startsWith("/")) { entryName = "/" + entryName; } ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(zipIn, out); zipIn.closeEntry(); FILES.put(entryName, out.toByteArray()); } zipIn.close(); } catch (IOException e) { e.printStackTrace(); } } | 891 |
0 | public static void copyFile1(File srcFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); fis.close(); fos.close(); } | InputStream openURL(URL url) throws IOException, WrongMIMETypeException { InputStream is = null; if (url.getProtocol().equals("file")) { if (debug) { System.out.println("Using direct input stream on file url"); } URLConnection urlc = url.openConnection(); try { urlc.connect(); is = new DataInputStream(urlc.getInputStream()); } catch (FileNotFoundException e) { } } else { double start = 0; if (timing) { start = Time.getNow(); } ContentNegotiator cn = null; cn = new ContentNegotiator(url); Object obj = null; obj = cn.getContent(); if (obj != null) { byte[] buf = (byte[]) obj; is = new ByteArrayInputStream(buf); } else { System.err.println("Loader.openURL got null content"); throw new IOException("Loader.openURL got null content"); } if (timing) { double elapsed = Time.getNow() - start; System.out.println("Loader: open and buffer URL in: " + numFormat.format(elapsed, 2) + " seconds"); } } return is; } | 892 |
0 | public JarClassLoader(ClassLoader parent) { super(parent); initLogger(); hmClass = new HashMap<String, Class<?>>(); lstJarFile = new ArrayList<JarFileInfo>(); hsDeleteOnExit = new HashSet<File>(); String sUrlTopJar = null; pd = getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL urlTopJar = cs.getLocation(); String protocol = urlTopJar.getProtocol(); JarFileInfo jarFileInfo = null; if ("http".equals(protocol) || "https".equals(protocol)) { try { urlTopJar = new URL("jar:" + urlTopJar + "!/"); JarURLConnection jarCon = (JarURLConnection) urlTopJar.openConnection(); JarFile jarFile = jarCon.getJarFile(); jarFileInfo = new JarFileInfo(jarFile, jarFile.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", urlTopJar, protocol); } catch (Exception e) { logError(LogArea.JAR, "Failure to load HTTP JAR: %s %s", urlTopJar, e.toString()); return; } } if ("file".equals(protocol)) { try { sUrlTopJar = URLDecoder.decode(urlTopJar.getFile(), "UTF-8"); } catch (UnsupportedEncodingException e) { logError(LogArea.JAR, "Failure to decode URL: %s %s", urlTopJar, e.toString()); return; } File fileJar = new File(sUrlTopJar); if (fileJar.isDirectory()) { logInfo(LogArea.JAR, "Loading from exploded directory: %s", sUrlTopJar); return; } try { jarFileInfo = new JarFileInfo(new JarFile(fileJar), fileJar.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", sUrlTopJar, protocol); } catch (IOException e) { logError(LogArea.JAR, "Not a JAR: %s %s", sUrlTopJar, e.toString()); return; } } try { if (jarFileInfo == null) { throw new IOException(String.format("Unknown protocol %s", protocol)); } loadJar(jarFileInfo); } catch (IOException e) { logError(LogArea.JAR, "Not valid URL: %s %s", urlTopJar, e.toString()); return; } checkShading(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { shutdown(); } }); } | private GenomicSequence fetch(Chromosome k, int start, int end) throws IOException { try { String chr = k.toString(); if (chr.toLowerCase().startsWith("chr")) chr = chr.substring(3); SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(false); f.setValidating(false); SAXParser parser = f.newSAXParser(); URL url = new URL("http://genome.ucsc.edu/cgi-bin/das/" + genomeVersion + "/dna?segment=" + URLEncoder.encode(chr, "UTF-8") + ":" + (start + 1) + "," + (end)); DASHandler handler = new DASHandler(); InputStream in = url.openStream(); parser.parse(in, handler); in.close(); GenomicSequence seq = new GenomicSequence(); seq.sequence = handler.bytes.toByteArray(); seq.start = start; seq.end = end; if (seq.sequence.length != seq.length()) throw new IOException("bad bound " + seq + " " + seq.sequence.length + " " + seq.length()); return seq; } catch (IOException err) { throw err; } catch (Exception e) { throw new IOException(e); } } | 893 |
1 | @Override public void doExecute(String[] args) { if (args.length != 2) { printUsage(); } else { int fileNo = 0; try { fileNo = Integer.parseInt(args[1]) - 1; } catch (NumberFormatException e) { printUsage(); return; } if (fileNo < 0) { printUsage(); return; } StorageFile[] files = (StorageFile[]) ctx.getRemoteDir().listFiles(); try { StorageFile file = files[fileNo]; File outFile = getOutFile(file); FileOutputStream out = new FileOutputStream(outFile); InputStream in = file.openStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(out); afterSave(outFile); if (outFile.exists()) { print("File written to: " + outFile.getAbsolutePath()); } } catch (IOException e) { printError("Failed to load file. " + e.getMessage()); } catch (Exception e) { printUsage(); return; } } } | private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } | 894 |
1 | protected Object getMethodKey(String methodName, Object[] args) { StringBuffer key = new StringBuffer(methodName.trim().replace(" ", ".")).append("."); for (Object o : args) { if (o != null) key.append(o.hashCode()); } LOGGER.info("Generation key ->" + key.toString()); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); messageDigest.reset(); messageDigest.update(key.toString().getBytes(Charset.forName("UTF8"))); final byte[] resultByte = messageDigest.digest(); String hex = null; for (int i = 0; i < resultByte.length; i++) { hex = Integer.toHexString(0xFF & resultByte[i]); if (hex.length() < 2) { key.append("0"); } key.append(hex); } } catch (NoSuchAlgorithmException e) { LOGGER.severe("No hash generated for method key! " + StackTraceUtil.getStackTrace(e)); } LOGGER.info("Generation key ->" + key.toString()); return new String(key); } | PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); } | 895 |
0 | @Test public void test_lookupResourceType_FullSearch_TwoWords() throws Exception { URL url = new URL(baseUrl + "/lookupResourceType/alloyed+tritanium"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("[{\"itemTypeID\":25595,\"itemCategoryID\":4,\"name\":\"Alloyed Tritanium Bar\",\"icon\":\"69_11\"}]")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); } | @Override public Response executeGet(String url) throws IOException { if (logger.isLoggable(INFO)) logger.info("Making a GET request to " + url); HttpURLConnection httpUrlConnection = null; InputStream inputStream = null; try { httpUrlConnection = openConnection(new URL(url)); httpUrlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_IN_MS); httpUrlConnection.setUseCaches(false); customizeConnection(httpUrlConnection); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.connect(); if (logger.isLoggable(FINER)) logger.finer("Response headers: " + httpUrlConnection.getHeaderFields()); try { inputStream = httpUrlConnection.getResponseCode() != HTTP_OK ? httpUrlConnection.getErrorStream() : httpUrlConnection.getInputStream(); } catch (IOException e) { if (logger.isLoggable(WARNING)) logger.warning("An error occurred while making a GET request to " + url + ": " + e); } return new Response(httpUrlConnection.getResponseCode(), fromInputStream(inputStream)); } finally { closeQuietly(httpUrlConnection); } } | 896 |
1 | public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.setVisible(true); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.setVisible(true); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } } | public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } } | 897 |
1 | public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } } | public static byte[] encode(String origin, String algorithm) throws NoSuchAlgorithmException { String resultStr = null; resultStr = new String(origin); MessageDigest md = MessageDigest.getInstance(algorithm); md.update(resultStr.getBytes()); return md.digest(); } | 898 |
1 | public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; } | 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"); } | 899 |