label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| Code Sample 1:
public String[] fetchAutocomplete(String text) { String[] result = new String[0]; String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.autocomplete.url", text); HttpContext context = new BasicHttpContext(); HttpGet method = new HttpGet(url); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity).split("\n"); EntityUtils.consume(entity); } } catch (Exception ex) { result = new String[0]; } finally { method.abort(); } return result; }
Code Sample 2:
@Override protected String doInBackground(Void... params) { try { HttpGet request = new HttpGet(UPDATE_URL); request.setHeader("Accept", "text/plain"); HttpResponse response = MyMovies.getHttpClient().execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return "Error: Failed getting update notes"; } return EntityUtils.toString(response.getEntity()); } catch (Exception e) { return "Error: " + e.getMessage(); } } |
11
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void installBinaryFile(File source, File destination) { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { } catch (IOException e) { new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } |
00
| Code Sample 1:
private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal) throws IOException { if (httpPrincipal == null || httpPrincipal.getUrl() == null) { return null; } URL url = null; if ((httpPrincipal.getUserId() <= 0) || (httpPrincipal.getPassword() == null)) { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/liferay/do"); } else { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/secure/liferay/do"); } HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); urlc.setRequestMethod("POST"); if ((httpPrincipal.getUserId() > 0) && (httpPrincipal.getPassword() != null)) { String userNameAndPassword = httpPrincipal.getUserId() + ":" + httpPrincipal.getPassword(); urlc.setRequestProperty("Authorization", "Basic " + Base64.encode(userNameAndPassword.getBytes())); } return urlc; }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } 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(); } } |
00
| Code Sample 1:
public void GetFile(ClientConnector cc, Map<String, String> attributes) throws Exception { log.debug("Starting FTP FilePull"); String sourceNode = attributes.get("src_name"); String sourceUser = attributes.get("src_user"); String sourcePassword = attributes.get("src_password"); String sourceFile = attributes.get("src_file"); String messageID = attributes.get("messageID"); String sourceMD5 = attributes.get("src_md5"); String sourceFileType = attributes.get("src_file_type"); Integer sourcePort = 21; String sourcePortString = attributes.get("src_port"); if ((sourcePortString != null) && (sourcePortString.equals(""))) { try { sourcePort = Integer.parseInt(sourcePortString); } catch (Exception e) { sourcePort = 21; log.debug("Destination Port \"" + sourcePortString + "\" was not valid. Using Default (21)"); } } log.info("Starting FTP pull of \"" + sourceFile + "\" from \"" + sourceNode); if ((sourceUser == null) || (sourceUser.equals(""))) { List userDBVal = axt.db.GeneralDAO.getNodeValue(sourceNode, "ftpUser"); if (userDBVal.size() < 1) { sourceUser = DEFAULTUSER; } else { sourceUser = (String) userDBVal.get(0); } } if ((sourcePassword == null) || (sourcePassword.equals(""))) { List passwordDBVal = axt.db.GeneralDAO.getNodeValue(sourceNode, "ftpPassword"); if (passwordDBVal.size() < 1) { sourcePassword = DEFAULTPASSWORD; } else { sourcePassword = (String) passwordDBVal.get(0); } } String stageFile = null; int stageFileID; try { stageFileID = axt.db.GeneralDAO.getStageFile(messageID); stageFile = STAGINGDIR + "/" + stageFileID; } catch (Exception e) { throw new Exception("Failed to assign a staging file \"" + stageFile + "\" - ERROR: " + e); } FileOutputStream fos; try { fos = new FileOutputStream(stageFile); } catch (FileNotFoundException fileNFException) { throw new Exception("Failed to assign the staging file \"" + stageFile + "\" - ERROR: " + fileNFException); } FTPClient ftp = new FTPClient(); try { log.debug("Connecting"); ftp.connect(sourceNode, sourcePort); log.debug("Checking Status"); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + sourceNode + "\" as user \"" + sourceUser + "\" - ERROR: " + ftp.getReplyString()); } log.debug("Logging In"); if (!ftp.login(sourceUser, sourcePassword)) { ftp.disconnect(); throw new Exception("Failed to connect to \"" + sourceNode + "\" as user \"" + sourceUser + "\" - ERROR: Login Failed"); } } catch (SocketException socketException) { throw new Exception("Failed to connect to \"" + sourceNode + "\" as user \"" + sourceUser + "\" - ERROR: " + socketException); } catch (IOException ioe) { throw new Exception("Failed to connect to \"" + sourceNode + "\" as user \"" + sourceUser + "\" - ERROR: " + ioe); } log.debug("Performing Site Commands"); Iterator siteIterator = GeneralDAO.getNodeValue(sourceNode, "ftpSite").iterator(); while (siteIterator.hasNext()) { String siteCommand = null; try { siteCommand = (String) siteIterator.next(); ftp.site(siteCommand); } catch (IOException e) { throw new Exception("FTP \"site\" command \"" + siteCommand + "\" failed - ERROR: " + e); } } if (sourceFileType != null) { if (sourceFileType.equals("A")) { log.debug("Set File Type to ASCII"); ftp.setFileType(FTP.ASCII_FILE_TYPE); } else if (sourceFileType.equals("B")) { log.debug("Set File Type to BINARY"); ftp.setFileType(FTP.BINARY_FILE_TYPE); } else if (sourceFileType.equals("E")) { log.debug("Set File Type to EBCDIC"); ftp.setFileType(FTP.EBCDIC_FILE_TYPE); } } log.debug("Opening the File Stream"); InputStream in = null; try { in = ftp.retrieveFileStream(sourceFile); if (in == null) { throw new Exception("Failed get the file \"" + sourceFile + "\" from \"" + sourceNode + "\" - ERROR: " + ftp.getReplyString()); } } catch (IOException ioe2) { ftp.disconnect(); log.error("Failed get the file \"" + sourceFile + "\" from \"" + sourceNode + "\" - ERROR: " + ioe2); throw new Exception("Failed to retrieve file from \"" + sourceNode + "\" as user \"" + sourceUser + "\" - ERROR: " + ioe2); } log.debug("Starting the read"); DESCrypt encrypter = null; try { encrypter = new DESCrypt(); } catch (Exception cryptInitError) { log.error("Failed to initialize the encrypt process - ERROR: " + cryptInitError); } String receivedMD5 = null; try { Object[] returnValues = encrypter.encrypt(in, fos); receivedMD5 = (String) returnValues[0]; GeneralDAO.setStageFileSize(stageFileID, (Long) returnValues[1]); } catch (Exception cryptError) { log.error("Encrypt Error: " + cryptError); throw new Exception("Encrypt Error: " + cryptError); } log.debug("Logging Out"); try { ftp.logout(); fos.close(); } catch (Exception ioe3) { log.error("Failed close connection to \"" + sourceNode + "\" - ERROR: " + ioe3); } log.debug("Setting the File Digest"); GeneralDAO.setStageFileDigest(stageFileID, receivedMD5); if ((sourceMD5 != null) && (!sourceMD5.equals(""))) { log.debug("File DIGEST compare - Source: " + sourceMD5.toLowerCase() + " | Received: " + receivedMD5); if (!receivedMD5.equals(sourceMD5.toLowerCase())) { throw new Exception("MD5 validation on file failed."); } } return; }
Code Sample 2:
public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } |
11
| Code Sample 1:
protected static List<Pattern> getBotPatterns() { List<Pattern> patterns = new ArrayList<Pattern>(); try { Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { Pattern pattern = Pattern.compile(line); patterns.add(pattern); } } in.close(); } } catch (IOException e) { throw new RuntimeException("Error reading bot user-agent configuration", e); } return patterns; }
Code Sample 2:
public ArrayList loadIndexes() { JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "1").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("MobileIndexes"); for (int i = 0; i < jarr.length(); i++) { String indexname = jarr.getString(i); al.add(indexname); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } return al; } |
11
| Code Sample 1:
public static boolean insert(final CelulaFinanceira objCelulaFinanceira) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setString(1, objCelulaFinanceira.getDescricao()); pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo()); pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo()); pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo()); pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo()); pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo()); pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo()); pst.setDouble(8, objCelulaFinanceira.getValorProvisionado()); pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto()); pst.setDouble(10, objCelulaFinanceira.getGastoReal()); pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto()); pst.setDouble(12, objCelulaFinanceira.getSaldoReal()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public void testBlobB() { ResultSet rs; byte[] ba; byte[] baR1 = new byte[] { (byte) 0xF1, (byte) 0xF2, (byte) 0xF3, (byte) 0xF4, (byte) 0xF5, (byte) 0xF6, (byte) 0xF7, (byte) 0xF8, (byte) 0xF9, (byte) 0xFA, (byte) 0xFB }; byte[] baR2 = new byte[] { (byte) 0xE1, (byte) 0xE2, (byte) 0xE3, (byte) 0xE4, (byte) 0xE5, (byte) 0xE6, (byte) 0xE7, (byte) 0xE8, (byte) 0xE9, (byte) 0xEA, (byte) 0xEB }; try { connection.setAutoCommit(false); Statement st = connection.createStatement(); st.executeUpdate("DROP TABLE blo IF EXISTS"); st.executeUpdate("CREATE TABLE blo (id INTEGER, b blob( 100))"); PreparedStatement ps = connection.prepareStatement("INSERT INTO blo(id, b) values(2, ?)"); ps.setBlob(1, new SerialBlob(baR1)); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } java.sql.Blob blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); byte[] baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); ba = blob1.getBytes(1, baR2.length); if (ba.length != baR2.length) { assertTrue("row2 byte length differs", false); } for (int i = 0; i < ba.length; i++) { if (ba[i] != baR1[i]) { assertTrue("row2 byte " + i + " differs", false); } } rs.close(); connection.rollback(); ps.setBinaryStream(1, new HsqlByteArrayInputStream(baR1), baR1.length); ps.executeUpdate(); rs = st.executeQuery("SELECT b FROM blo WHERE id = 2"); if (!rs.next()) { assertTrue("No row with id 2", false); } blob1 = rs.getBlob("b"); System.out.println("Size of retrieved blob: " + blob1.length()); baOut = blob1.getBytes(1, (int) blob1.length()); if (baOut.length != baR1.length) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } for (int i = 0; i < baOut.length; i++) { if (baOut[i] != baR1[i]) { assertTrue("Expected array len " + baR1.length + ", got len " + baOut.length, false); } } rs.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); fail("test failure"); } } |
11
| Code Sample 1:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } } |
11
| Code Sample 1:
private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
Code Sample 2:
private boolean postCorrecao() { boolean valido = false; Integer newCodCorrecao = null; String sqlmaxac = "SELECT MAX(SEQAC) FROM PPOPACAOCORRET WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; String sqlmaxcq = "SELECT MAX(SEQOPCQ) + 1 FROM PPOPCQ WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?"; try { for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { valido = true; keysItens[2] = ek.getKey(); break; } } if (!valido) { Funcoes.mensagemInforma(this, "Selecione as analises para aplicar a corre��o!"); return false; } if (txaCausa.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Informe as causas!"); return false; } if (txaAcao.getVlrString().trim().length() == 0) { Funcoes.mensagemInforma(this, "Detalhe a a��o corretiva!"); return false; } PreparedStatement ps = con.prepareStatement(sqlmaxac); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ResultSet rs = ps.executeQuery(); if (rs.next()) { newCodCorrecao = rs.getInt(1) + 1; keysItens[3] = newCodCorrecao; } rs.close(); ps.close(); if (newCodCorrecao != null) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO PPOPACAOCORRET "); sql.append("( CODEMP, CODFILIAL, CODOP, SEQOP, SEQAC, TPCAUSA, OBSCAUSA, TPACAO, OBSACAO ) "); sql.append("VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, newCodCorrecao); ps.setString(6, m.getCode()); ps.setString(7, txaCausa.getVlrString()); ps.setString(8, rgSolucao.getVlrString()); ps.setString(9, txaAcao.getVlrString()); ps.execute(); ps.close(); String strAnalises = ""; for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) { JCheckBoxPad cb = ek.getValue(); if ("S".equals(cb.getVlrString())) { if (strAnalises.trim().length() > 0) { strAnalises += ","; } strAnalises += String.valueOf(ek.getKey()); } } sql = new StringBuilder(); sql.append("UPDATE PPOPCQ SET SEQAC=? "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); ps = con.prepareStatement(sql.toString()); ps.setInt(1, newCodCorrecao); ps.setInt(2, Aplicativo.iCodEmp); ps.setInt(3, ListaCampos.getMasterFilial("PPOPACAOCORRET")); ps.setInt(4, txtCodOP.getVlrInteger()); ps.setInt(5, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); sql.delete(0, sql.length()); sql.append("INSERT INTO PPOPCQ (CODEMP,CODFILIAL,CODOP,SEQOP,SEQOPCQ,"); sql.append("CODEMPEA,CODFILIALEA,CODESTANALISE) "); sql.append("SELECT CODEMP,CODFILIAL,CODOP,SEQOP,("); sql.append(sqlmaxcq); sql.append("),CODEMPEA,CODFILIALEA,CODESTANALISE "); sql.append("FROM PPOPCQ "); sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND "); sql.append("SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )"); System.out.println(sql.toString()); ps = con.prepareStatement(sql.toString()); ps = con.prepareStatement(sql.toString()); ps.setInt(1, Aplicativo.iCodEmp); ps.setInt(2, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(3, txtCodOP.getVlrInteger()); ps.setInt(4, txtSeqOP.getVlrInteger()); ps.setInt(5, Aplicativo.iCodEmp); ps.setInt(6, ListaCampos.getMasterFilial("PPOPCQ")); ps.setInt(7, txtCodOP.getVlrInteger()); ps.setInt(8, txtSeqOP.getVlrInteger()); ps.executeUpdate(); ps.close(); montaAnalises(); Funcoes.mensagemInforma(this, "A��o corretiva aplicada com sucesso!"); } con.commit(); } catch (Exception err) { try { con.rollback(); } catch (SQLException e) { System.out.println("Erro ao realizar rollback!\n" + err.getMessage()); } err.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao atualizar analises!\n" + err.getMessage(), true, con, err); valido = false; } return valido; } |
00
| Code Sample 1:
protected TaobaoResponse _fetch(HttpPost post, Map<String, CharSequence> payload, File file) throws IOException { Set<Entry<String, CharSequence>> entries = payload.entrySet(); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Entry<String, CharSequence> entry : entries) { NameValuePair nvp = new BasicNameValuePair(entry.getKey(), (String) entry.getValue()); nvps.add(nvp); } if (file != null) { } else { post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } if (this.keepAlive) { post.setHeader("Connection", "Keep-Alive"); } Header responseHeader = null; HttpResponse response = httpClient.execute(post); responseHeader = post.getLastHeader("sip_status"); String body = EntityUtils.toString(response.getEntity()); TaobaoResponse urlRsp = new TaobaoResponse(); if (responseHeader != null) { String status = responseHeader.getValue(); if (!SIP_STATUS_OK.equals(status)) { urlRsp.setErrorCode(status); urlRsp.setMsg(post.getLastHeader("sip_error_message").getValue()); if (status.equals("1004")) { urlRsp.setRedirectUrl(post.getLastHeader("sip_isp_loginurl").getValue()); } } } urlRsp.setBody(body); return urlRsp; }
Code Sample 2:
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); } } |
00
| Code Sample 1:
public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }
Code Sample 2:
private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); } |
00
| Code Sample 1:
private void initializeTree() { InputStreamReader reader = null; BufferedReader buffReader = null; try { for (int i = 0; i < ORDER.length; i++) { int index = ORDER[i]; String indexName = index < 10 ? "0" + index : (index > 20 ? "big" : "" + index); URL url = EmptyClass.class.getResource("engchar" + indexName + ".dic"); logger.info("... Loading: " + "engchar" + indexName + ".dic = {" + url + "}"); reader = new InputStreamReader(url.openStream()); buffReader = new BufferedReader(reader); String line = null; String word = null; do { line = buffReader.readLine(); if (line != null) { boolean plural = line.endsWith("/S"); boolean forbidden = line.endsWith("/X"); if (plural) { int stringIndex = line.indexOf("/S"); word = new String(line.substring(0, stringIndex)); } else if (forbidden) { int stringIndex = line.indexOf("/X"); word = new String(line.substring(0, stringIndex)); } else { word = line.toString(); } if (tree == null) { tree = new BKTree(); } tree.insertDictionaryWord(word, plural, forbidden); } } while (line != null); } logger.debug("Loading supplemental dictionary..."); List<String> listOfWords = KSupplementalDictionaryUtil.getWords(); for (String word : listOfWords) { tree.insertDictionaryWord(word, false, false); } initialized = true; } catch (Exception exception) { logger.error("Error", exception); } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { } } if (buffReader != null) { try { buffReader.close(); } catch (Exception ex) { } } } }
Code Sample 2:
public static String encodeMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } |
00
| Code Sample 1:
public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } |
11
| Code Sample 1:
public void backup(File source) throws BackupException { try { int index = source.getAbsolutePath().lastIndexOf("."); if (index == -1) return; File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak"); FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { throw new BackupException(ex.getMessage(), ex, source); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } } |
11
| Code Sample 1:
Library(MainFrame mf, boolean newLibrary, String templateName, String newFileName) throws Exception { mainFrame = mf; trackMap = new HashMap<String, LibraryTrack>(); trackVec = new Vector<LibraryTrack>(); String propFileName = null; File propFile = null; String notExist = ""; String[] options = templateDesc; boolean isCurrent = mainFrame.library != null; int ix; if (!newLibrary) { propFileName = mainFrame.name + ".jampal"; propFile = new File(propFileName); } if (isCurrent) { options = new String[templateDesc.length + 1]; options[0] = "Copy of Current Library"; for (ix = 0; ix < templateDesc.length; ix++) { options[ix + 1] = templateDesc[ix]; } } boolean copyLibrary = false; if (newLibrary) { if (templateName == null) { Object resp = JOptionPane.showInputDialog(mainFrame.frame, "Please select a template.", "Select Type of Library", JOptionPane.WARNING_MESSAGE, null, options, null); if (resp == null) return; templateName = (String) resp; } for (ix = 0; ix < options.length && !options[ix].equals(templateName); ix++) ; if (isCurrent) ix--; boolean creatingPlaylist = false; BufferedReader in; if (ix == -1) { in = new BufferedReader(new FileReader(mainFrame.name + ".jampal")); copyLibrary = true; creatingPlaylist = (mainFrame.library.attributes.libraryType == 'P'); } else { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/" + templateNames[ix]))); creatingPlaylist = ("playlist.jampal".equals(templateNames[ix])); } if (newFileName == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Create New Library File"); String currentDirectory = null; if (mainFrame.name != null) { File nameFile = new File(mainFrame.name); currentDirectory = nameFile.getParent(); if (currentDirectory == null) currentDirectory = "."; } if (currentDirectory == null) currentDirectory = Jampal.jampalDirectory; if (currentDirectory != null) fileChooser.setCurrentDirectory(new File(currentDirectory)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); Mp3FileFilter filter = new Mp3FileFilter(); filter.setExtension("jampal", "Jampal library files"); fileChooser.addChoosableFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fileChooser.showSaveDialog(mainFrame.frame); if (returnVal == fileChooser.APPROVE_OPTION) { propFile = fileChooser.getSelectedFile(); propFileName = propFile.getPath(); if (!propFileName.toLowerCase().endsWith(".jampal")) { propFileName = propFileName + ".jampal"; propFile = new File(propFileName); } } else return; } else { propFileName = newFileName; propFile = new File(propFileName); } if (propFile.exists()) { if (JOptionPane.showConfirmDialog(mainFrame.frame, "File " + propFileName + " already exists. Do you want to overwrite it ?", "Warning", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } PrintWriter out = new PrintWriter(new FileOutputStream(propFile)); String libName = propFile.getName(); libName = libName.substring(0, libName.length() - 7); for (; ; ) { String line = in.readLine(); if (line == null) break; if (creatingPlaylist && line.startsWith("playlist=")) { line = "playlist=" + libName; } if (line.startsWith("libraryname=")) { line = "libraryname=" + libName + ".jmp"; } out.println(line); } in.close(); out.close(); if (!creatingPlaylist && !copyLibrary) { String playlistName = propFile.getParent() + File.separator + "playlist.jampal"; File playlistFile = new File(playlistName); if (!playlistFile.exists()) { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/playlist.jampal"))); out = new PrintWriter(new FileOutputStream(playlistFile)); for (; ; ) { String line = in.readLine(); if (line == null) break; out.println(line); } in.close(); out.close(); } } } if (propFileName != null) attributes = new LibraryAttributes(propFileName); insertBefore = -1; }
Code Sample 2:
@Override public void copierPhotos(FileInputStream fichierACopier, FileOutputStream fichierDestination) { FileChannel in = null; FileChannel out = null; try { in = fichierACopier.getChannel(); out = fichierDestination.getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } |
00
| Code Sample 1:
private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; }
Code Sample 2:
private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText("Cargar Imagen"); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setFileView(new ImageFileView()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName(); String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); } catch (IOException ex) { ex.printStackTrace(); } imagen.setImagenURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL())); } else { } } }); } return buttonImagen; } |
00
| Code Sample 1:
private SecretKey getSecretKey() { try { String path = "/org.dbreplicator/repconsole/secretKey.obj"; java.net.URL url1 = getClass().getResource(path); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(url1.openStream())); SecretKey sk = (SecretKey) ois.readObject(); return sk; } catch (IOException ex) { } catch (ClassNotFoundException ex) { } return null; }
Code Sample 2:
public static void writeFromURL(String urlstr, String filename) throws Exception { URL url = new URL(urlstr); InputStream in = url.openStream(); BufferedReader bf = null; StringBuffer sb = new StringBuffer(); try { bf = new BufferedReader(new InputStreamReader(in, "latin1")); String s; while (true) { s = bf.readLine(); if (s != null) { sb.append(s); } else { break; } } } catch (Exception e) { throw e; } finally { bf.close(); } writeRawBytes(sb.toString(), filename); } |
11
| Code Sample 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; }
Code Sample 2:
public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } } |
11
| Code Sample 1:
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } |
00
| Code Sample 1:
public static AddUserResponse napiUserAdd(String user, String pass, String email) throws TimeoutException, InterruptedException, IOException { if (user.matches("^[a-zA-Z0-9]{2,20}$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_LOGIN; } if (pass.equals("")) { return AddUserResponse.NAPI_ADD_USER_BAD_PASS; } if (email.matches("^[a-zA-Z0-9\\-\\_]{1,30}@[a-zA-Z0-9]+(\\.[a-zA-Z0-9]+)+$") == false) { return AddUserResponse.NAPI_ADD_USER_BAD_EMAIL; } URLConnection conn = null; ClientHttpRequest httpPost = null; InputStreamReader responseStream = null; URL url = new URL("http://www.napiprojekt.pl/users_add.php"); conn = url.openConnection(Global.getProxy()); httpPost = new ClientHttpRequest(conn); httpPost.setParameter("login", user); httpPost.setParameter("haslo", pass); httpPost.setParameter("mail", email); httpPost.setParameter("z_programu", "true"); responseStream = new InputStreamReader(httpPost.post(), "Cp1250"); BufferedReader responseReader = new BufferedReader(responseStream); String response = responseReader.readLine(); if (response.indexOf("login już istnieje") != -1) { return AddUserResponse.NAPI_ADD_USER_LOGIN_EXISTS; } if (response.indexOf("na podany e-mail") != -1) { return AddUserResponse.NAPI_ADD_USER_EMAIL_EXISTS; } if (response.indexOf("NPc0") == 0) { return AddUserResponse.NAPI_ADD_USER_OK; } return AddUserResponse.NAPI_ADD_USER_BAD_UNKNOWN; }
Code Sample 2:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); } |
00
| Code Sample 1:
public static List<String> getFiles(int year, int month, int day, String type) throws Exception { ArrayList<String> list = new ArrayList<String>(); URL url = new URL(baseUrl + "/" + year + "/" + ((month > 9) ? month : ("0" + month)) + "/" + ((day > 9) ? day : ("0" + day))); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null && line != "") { if (line.startsWith("<tr>") && line.indexOf("[TXT]") >= 0) { int i = line.indexOf("href="); i = i + 6; int j = line.indexOf("\"", i); String filename = line.substring(i, j); if (filename.matches(".*" + type + ".*")) { list.add(filename); } } } br.close(); return list; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } |
11
| Code Sample 1:
private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } }
Code Sample 2:
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } } |
00
| Code Sample 1:
private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } }
Code Sample 2:
public void connect() throws FTPException { try { ftp = new FTPClient(); ftp.connect(host); if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) { ftp.login(this.username, this.password); } else { ftp.disconnect(); throw new FTPException("Não foi possivel se conectar no servidor FTP"); } isConnected = true; } catch (Exception ex) { throw new FTPException(ex); } } |
11
| Code Sample 1:
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } |
11
| Code Sample 1:
public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } } |
00
| Code Sample 1:
public static void copy(File in, File out) throws IOException { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
Code Sample 2:
private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } } |
00
| Code Sample 1:
private static void main(String mp3Path) throws IOException { String convPath = "http://android.adinterest.biz/wav2mp3.php?k="; String uri = convPath + mp3Path; URL rssurl = new URL(uri); InputStream is = rssurl.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String buf = ""; while ((buf = br.readLine()) != null) { } is.close(); br.close(); }
Code Sample 2:
public static void toZip(File zippedFile, File[] filesToZip, String zipComment, boolean savePath, int compressionLevel) throws IOException, FileNotFoundException, ZipException { if (zippedFile != null && filesToZip != null) { new File(zippedFile.getParent()).mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new CheckedOutputStream(new FileOutputStream(zippedFile), new CRC32()))); if (ZIP_NO_COMPRESSION <= compressionLevel && compressionLevel <= ZIP_MAX_COMPRESSION) out.setLevel(compressionLevel); else out.setLevel(ZIP_MAX_COMPRESSION); if (zipComment != null) out.setComment(zipComment); for (int i = 0; i < filesToZip.length; i++) { BufferedInputStream in; if (savePath) { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(cleanPath(filesToZip[i].getAbsolutePath()))); } else { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(filesToZip[i].getName())); } for (int c = in.read(); c != -1; c = in.read()) out.write(c); in.close(); } out.close(); } else throw new ZipException(MAIN_RESOURCE_BUNDLE.getString("default.ZipException.text")); } |
00
| Code Sample 1:
public Download(URL url, int segs) { this.url = url; Mediator.register(this); status = "Starting..."; try { totalSize = url.openConnection().getContentLength(); name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1); if (name.isEmpty()) { name = "UNKNOWN"; } tempFolder = new File(Configuration.PARTS_FOLDER, getName()); tempFolder.mkdir(); } catch (IOException ex) { Logger.post(Logger.Level.WARNING, "URL could not be opened: " + url); } dest = new File(System.getProperty("user.home") + File.separator + name); if (segs > totalSize) { segs = totalSize; } Properties props = new Properties(); props.setProperty("url", getUrl().toString()); props.setProperty("segments", String.valueOf(segs)); try { props.storeToXML(new FileOutputStream(new File(getTempFolder(), "index.xml")), "Warning: Editing this file may compromise the integrity of the download"); } catch (IOException ex) { ex.printStackTrace(); } segments = new Segment[segs]; for (int i = 0; i < segs; i++) { segments[i] = new Segment(this, i); } Thread thread = new Thread(this); thread.setDaemon(true); thread.start(); status = "Downloading..."; Mediator.post(new DownloadStatusChanged(this)); Logger.post(Logger.Level.INFO, "Starting download: " + getName()); }
Code Sample 2:
private void run(String[] args) throws Throwable { ArgParser parser = new ArgParser("Run an experiment"); parser.addOptions(this, true); args = parser.matchAllArgs(args, 0, ArgParserOption.EXIT_ON_ERROR, ArgParserOption.STOP_FIRST_UNMATCHED); if (log4jFile != null) { logger.info("Using another log4j configuration: %s", log4jFile); PropertyConfigurator.configure(log4jFile.getAbsolutePath()); } final TreeMap<TaskName, Class<Task>> tasks = GenericHelper.newTreeMap(); final Enumeration<URL> e = About.class.getClassLoader().getResources(EXPERIMENT_PACKAGES); while (e.hasMoreElements()) { final URL url = e.nextElement(); logger.debug("Got URL %s", url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { String packageName = line; getTasks(url, tasks, packageName); } } getTasks(null, tasks, getClass().getPackage().getName()); if (tasks.isEmpty()) { logger.fatal("I did not find any valid experiment (service bpiwowar.experiments.ExperimentListProvider)"); System.exit(1); } if (args.length == 0 || args[0].equals("list")) { System.out.format("Available experiments:%n"); TreeMapArray<PackageName, String> map = TreeMapArray.newInstance(); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { TaskName task = entry.getKey(); if (showClassNames) map.add(task.packageName, String.format("%s (%s)", task.name, entry.getValue().toString())); else map.add(task.packageName, task.name); } Stack<PackageName> ancestors = new Stack<PackageName>(); for (Entry<PackageName, ArrayList<String>> entry : map.entrySet()) { final PackageName key = entry.getKey(); while (!ancestors.isEmpty() && key.commonPrefixLength(ancestors.peek()) != ancestors.peek().getLength()) ancestors.pop(); int nbAncestors = ancestors.size(); int c = nbAncestors > 0 ? ancestors.peek().getLength() : 0; StringBuilder s = new StringBuilder(); for (int i = 0; i < c; i++) s.append("|"); for (int i = c; i < key.getLength(); i++) { s.append("|"); ancestors.add(new PackageName(key, i + 1)); System.out.format("%s%n", s); System.out.format("%s+ [%s]%n", s, ancestors.peek()); nbAncestors++; } String prefix = s.toString(); for (String task : entry.getValue()) System.out.format("%s|- %s%n", prefix, task); ancestors.add(key); } return; } else if (args[0].equals(SEARCH_COMMAND)) { final class Options { @OrderedArgument(required = true) String search; } Options options = new Options(); ArgParser ap = new ArgParser(SEARCH_COMMAND); ap.addOptions(options); ap.matchAllArgs(args, 1); logger.info("Searching for %s", options.search); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { TaskName taskname = entry.getKey(); if (taskname.name.contains(options.search)) { System.err.format("[*] %s - %s%n %s%n", taskname, entry.getValue(), entry.getValue().getAnnotation(TaskDescription.class).description()); } } return; } String taskName = args[0]; args = Arrays.copyOfRange(args, 1, args.length); ArrayList<Class<Task>> matching = GenericHelper.newArrayList(); for (Entry<TaskName, Class<Task>> entry : tasks.entrySet()) { if (entry.getKey().name.equals(taskName)) matching.add(entry.getValue()); } if (matching.isEmpty()) { System.err.println("No task match " + taskName); System.exit(1); } if (matching.size() > 1) { System.err.println("Too many tasks match " + taskName); System.exit(1); } Class<Task> taskClass = matching.get(0); logger.info("Running experiment " + taskClass.getCanonicalName()); Task task = taskClass.newInstance(); int errorCode = 0; try { task.init(args); if (xstreamOutput != null) { OutputStream out; if (xstreamOutput.toString().equals("-")) out = System.out; else out = new FileOutputStream(xstreamOutput); logger.info("Serializing the object into %s", xstreamOutput); new XStream().toXML(task, out); out.close(); } else { errorCode = task.run(); } logger.info("Finished task"); } catch (Throwable t) { if (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } logger.error("Exception thrown while executing the action:%n%s%n", t); errorCode = 2; } System.exit(errorCode); } |
00
| Code Sample 1:
public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
Code Sample 2:
public void loadProperties() { try { java.util.Properties props = new java.util.Properties(); java.net.URL url = ClassLoader.getSystemResource("env.properties"); props.load(url.openStream()); this.proxyCertificatePath = props.getProperty("proxy.certificate.path"); this.dummyFileDirName = props.getProperty("delete.dummyFileDirName"); this.idleTimeTestDelay = new Integer(props.getProperty("idleTimeTestDelaySeconds")); if (props.getProperty("gridftp.timeoutMilliSecs") != null) { this.gridftpTimeoutMilliSecs = new Integer(props.getProperty("gridftp.timeoutMilliSecs").trim()); } this.assertContentInWriteTests = new Boolean(props.getProperty("assertContentInWriteTests")); this.gridftpHost1 = props.getProperty("gridftp.host1"); this.gridftpPort1 = new Integer(props.getProperty("gridftp.port1")); this.gridftpHost2 = props.getProperty("gridftp.host2"); this.gridftpPort2 = new Integer(props.getProperty("gridftp.port2")); this.srbGsiHost = props.getProperty("srb.gsi.host"); this.srbGsiPort = new Integer(props.getProperty("srb.gsi.port")); this.srbGsiPortMin = new Integer(props.getProperty("srb.gsi.port.min")); this.srbGsiPortMax = new Integer(props.getProperty("srb.gsi.port.max")); this.srbGsiDefaultResource = props.getProperty("srb.gsi.defaultResource"); this.srbEncryptHost = props.getProperty("srb.encrypt.host"); this.srbEncryptPort = new Integer(props.getProperty("srb.encrypt.port")); this.srbEncryptPortMin = new Integer(props.getProperty("srb.encrypt.port.min")); this.srbEncryptPortMax = new Integer(props.getProperty("srb.encrypt.port.max")); this.srbEncryptDefaultResource = props.getProperty("srb.encrypt.defaultResource"); this.srbEncryptHomeDirectory = props.getProperty("srb.encrypt.homeDirectory"); this.srbEncryptMcatZone = props.getProperty("srb.encrypt.mcatZone"); this.srbEncryptMdasDomainName = props.getProperty("srb.encrypt.mdasDomainName"); this.srbEncryptUsername = props.getProperty("srb.encrypt.username"); this.srbEncryptPassword = props.getProperty("srb.encrypt.password"); this.sftpHost = props.getProperty("sftp.host"); this.sftpPort = new Integer(props.getProperty("sftp.port")); this.sftpPath = props.getProperty("sftp.path"); this.sftpUsername = props.getProperty("sftp.username"); this.sftpPassword = props.getProperty("sftp.password"); if (props.getProperty("sftp.timeoutMilliSecs") != null) { this.sftpTimeoutMilliSecs = new Integer(props.getProperty("sftp.timeoutMilliSecs").trim()); } irodsEncryptHost = props.getProperty("irods.encrypt.host"); irodsEncryptPort = new Integer(props.getProperty("irods.encrypt.port")); irodsEncryptResource = props.getProperty("irods.encrypt.defaultResource"); irodsEncryptHomeDirectory = props.getProperty("irods.encrypt.homeDirectory"); irodsEncryptZone = props.getProperty("irods.encrypt.zone"); irodsEncryptUsername = props.getProperty("irods.encrypt.username"); irodsEncryptPassword = props.getProperty("irods.encrypt.password"); irodsGsiHost = props.getProperty("irods.gsi.host"); irodsGsiPort = new Integer(props.getProperty("irods.gsi.port")); irodsGsiZone = props.getProperty("irods.gsi.zone"); srbQueryTimeout = new Integer(props.getProperty("srb.query.timeout")); this.ftpUri = props.getProperty("ftp.uri"); this.httpUri = props.getProperty("http.uri"); this.httpProxy = props.getProperty("http.proxy"); this.httpPort = new Integer(props.getProperty("http.port")); this.fileUri = props.getProperty("file.uri"); java.net.URI tempUri = new java.net.URI(this.fileUri); File f = new File(tempUri); if (!f.exists()) { String temp = System.getProperty("java.io.tmpdir"); System.out.println("Cannot list [" + fileUri + "] listing java.io.tmpdir instead [" + temp + "]"); this.fileUri = temp; } useSrbGsiInFsCopyTest = new Boolean(props.getProperty("srb.gsi.use.in.fs.copy.test")); useSrbEncryptInFsCopyTest = new Boolean(props.getProperty("srb.encrypt.use.in.fs.copy.test")); useGridftpHost1InFsCopyTest = new Boolean(props.getProperty("gridftp.host1.use.in.fs.copy.test")); useGridftpHost2InFsCopyTest = new Boolean(props.getProperty("gridftp.host2.use.in.fs.copy.test")); useSftpInFsCopyTest = new Boolean(props.getProperty("sftp.use.in.fs.copy.test")); useLocalFileInFsCopyTest = new Boolean(props.getProperty("file.use.in.fs.copy.test")); useIrodsGsiCopyTest = new Boolean(props.getProperty("irods.gsi.use.in.fs.copy.test")); useIrodsEncryptCopyTest = new Boolean(props.getProperty("irods.encrypt.use.in.fs.copy.test")); assertNotNull(this.proxyCertificatePath); assertNotNull(this.dummyFileDirName); assertNotNull(this.idleTimeTestDelay); assertNotNull(this.ftpUri); assertNotNull(this.httpUri); } catch (Exception ex) { Logger.getLogger(AbstractTestClass.class.getName()).log(Level.SEVERE, null, ex); fail("Unable to locate and load 'testsettings.properties' file in source " + ex); } } |
11
| Code Sample 1:
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException { File pathToWebInf = new File(portletDir, "WEB-INF"); File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf); tempWebXml.deleteOnExit(); OutputStream webOutputStream = new FileOutputStream(tempWebXml); PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY; IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream); webOutputStream.close(); return tempWebXml; } |
00
| Code Sample 1:
public static InputSource openInputSource(String resource) { InputSource src = null; URL url = findResource(resource); if (url != null) { try { InputStream in = url.openStream(); src = new InputSource(in); src.setSystemId(url.toExternalForm()); } catch (IOException e) { } } return src; }
Code Sample 2:
private boolean importPKC(String keystoreLocation, String pw, String pkcFile, String alias) { boolean imported = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pkcFile)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { cert = cf.generateCertificate(bis); } } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from file when importing PKC: " + e.getMessage()); } return false; } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation))); } catch (FileNotFoundException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error accessing key store file when importing certificate: " + e.getMessage()); } return false; } try { if (alias.equals("rootca")) { ks.setCertificateEntry(alias, cert); } else { KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(pw.toCharArray())); ks.setKeyEntry(alias, pkEntry.getPrivateKey(), pw.toCharArray(), new Certificate[] { cert }); } ks.store(bos, pw.toCharArray()); imported = true; } catch (Exception e) { e.printStackTrace(); if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error writing keystore to file when importing key store: " + e.getMessage()); } return false; } return imported; } |
11
| Code Sample 1:
public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
public static String encrypt(String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(password.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return password; } }
Code Sample 2:
public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); } |
00
| Code Sample 1:
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
private void copyFile(File sourceFile, File targetFile) { beNice(); dispatchEvent(SynchronizationEventType.FileCopy, sourceFile, targetFile); File temporaryFile = new File(targetFile.getPath().concat(".jnstemp")); while (temporaryFile.exists()) { try { beNice(); temporaryFile.delete(); beNice(); } catch (Exception ex) { } } try { if (targetFile.exists()) { targetFile.delete(); } FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(temporaryFile); byte[] buffer = new byte[204800]; int readBytes = 0; int counter = 0; while ((readBytes = fis.read(buffer)) != -1) { counter++; updateStatus("... processing fragment " + String.valueOf(counter)); fos.write(buffer, 0, readBytes); } fis.close(); fos.close(); temporaryFile.renameTo(targetFile); temporaryFile.setLastModified(sourceFile.lastModified()); targetFile.setLastModified(sourceFile.lastModified()); } catch (IOException e) { Exception dispatchedException = new Exception("ERROR: Copy File( " + sourceFile.getPath() + ", " + targetFile.getPath() + " )"); dispatchEvent(dispatchedException, sourceFile, targetFile); } dispatchEvent(SynchronizationEventType.FileCopyDone, sourceFile, targetFile); }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } |
11
| Code Sample 1:
protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
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(); } }
Code Sample 2:
public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } } |
00
| Code Sample 1:
public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) { log.info("Start update auth"); PreparedStatement ps = null; DatabaseAdapter db = null; try { db = DatabaseAdapter.getInstance(); String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE ID_AUTH_USER=? "; ps = db.prepareStatement(sql); if (infoAuth.getAuthInfo().getCompanyId() == null) { ps.setNull(1, Types.INTEGER); ps.setInt(2, 0); } else { ps.setLong(1, infoAuth.getAuthInfo().getCompanyId()); ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0); } if (infoAuth.getAuthInfo().getHoldingId() == null) { ps.setNull(3, Types.INTEGER); ps.setInt(4, 0); } else { ps.setLong(3, infoAuth.getAuthInfo().getHoldingId()); ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0); } ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId()); ps.executeUpdate(); processDeletedRoles(db, infoAuth); processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId()); db.commit(); } catch (Throwable e) { try { if (db != null) db.rollback(); } catch (Exception e001) { } final String es = "Error add user auth"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(db, ps); ps = null; db = null; log.info("End update auth"); } }
Code Sample 2:
private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } } |
00
| Code Sample 1:
private File extractSiteFile() { final URL url = TestCrueCONF.class.getResource(CONFIG_SITE); final File confFile = new File(createTempDir(), "FudaaCrue_Site.xml"); try { CtuluLibFile.copyStream(url.openStream(), new FileOutputStream(confFile), true, true); } catch (Exception e) { Logger.getLogger(TestCrueCONF.class.getName()).log(Level.SEVERE, "erreur while extracting FudaaCrue_Site.xml", e); fail(e.getMessage()); } return confFile; }
Code Sample 2:
public void moveMessage(DBMimeMessage oSrcMsg) throws MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.moveMessage()"); DebugFile.incIdent(); } JDCConnection oConn = null; PreparedStatement oStmt = null; ResultSet oRSet = null; BigDecimal oPg = null; BigDecimal oPos = null; int iLen = 0; try { oConn = ((DBStore) getStore()).getConnection(); oStmt = oConn.prepareStatement("SELECT " + DB.pg_message + "," + DB.nu_position + "," + DB.len_mimemsg + " FROM " + DB.k_mime_msgs + " WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, oSrcMsg.getMessageGuid()); oRSet = oStmt.executeQuery(); if (oRSet.next()) { oPg = oRSet.getBigDecimal(1); oPos = oRSet.getBigDecimal(2); iLen = oRSet.getInt(3); } oRSet.close(); oRSet = null; oStmt.close(); oStmt = null; oConn.setAutoCommit(false); oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "-" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, ((DBFolder) (oSrcMsg.getFolder())).getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iLen) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oRSet) { try { oRSet.close(); } catch (Exception ignore) { } } if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (null == oPg) throw new MessagingException("Source message not found"); if (null == oPos) throw new MessagingException("Source message position is not valid"); DBFolder oSrcFldr = (DBFolder) oSrcMsg.getFolder(); MboxFile oMboxSrc = null, oMboxThis = null; try { oMboxSrc = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis = new MboxFile(oSrcFldr.getFile(), MboxFile.READ_WRITE); oMboxThis.appendMessage(oMboxSrc, oPos.longValue(), iLen); oMboxThis.close(); oMboxThis = null; oMboxSrc.purge(new int[] { oPg.intValue() }); oMboxSrc.close(); oMboxSrc = null; } catch (Exception e) { if (oMboxThis != null) { try { oMboxThis.close(); } catch (Exception ignore) { } } if (oMboxSrc != null) { try { oMboxSrc.close(); } catch (Exception ignore) { } } throw new MessagingException(e.getMessage(), e); } try { oConn = ((DBStore) getStore()).getConnection(); BigDecimal dNext = getNextMessage(); String sCatGuid = getCategory().getString(DB.gu_category); oStmt = oConn.prepareStatement("UPDATE " + DB.k_mime_msgs + " SET " + DB.gu_category + "=?," + DB.pg_message + "=? WHERE " + DB.gu_mimemsg + "=?"); oStmt.setString(1, sCatGuid); oStmt.setBigDecimal(2, dNext); oStmt.setString(3, oSrcMsg.getMessageGuid()); oStmt.executeUpdate(); oStmt.close(); oStmt = null; oConn.commit(); } catch (SQLException sqle) { if (null != oStmt) { try { oStmt.close(); } catch (Exception ignore) { } } if (null != oConn) { try { oConn.rollback(); } catch (Exception ignore) { } } throw new MessagingException(sqle.getMessage(), sqle); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.moveMessage()"); } } |
11
| Code Sample 1:
private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } }
Code Sample 2:
public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } |
11
| Code Sample 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; }
Code Sample 2:
public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } |
00
| Code Sample 1:
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if (baseName == null || locale == null || format == null || loader == null) throw new NullPointerException(); ResourceBundle bundle = null; if (format.equals("user")) { String bundleName = toBundleName(baseName, locale); String resourceName = "file://" + config.getString(HOME) + "/" + bundleName + ".properties"; InputStream stream = null; try { URL url = new URL(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { if (reload) { connection.setUseCaches(false); } stream = connection.getInputStream(); } } } catch (Throwable t) { } if (stream != null) { BufferedInputStream bis = new BufferedInputStream(stream); bundle = new UserResourceBundle(UTF8ClassLoader.readUTFStreamToEscapedASCII(bis), super.newBundle(baseName, locale, "java.properties", loader, reload)); bis.close(); } else { return super.newBundle(baseName, locale, "java.properties", loader, reload); } } return bundle; }
Code Sample 2:
protected void shutdown(final boolean unexpected) { ControlerState oldState = this.state; this.state = ControlerState.Shutdown; if (oldState == ControlerState.Running) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } this.controlerListenerManager.fireControlerShutdownEvent(unexpected); if (this.dumpDataAtEnd) { Knowledges kk; if (this.config.scenario().isUseKnowledges()) { kk = (this.getScenario()).getKnowledges(); } else { kk = this.getScenario().retrieveNotEnabledKnowledges(); } new PopulationWriter(this.population, this.network, kk).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); ActivityFacilities facilities = this.getFacilities(); if (facilities != null) { new FacilitiesWriter((ActivityFacilitiesImpl) facilities).write(this.controlerIO.getOutputFilename("output_facilities.xml.gz")); } if (((NetworkFactoryImpl) this.network.getFactory()).isTimeVariant()) { new NetworkChangeEventsWriter().write(this.controlerIO.getOutputFilename("output_change_events.xml.gz"), ((NetworkImpl) this.network).getNetworkChangeEvents()); } if (this.config.scenario().isUseHouseholds()) { new HouseholdsWriterV10(this.scenarioData.getHouseholds()).writeFile(this.controlerIO.getOutputFilename(FILENAME_HOUSEHOLDS)); } if (this.config.scenario().isUseLanes()) { new LaneDefinitionsWriter20(this.scenarioData.getScenarioElement(LaneDefinitions20.class)).write(this.controlerIO.getOutputFilename(FILENAME_LANES)); } if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); } } |
11
| Code Sample 1:
public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[]) m_data; os.write(buffer); os.flush(); os.close(); log.config("Save to " + file + " #" + buffer.length); } else { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data; log.config("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.log(Level.WARNING, "Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) { } }
Code Sample 2:
protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } } |
11
| Code Sample 1:
public void salva(UploadedFile imagem, Usuario usuario) { File destino = new File(pastaImagens, usuario.getId() + ".imagem"); try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (IOException e) { throw new RuntimeException("Erro ao copiar imagem", e); } }
Code Sample 2:
public static void copyFile(String sourceFilePath, String destFilePath) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sourceFilePath).getChannel(); out = new FileOutputStream(destFilePath).getChannel(); long inputSize = in.size(); in.transferTo(0, inputSize, out); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, inputSize); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } |
00
| Code Sample 1:
protected InputSource getInputSource(String pReferencingSystemId, String pURI) throws SAXException { URL url = null; if (pReferencingSystemId != null) { try { url = new URL(new URL(pReferencingSystemId), pURI); } catch (MalformedURLException e) { } if (url == null) { try { url = new File(new File(pReferencingSystemId).getParentFile(), pURI).toURL(); } catch (MalformedURLException e) { } } } if (url == null) { try { url = new URL(pURI); } catch (MalformedURLException e) { try { url = new File(pURI).toURL(); } catch (MalformedURLException f) { throw new SAXException("Failed to parse the URI " + pURI); } } } try { InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toString()); return isource; } catch (IOException e) { throw new SAXException("Failed to open the URL " + url, e); } }
Code Sample 2:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long startTime = System.currentTimeMillis(); boolean validClient = true; boolean validSession = false; String sessionKey = req.getParameter("sid"); String storedKey = CLIENT_SESSION_KEYS.get(req.getRemoteAddr()); if (sessionKey != null && storedKey != null && sessionKey.equals(storedKey)) validSession = true; DataStore ds = DataStore.getConnection(); if (IPV6_DETECTED) { boolean doneWarning; synchronized (SJQServlet.class) { doneWarning = IPV6_WARNED; if (!IPV6_WARNED) IPV6_WARNED = true; } if (!doneWarning) LOG.warn("IPv6 interface detected; client restriction settings ignored [restrictions do not support IPv6 addresses]"); } else { String[] clntRestrictions = ds.getSetting("ValidClients", "").split(";"); List<IPMatcher> matchers = new ArrayList<IPMatcher>(); if (clntRestrictions.length == 1 && clntRestrictions[0].trim().length() == 0) { LOG.warn("All client connections are being accepted and processed, please consider setting up client restrictions in SJQ settings"); } else { for (String s : clntRestrictions) { s = s.trim(); try { matchers.add(new IPMatcher(s)); } catch (IPMatcherException e) { LOG.error("Invalid client restriction settings; client restrictions ignored!", e); matchers.clear(); break; } } validClient = matchers.size() > 0 ? false : true; for (IPMatcher m : matchers) { try { if (m.match(req.getRemoteAddr())) { validClient = true; break; } } catch (IPMatcherException e) { LOG.error("IPMatcherException", e); } } } } String clntProto = req.getParameter("proto"); if (clntProto == null || Integer.parseInt(clntProto) != SJQ_PROTO) throw new RuntimeException("Server is speaking protocol '" + SJQ_PROTO + "', but client is speaking protocol '" + clntProto + "'; install a client version that matches the server protocol version!"); resp.setHeader("Content-Type", "text/plain"); resp.setDateHeader("Expires", 0); resp.setDateHeader("Last-Modified", System.currentTimeMillis()); resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); resp.setHeader("Pragma", "no-cache"); String cmd = req.getParameter("cmd"); if (cmd == null) { DataStore.returnConnection(ds); return; } ActiveClientList list = ActiveClientList.getInstance(); BufferedWriter bw = new BufferedWriter(resp.getWriter()); if (cmd.equals("pop")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); ClientParser clnt = new ClientParser(new StringReader(ds.getClientConf(req.getRemoteHost()))); String offDay = clnt.getGlobalOption("OFFDAY"); String offHour = clnt.getGlobalOption("OFFHOUR"); Calendar now = Calendar.getInstance(); if (RangeInterpreter.inRange(now.get(Calendar.DAY_OF_WEEK), 1, 7, offDay) || RangeInterpreter.inRange(now.get(Calendar.HOUR_OF_DAY), 0, 23, offHour)) { LOG.warn("Client '" + req.getRemoteAddr() + "' currently disabled via OFFDAY/OFFHOUR settings."); bw.write("null"); } else { Task t = TaskQueue.getInstance().pop(req.getRemoteHost(), getPopCandidates(req.getRemoteHost(), clnt)); if (t == null) bw.write("null"); else { t.setResourcesUsed(Integer.parseInt(clnt.getTask(t.getTaskId()).getOption("RESOURCES"))); Object obj = null; if (t.getObjType().equals("media")) obj = Butler.SageApi.mediaFileAPI.GetMediaFileForID(Integer.parseInt(t.getObjId())); else if (t.getObjType().equals("sysmsg")) obj = SystemMessageUtils.getSysMsg(t.getObjId()); ClientTask cTask = clnt.getTask(t.getTaskId()); JSONObject jobj = cTask.toJSONObject(obj); String objType = null; try { if (jobj != null) objType = jobj.getString(Task.JSON_OBJ_TYPE); } catch (JSONException e) { throw new RuntimeException("Invalid ClienTask JSON object conversion!"); } if (obj == null || jobj == null) { LOG.error("Source object has disappeared! [" + t.getObjType() + "/" + t.getObjId() + "]"); TaskQueue.getInstance().updateTask(t.getObjId(), t.getTaskId(), Task.State.FAILED, t.getObjType()); bw.write("null"); } else if (objType.equals("media")) { try { long ratio = calcRatio(jobj.getString(Task.JSON_OBJ_ID), jobj.getString(Task.JSON_NORECORDING)); if (ratio > 0 && new FieldTimeUntilNextRecording(null, "<=", ratio + "S").run()) { LOG.info("Client '" + req.getRemoteAddr() + "' cannot pop task '" + t.getObjType() + "/" + t.getTaskId() + "/" + t.getObjId() + "'; :NORECORDING option prevents running of this task"); TaskQueue.getInstance().pushBack(t); bw.write("null"); } else bw.write(jobj.toString()); } catch (JSONException e) { throw new RuntimeException(e); } } else bw.write(jobj.toString()); } } } } else if (cmd.equals("update")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); try { Task t = new Task(new JSONObject(req.getParameter("data"))); TaskQueue.getInstance().updateTask(t); } catch (JSONException e) { throw new RuntimeException("Input error; client '" + req.getRemoteHost() + "', CMD: update", e); } } } else if (cmd.equals("showQ")) { if (validSession) bw.write(TaskQueue.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("log")) { if (validSession) { String mediaId = req.getParameter("m"); String taskId = req.getParameter("t"); String objType = req.getParameter("o"); if ((mediaId != null && !mediaId.equals("0")) && (taskId != null && !taskId.equals("0"))) bw.write(ds.readLog(mediaId, taskId, objType)); else { BufferedReader r = new BufferedReader(new FileReader("sjq.log")); String line; while ((line = r.readLine()) != null) bw.write(line + "\n"); r.close(); } } else notAuthorized(resp, bw); } else if (cmd.equals("appState")) { if (validSession) bw.write(Butler.dumpAppTrace()); else notAuthorized(resp, bw); } else if (cmd.equals("writeLog")) { if (!validClient) { LOG.warn("Client IP reject: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { String mediaId = req.getParameter("m"); String taskId; if (!mediaId.equals("-1")) taskId = req.getParameter("t"); else taskId = req.getRemoteHost(); String objType = req.getParameter("o"); if (!mediaId.equals("0") && Boolean.parseBoolean(ds.getSetting("IgnoreTaskOutput", "false"))) { LOG.info("Dropping task output as per settings"); DataStore.returnConnection(ds); return; } String data = req.getParameter("data"); String[] msg = StringUtils.splitByWholeSeparator(data, "\r\n"); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\r'); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\n'); long now = System.currentTimeMillis(); for (String line : msg) ds.logForTaskClient(mediaId, taskId, line, now, objType); if (msg.length > 0) ds.flushLogs(); } } else if (cmd.equals("ruleset")) { if (validSession) bw.write(ds.getSetting("ruleset", "")); else notAuthorized(resp, bw); } else if (cmd.equals("saveRuleset")) { if (validSession) { ds.setSetting("ruleset", req.getParameter("data")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getClients")) { if (validSession) bw.write(ActiveClientList.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("loadClnt")) { if (validSession) bw.write(ds.getClientConf(req.getParameter("id"))); else notAuthorized(resp, bw); } else if (cmd.equals("saveClnt")) { if (validSession) { if (ds.saveClientConf(req.getParameter("id"), req.getParameter("data"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("history")) { if (validSession) { int start, limit; try { start = Integer.parseInt(req.getParameter("start")); limit = Integer.parseInt(req.getParameter("limit")); } catch (NumberFormatException e) { start = 0; limit = -1; } bw.write(ds.getJobHistory(Integer.parseInt(req.getParameter("t")), start, limit, req.getParameter("sort")).toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("getSrvSetting")) { if (validSession) bw.write(ds.getSetting(req.getParameter("var"), "")); else notAuthorized(resp, bw); } else if (cmd.equals("setSrvSetting")) { if (validSession) { ds.setSetting(req.getParameter("var"), req.getParameter("val")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("setFileCleaner")) { if (validSession) { ds.setSetting("DelRegex", req.getParameter("orphan")); ds.setSetting("IfRegex", req.getParameter("parent")); ds.setSetting("IgnoreRegex", req.getParameter("ignore")); new Thread(new FileCleaner()).start(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getFileCleanerSettings")) { if (validSession) { bw.write(ds.getSetting("DelRegex", "") + "\n"); bw.write(ds.getSetting("IfRegex", "") + "\n"); bw.write(ds.getSetting("IgnoreRegex", "")); } else notAuthorized(resp, bw); } else if (cmd.equals("writeSrvSettings")) { if (validSession) { try { ds.setSettings(new JSONObject(req.getParameter("data"))); } catch (JSONException e) { throw new RuntimeException(e); } bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("readSrvSettings")) { if (validSession) bw.write(ds.readSettings().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("login")) { String pwd = ds.getSetting("password", ""); try { MessageDigest msg = MessageDigest.getInstance("MD5"); msg.update(req.getParameter("password").getBytes()); String userPwd = new String(msg.digest()); if (pwd.length() > 0 && pwd.equals(userPwd)) { bw.write("Success"); int key = new java.util.Random().nextInt(); resp.addHeader("SJQ-Session-Token", Integer.toString(key)); CLIENT_SESSION_KEYS.put(req.getRemoteAddr(), Integer.toString(key)); } else bw.write("BadPassword"); } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("editPwd")) { try { MessageDigest msg = MessageDigest.getInstance("MD5"); String curPwd = ds.getSetting("password", ""); String oldPwd = req.getParameter("old"); msg.update(oldPwd.getBytes()); oldPwd = new String(msg.digest()); msg.reset(); String newPwd = req.getParameter("new"); String confPwd = req.getParameter("conf"); if (!curPwd.equals(oldPwd)) bw.write("BadOld"); else if (!newPwd.equals(confPwd) || newPwd.length() == 0) bw.write("BadNew"); else { msg.update(newPwd.getBytes()); newPwd = new String(msg.digest()); ds.setSetting("password", newPwd); bw.write("Success"); } } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("runStats")) { if (validSession) { JSONObject o = new JSONObject(); try { o.put("last", Long.parseLong(ds.getSetting("LastRun", "0"))); o.put("next", Long.parseLong(ds.getSetting("NextRun", "0"))); bw.write(o.toString()); } catch (JSONException e) { bw.write(e.getLocalizedMessage()); } } else notAuthorized(resp, bw); } else if (cmd.equals("runQLoader")) { if (validSession) { Butler.wakeQueueLoader(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("delActiveQ")) { if (validSession) { if (TaskQueue.getInstance().delete(req.getParameter("m"), req.getParameter("t"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("clearActiveQ")) { if (validSession) { if (TaskQueue.getInstance().clear()) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("editPri")) { if (validSession) { try { int priority = Integer.parseInt(req.getParameter("p")); if (TaskQueue.getInstance().editPriority(req.getParameter("m"), req.getParameter("t"), priority)) bw.write("Success"); else bw.write("Failed"); } catch (NumberFormatException e) { bw.write("Failed"); } } else notAuthorized(resp, bw); } else if (cmd.equals("clearHistory")) { if (validSession) { if (ds.clear(Integer.parseInt(req.getParameter("t")))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("delHistRow")) { if (validSession) { if (ds.delTask(req.getParameter("m"), req.getParameter("t"), Integer.parseInt(req.getParameter("y")), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("rmLog")) { if (validSession) { String mid = req.getParameter("m"); String tid = req.getParameter("t"); String oid = req.getParameter("o"); if (mid.equals("0") && tid.equals("0") && oid.equals("null")) { bw.write("Failed: Can't delete server log file (sjq.log) while SageTV is running!"); } else if (ds.clearLog(mid, tid, oid)) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("qryMediaFile")) { if (validSession) { JSONArray jarr = new JSONArray(); MediaFileAPI.List mediaList = Butler.SageApi.mediaFileAPI.GetMediaFiles(ds.getMediaMask()); String qry = req.getParameter("q"); int max = Integer.parseInt(req.getParameter("m")); for (MediaFileAPI.MediaFile mf : mediaList) { if ((qry.matches("\\d+") && Integer.toString(mf.GetMediaFileID()).startsWith(qry)) || mf.GetMediaTitle().matches(".*" + Pattern.quote(qry) + ".*") || fileSegmentMatches(mf, qry)) { JSONObject o = new JSONObject(); try { o.put("value", mf.GetFileForSegment(0).getAbsolutePath()); String subtitle = null; if (mf.GetMediaFileAiring() != null && mf.GetMediaFileAiring().GetShow() != null) subtitle = mf.GetMediaFileAiring().GetShow().GetShowEpisode(); String display; if (subtitle != null && subtitle.length() > 0) display = mf.GetMediaTitle() + ": " + subtitle; else display = mf.GetMediaTitle(); o.put("display", mf.GetMediaFileID() + " - " + display); jarr.put(o); if (jarr.length() >= max) break; } catch (JSONException e) { e.printStackTrace(System.out); } } } bw.write(jarr.toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("debugMediaFile")) { if (validSession) { if (Butler.debugQueueLoader(req.getParameter("f"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("killTask")) { if (validSession) { if (TaskQueue.getInstance().killTask(req.getParameter("m"), req.getParameter("t"), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("keepAlive")) { bw.write(Boolean.toString(!TaskQueue.getInstance().isTaskKilled(req.getParameter("m"), req.getParameter("t"), req.getParameter("o")))); } bw.close(); DataStore.returnConnection(ds); LOG.info("Servlet POST request completed [" + (System.currentTimeMillis() - startTime) + "ms]"); return; } |
00
| Code Sample 1:
public LogoutHandler(String username, String token) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void bubbleSort(String[] a) { Collator myCollator = Collator.getInstance(); boolean switched = true; for (int pass = 0; pass < a.length - 1 && switched; pass++) { switched = false; for (int i = 0; i < a.length - pass - 1; i++) { if (myCollator.compare(a[i], a[i + 1]) > 0) { switched = true; String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } } |
11
| Code Sample 1:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
Code Sample 2:
public static void copyFile(String fromFile, String toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
00
| Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
Code Sample 2:
public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } |
11
| Code Sample 1:
private void copy(File source, File destination) { if (!destination.exists()) { destination.mkdir(); } File files[] = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { copy(files[i], new File(destination, files[i].getName())); } else { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { log.error("Could not write to " + destination.getAbsolutePath(), ioe); } } } } }
Code Sample 2:
public void run(String srcf, String dst) { final Path srcPath = new Path("./" + srcf); final Path desPath = new Path(dst); try { Path[] srcs = FileUtil.stat2Paths(hdfs.globStatus(srcPath), srcPath); OutputStream out = FileSystem.getLocal(conf).create(desPath); for (int i = 0; i < srcs.length; i++) { System.out.println(srcs[i]); InputStream in = hdfs.open(srcs[i]); IOUtils.copyBytes(in, out, conf, false); in.close(); } out.close(); } catch (IOException ex) { System.err.print(ex.getMessage()); } } |
11
| Code Sample 1:
public synchronized void receive(MessageEvent e) { switch(e.message.getType()) { case MessageTypes.QUIT: activeSessions--; break; case MessageTypes.SHUTDOWN_SERVER: activeSessions--; if (Options.password.trim().equals("")) { System.err.println("No default password set. Shutdown not allowed."); break; } if (e.message.get("pwhash") == null) { System.err.println("Shutdown message without password received. Shutdown not allowed."); break; } try { java.security.MessageDigest hash = java.security.MessageDigest.getInstance("SHA-1"); hash.update(Options.password.getBytes("UTF-8")); if (!java.security.MessageDigest.isEqual(hash.digest(), (byte[]) e.message.get("pwhash"))) { System.err.println("Wrong shutdown password. Shutdown not allowed."); break; } else { System.out.println("Valid shutdown password received."); } } catch (java.security.NoSuchAlgorithmException ex) { System.err.println("Password hash algorithm SHA-1 not supported by runtime."); break; } catch (UnsupportedEncodingException ex) { System.err.println("Password character encoding not supported."); break; } catch (Exception ex) { System.err.println("Unhandled exception occured. Shutdown aborted. Details:"); ex.printStackTrace(System.err); break; } if (activeSessions == 0) tStop(); else System.err.println("there are other active sessions - shutdown failed"); break; default: } }
Code Sample 2:
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)); } |
00
| Code Sample 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; }
Code Sample 2:
private boolean saveLOBDataToFileSystem() { if ("".equals(m_attachmentPathRoot)) { log.severe("no attachmentPath defined"); return false; } if (m_items == null || m_items.size() == 0) { setBinaryData(null); return true; } final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.newDocument(); final Element root = document.createElement("attachments"); document.appendChild(root); document.setXmlStandalone(true); for (int i = 0; i < m_items.size(); i++) { log.fine(m_items.get(i).toString()); File entryFile = m_items.get(i).getFile(); final String path = entryFile.getAbsolutePath(); log.fine(path + " - " + m_attachmentPathRoot); if (!path.startsWith(m_attachmentPathRoot)) { log.fine("move file: " + path); FileChannel in = null; FileChannel out = null; try { final File destFolder = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet()); if (!destFolder.exists()) { if (!destFolder.mkdirs()) { log.warning("unable to create folder: " + destFolder.getPath()); } } final File destFile = new File(m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); in = new FileInputStream(entryFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); if (entryFile.exists()) { if (!entryFile.delete()) { entryFile.deleteOnExit(); } } entryFile = destFile; } catch (IOException e) { e.printStackTrace(); log.severe("unable to copy file " + entryFile.getAbsolutePath() + " to " + m_attachmentPathRoot + File.separator + getAttachmentPathSnippet() + File.separator + entryFile.getName()); } finally { if (in != null && in.isOpen()) { in.close(); } if (out != null && out.isOpen()) { out.close(); } } } final Element entry = document.createElement("entry"); entry.setAttribute("name", getEntryName(i)); String filePathToStore = entryFile.getAbsolutePath(); filePathToStore = filePathToStore.replaceFirst(m_attachmentPathRoot.replaceAll("\\\\", "\\\\\\\\"), ATTACHMENT_FOLDER_PLACEHOLDER); log.fine(filePathToStore); entry.setAttribute("file", filePathToStore); root.appendChild(entry); } final Source source = new DOMSource(document); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final Result result = new StreamResult(bos); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.transform(source, result); final byte[] xmlData = bos.toByteArray(); log.fine(bos.toString()); setBinaryData(xmlData); return true; } catch (Exception e) { log.log(Level.SEVERE, "saveLOBData", e); } setBinaryData(null); return false; } |
11
| Code Sample 1:
public static Set<Street> getVias(String pURL) { Set<Street> result = new HashSet<Street>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniVia = "<calle>"; String finVia = "</calle>"; String iniCodVia = "<cv>"; String finCodVia = "</cv>"; String iniTipoVia = "<tv>"; String finTipoVia = "</tv>"; String iniNomVia = "<nv>"; String finNomVia = "</nv>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Street via; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniVia)) { via = new Street(); while ((str = br.readLine()) != null && !str.contains(finVia)) { if (str.contains(iniCodVia)) { ini = str.indexOf(iniCodVia) + iniCodVia.length(); fin = str.indexOf(finCodVia); via.setCodeStreet(Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniTipoVia)) { TypeStreet tipo = new TypeStreet(); if (!str.contains(finTipoVia)) tipo.setCodetpStreet(""); else { ini = str.indexOf(iniTipoVia) + iniTipoVia.length(); fin = str.indexOf(finTipoVia); tipo.setCodetpStreet(str.substring(ini, fin)); } tipo.setDescription(getDescripcionTipoVia(tipo.getCodetpStreet())); via.setTypeStreet(tipo); } if (str.contains(iniNomVia)) { ini = str.indexOf(iniNomVia) + iniNomVia.length(); fin = str.indexOf(finNomVia); via.setStreetName(str.substring(ini, fin).trim()); } } result.add(via); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
Code Sample 2:
public URL grabCover(String artist, String title) { if (idf.jCheckBox3.isSelected()) { println("Searching cover for: " + artist); artist = artist.trim(); URL url = null; int searchnumber = 0; try { URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist"); BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream())); println("" + yahoo); String inputLine; String line = ""; while ((inputLine = in.readLine()) != null) line += inputLine; boolean notfound = true; String cut = line; while (notfound) { String search = "<div class=\"album-name large\"><strong>Album:</strong> <a href=\""; if (line.indexOf(search) <= 0) { println("Artist was not found!"); in.close(); return null; } cut = cut.substring(cut.indexOf(search) + search.length()); String test = cut.substring(0, cut.indexOf("\"")); URL secondurl = new URL("http://www.gracenote.com" + test); println("" + secondurl); BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream())); String secinputLine; String secline = ""; while ((secinputLine = secin.readLine()) != null) secline += secinputLine; if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) { String secsearch = "<div class=\"album-image\"><img src=\""; String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length()); seccut = seccut.substring(0, seccut.indexOf("\"")); url = new URL("http://www.gracenote.com" + seccut); if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) { notfound = false; } } secin.close(); } in.close(); println(url.toString()); } catch (Exception e) { println("error " + e + "\n"); e.printStackTrace(); } return url; } else { return null; } } |
00
| Code Sample 1:
private void delay(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String url = request.getRequestURL().toString(); if (delayed.contains(url)) { delayed.remove(url); LOGGER.info(MessageFormat.format("Loading delayed resource at url = [{0}]", url)); chain.doFilter(request, response); } else { LOGGER.info("Returning resource = [LoaderApplication.swf]"); InputStream input = null; OutputStream output = null; try { input = getClass().getResourceAsStream("LoaderApplication.swf"); output = response.getOutputStream(); delayed.add(url); response.setHeader("Cache-Control", "no-cache"); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } } }
Code Sample 2:
static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; } |
11
| Code Sample 1:
public static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); }
Code Sample 2:
public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } } |
00
| Code Sample 1:
private void copyTemplates(ProjectPath pPath) { String sourceAntPath = pPath.sourceAntPath(); final String moduleName = projectOperations.getFocusedTopLevelPackage().toString(); logger.info("Module Name: " + moduleName); String targetDirectory = pPath.canonicalFileSystemPath(projectOperations); logger.info("Moving into target Directory: " + targetDirectory); if (!targetDirectory.endsWith("/")) { targetDirectory += "/"; } if (!fileManager.exists(targetDirectory)) { fileManager.createDirectory(targetDirectory); } System.out.println("Target Directory: " + pPath.sourceAntPath()); String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath); Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path); Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'"); if (urls.isEmpty()) { logger.info("URLS are empty stopping..."); } for (URL url : urls) { logger.info("Stepping into " + url.toExternalForm()); String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1); fileName = fileName.replace("-template", ""); String targetFilename = targetDirectory + fileName; logger.info("Handling " + targetFilename); if (!fileManager.exists(targetFilename)) { try { logger.info("Copied file"); String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream())); logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage()); logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations)); String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString(); input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage); input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage()); input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName()); input = input.replace("__ENTITY_NAME__", entityName); MutableFile mutableFile = fileManager.createFile(targetFilename); FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream()); } catch (IOException ioe) { throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe); } } } }
Code Sample 2:
public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } } |
00
| Code Sample 1:
public void update(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String exp = channel.getExtendParent(); String path = channel.getPath(); try { String sqlStr = "UPDATE t_ip_channel SET id=?,name=?,description=?,ascii_name=?,site_id=?,type=?,data_url=?,template_id=?,use_status=?,order_no=?,style=?,creator=?,create_date=?,refresh_flag=?,page_num=? where channel_path=?"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(path, exp, connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); selfDefineAdd(selfDefinePath, channel, connection, preparedStatement); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, channel.getChannelID()); preparedStatement.setString(2, channel.getName()); preparedStatement.setString(3, channel.getDescription()); preparedStatement.setString(4, channel.getAsciiName()); preparedStatement.setInt(5, channel.getSiteId()); preparedStatement.setString(6, channel.getChannelType()); preparedStatement.setString(7, channel.getDataUrl()); if (channel.getTemplateId() == null || channel.getTemplateId().trim().equals("")) preparedStatement.setNull(8, Types.INTEGER); else preparedStatement.setInt(8, Integer.parseInt(channel.getTemplateId())); preparedStatement.setString(9, channel.getUseStatus()); preparedStatement.setInt(10, channel.getOrderNo()); preparedStatement.setString(11, channel.getStyle()); preparedStatement.setInt(12, channel.getCreator()); preparedStatement.setTimestamp(13, (Timestamp) channel.getCreateDate()); preparedStatement.setString(14, channel.getRefresh()); preparedStatement.setInt(15, channel.getPageNum()); preparedStatement.setString(16, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); int resID = channel.getChannelID() + Const.CHANNEL_TYPE_RES; StructResource sr = new StructResource(); sr.setResourceID(Integer.toString(resID)); sr.setOperateID(Integer.toString(1)); sr.setOperateTypeID(Const.OPERATE_TYPE_ID); sr.setTypeID(Const.RES_TYPE_ID); StructAuth sa = new AuthorityManager().getExternalAuthority(sr); int authID = sa.getAuthID(); if (authID == 0) { String resName = channel.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); } } catch (SQLException ex) { connection.rollback(); log.error("����Ƶ��ʧ�ܣ�channelPath=" + channel.getPath()); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
Code Sample 2:
@SuppressWarnings("unchecked") private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException { String uri = url + path; HttpRequest request; if (body == null) { BasicHttpRequest r = new BasicHttpRequest(method, uri); request = r; } else { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri); StringEntity entity; try { entity = new StringEntity(JSON.encode(body), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } entity.setContentType("application/json; charset=utf-8"); r.setEntity(entity); request = r; } HttpClient client = getClient(); try { HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); HttpEntity entity = response.getEntity(); if (entity == null) return null; String contentType = entity.getContentType().getValue(); boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;")); String result = null; InputStream in = entity.getContent(); try { Reader r = new InputStreamReader(in, "UTF-8"); StringBuilder sb = new StringBuilder(); char[] buf = new char[256]; int read; while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read); r.close(); result = sb.toString(); } finally { try { in.close(); } catch (Exception e) { } } int code = response.getStatusLine().getStatusCode(); if (code >= 400) { if (isJson) { try { throw deserializeException((Map<String, Object>) JSON.decode(result)); } catch (IllegalArgumentException e) { throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e); } } if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result); } if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result); try { return (Map<String, Object>) JSON.decode(result, recognizers); } catch (Exception e) { throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e); } } catch (ClientProtocolException e) { throw new IOException(e); } } |
11
| Code Sample 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; }
Code Sample 2:
public void copyFile() throws Exception { SmbFile file = new SmbFile("smb://elsa:elsa@elsa/Elsa/Desktop/Ficheiros2/04-04-2066/How To Make a Flash Preloader.doc"); println("length: " + file.length()); SmbFileInputStream in = new SmbFileInputStream(file); println("available: " + in.available()); File dest = new File("C:\\Documents and Settings\\Carlos\\Desktop\\Flash Preloader.doc"); FileOutputStream out = new FileOutputStream(dest); int buffer_length = 1024; byte[] buffer = new byte[buffer_length]; while (true) { int bytes_read = in.read(buffer, 0, buffer_length); if (bytes_read <= 0) { break; } out.write(buffer, 0, bytes_read); } in.close(); out.close(); println("done."); } |
00
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static byte[] SHA1byte(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; } |
11
| Code Sample 1:
private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; }
Code Sample 2:
public long copyDirAllFilesToDirectoryRecursive(String baseDirStr, String destDirStr, boolean copyOutputsRtIDsDirs) 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(); } if (entryFile.isDirectory()) { boolean enableCopyDir = false; if (copyOutputsRtIDsDirs) { enableCopyDir = true; } else { if (entryFile.getParentFile().getName().equals("outputs")) { enableCopyDir = false; } else { enableCopyDir = true; } } if (enableCopyDir) { plussQuotaSize += this.copyDirAllFilesToDirectoryRecursive(baseDirStr + sep + entryName, destDirStr + sep + entryName, copyOutputsRtIDsDirs); } } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; } |
11
| Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } } |
11
| Code Sample 1:
private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } }
Code Sample 2:
public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } } |
00
| Code Sample 1:
private void insertService(String table, int type) { Connection con = null; log.info(""); log.info("正在生成" + table + "的服务。。。。。。。"); try { con = DODataSource.getDefaultCon(); con.setAutoCommit(false); Statement stmt = con.createStatement(); Statement stmt2 = con.createStatement(); String serviceUid = UUIDHex.getInstance().generate(); DOBO bo = DOBO.getDOBOByName(StringUtil.getDotName(table)); List props = new ArrayList(); StringBuffer mainSql = null; String name = ""; String l10n = ""; String prefix = StringUtil.getDotName(table); Boolean isNew = null; switch(type) { case 1: name = prefix + ".insert"; l10n = name; props = bo.retrieveProperties(); mainSql = getInsertSql(props, table); isNew = Boolean.TRUE; break; case 2: name = prefix + ".update"; l10n = name; props = bo.retrieveProperties(); mainSql = this.getModiSql(props, table); isNew = Boolean.FALSE; break; case 3: DOBOProperty property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); System.out.println("BOBOBO::::::" + bo); System.out.println("Property::::::" + property); if (property == null) { return; } name = prefix + ".delete"; l10n = name; props.add(property); mainSql = new StringBuffer("delete from ").append(table).append(" where objuid = ?"); break; case 4: property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); if (property == null) { return; } name = prefix + ".browse"; l10n = name; props.add(property); mainSql = new StringBuffer("select * from ").append(table).append(" where objuid = ?"); break; case 5: name = prefix + ".list"; l10n = name; mainSql = new StringBuffer("select * from ").append(table); } this.setParaLinkBatch(props, stmt2, serviceUid, isNew); StringBuffer aSql = new StringBuffer("insert into DO_Service(objuid,l10n,name,bouid,mainSql) values(").append("'").append(serviceUid).append("','").append(l10n).append("','").append(name).append("','").append(this.getDOBOUid(table)).append("','").append(mainSql).append("')"); log.info("Servcice's Sql:" + aSql.toString()); stmt.executeUpdate(aSql.toString()); stmt2.executeBatch(); con.commit(); } catch (SQLException ex) { try { con.rollback(); } catch (SQLException ex2) { ex2.printStackTrace(); } ex.printStackTrace(); } finally { try { if (!con.isClosed()) { con.close(); } } catch (SQLException ex1) { ex1.printStackTrace(); } } }
Code Sample 2:
private boolean verifyPassword(String password, byte[] hash) { boolean returnValue = false; try { MessageDigest msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.update(password.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); returnValue = Arrays.equals(hash, digest); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } return returnValue; } |
11
| Code Sample 1:
public static String md5(String s) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); return prepad(output, 32, '0'); } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm. we are sunk."); return s; } }
Code Sample 2:
public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } |
11
| Code Sample 1:
public static File copyFile(String path) { File src = new File(path); File dest = new File(src.getName()); 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; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; } |
00
| Code Sample 1:
public static void doHttpPost(String urlName, byte[] data, String contentType, String cookieData) throws InteropException { URL url = getAccessURL(urlName); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Cookie", cookieData); connection.setRequestProperty("Content-type", contentType); connection.setRequestProperty("Content-length", "" + data.length); OutputStream stream = connection.getOutputStream(); stream.write(data); stream.flush(); stream.close(); connection.connect(); InputStream inputStream = connection.getInputStream(); inputStream.close(); } catch (IOException ex) { throw new InteropException("Error POSTing to " + urlName, ex); } }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); } |
00
| Code Sample 1:
private List<String> getHashesFrom(String webPage) { Vector<String> out = new Vector(); try { URL url = new URL(webPage); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = r.readLine()) != null) { out.add(line); } } catch (Exception X) { return null; } return out; }
Code Sample 2:
public String[] getFriends() { InputStream is = null; String[] answer = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { answer = new String[1]; answer[0] = "none"; return answer; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray json = new JSONArray(result); answer = new String[json.length()]; for (int i = 0; i < json.length(); i++) { JSONObject jsonId = json.getJSONObject(i); answer[i] = jsonId.getString("uid"); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return answer; } |
00
| Code Sample 1:
public InputStream open(String filename) throws IOException { URL url = TemplateLoader.resolveURL("cms/" + filename); if (url != null) return url.openStream(); url = TemplateLoader.resolveURL(filename); if (url != null) return url.openStream(); return null; }
Code Sample 2:
public boolean write(Node node, LSOutput output) throws LSException { OutputStream out = output.getByteStream(); try { if (out == null) { String systemId = output.getSystemId(); try { URL url = new URL(systemId); URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof HttpURLConnection) { ((HttpURLConnection) connection).setRequestMethod("PUT"); } out = connection.getOutputStream(); } catch (MalformedURLException e) { File file = new File(systemId); out = new FileOutputStream(file); } } serialize(node, out); out.flush(); return true; } catch (IOException e) { throw new DomLSException(LSException.SERIALIZE_ERR, e); } } |
11
| Code Sample 1:
public static String generateToken(ClientInfo clientInfo) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); Random rand = new Random(); String random = clientInfo.getIpAddress() + ":" + clientInfo.getPort() + ":" + rand.nextInt(); md5.update(random.getBytes()); String token = toHexString(md5.digest((new Date()).toString().getBytes())); clientInfo.setToken(token); return token; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; } |
00
| Code Sample 1:
protected String getPageText(final String url) { StringBuilder b = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line = null; while ((line = reader.readLine()) != null) { b.append(line).append('\n'); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } return b.toString(); }
Code Sample 2:
public static String MD5(String text) throws ProducteevSignatureException { try { MessageDigest md; md = MessageDigest.getInstance(ALGORITHM); byte[] md5hash; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nsae) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, nsae); } catch (UnsupportedEncodingException e) { throw new ProducteevSignatureException("No such algorithm : " + ALGORITHM, e); } } |
11
| Code Sample 1:
public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } }
Code Sample 2:
private static boolean prepareQualifyingFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "qualifying.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line.substring(0, line.indexOf(","))).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } |
11
| Code Sample 1:
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
Code Sample 2:
public static String encrypt(String key) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(key.getBytes()); byte hash[] = md5.digest(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String temp = Integer.toHexString(0xFF & hash[i]); if (temp.length() == 1) temp = "0" + temp; buffer.append(temp); } return buffer.toString(); } |
00
| Code Sample 1:
public String getHash(String type, String text, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance(type); byte[] hash = new byte[md.getDigestLength()]; if (!salt.isEmpty()) { md.update(salt.getBytes("iso-8859-1"), 0, salt.length()); } md.update(text.getBytes("iso-8859-1"), 0, text.length()); hash = md.digest(); return convertToHex(hash); }
Code Sample 2:
private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); } |
11
| Code Sample 1:
public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) { this.logLevel = logLevel; this.displayLogLevel = displayLogLevel; if (null != logPath) { logFile = new File(logPath, "current.log"); log(LOG_LEVEL.DEBUG, "FileLog", "Initialising logfile " + logFile.getAbsolutePath() + " ."); try { if (logFile.exists()) { if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + ".log"))) { File newFile = new File(logPath, System.currentTimeMillis() + ".log"); if (newFile.exists()) { log(LOG_LEVEL.WARN, "FileLog", "The file (" + newFile.getAbsolutePath() + newFile.getName() + ") already exists, will overwrite it."); newFile.delete(); } newFile.createNewFile(); FileInputStream inStream = new FileInputStream(logFile); FileOutputStream outStream = new FileOutputStream(newFile); byte buffer[] = null; int offSet = 0; while (inStream.read(buffer, offSet, 2048) != -1) { outStream.write(buffer); offSet += 2048; } inStream.close(); outStream.close(); logFile.delete(); logFile = new File(logPath, "current.log"); } } logFile.createNewFile(); } catch (IOException e) { logFile = null; } } else { logFile = null; } } |
11
| Code Sample 1:
public static void copyFile(final File sourceFile, final 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(); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
11
| Code Sample 1:
public Boolean compress(String sSourceDir, ArrayList<String> aFiles, String sDestinationFilename) { logger.debug("compress(%s, %s, %s)", sSourceDir, aFiles, sDestinationFilename); BufferedInputStream oOrigin = null; FileOutputStream oDestination; ZipOutputStream oOutput = null; Iterator<String> oIterator; byte[] aData; try { oDestination = new FileOutputStream(sDestinationFilename); oOutput = new ZipOutputStream(new BufferedOutputStream(oDestination)); aData = new byte[BUFFER_SIZE]; oIterator = aFiles.iterator(); while (oIterator.hasNext()) { try { String sFilename = (String) oIterator.next(); FileInputStream fisInput = new FileInputStream(sSourceDir + File.separator + sFilename); oOrigin = new BufferedInputStream(fisInput, BUFFER_SIZE); ZipEntry oEntry = new ZipEntry(sFilename.replace('\\', '/')); oOutput.putNextEntry(oEntry); int iCount; while ((iCount = oOrigin.read(aData, 0, BUFFER_SIZE)) != -1) oOutput.write(aData, 0, iCount); } finally { StreamHelper.close(oOrigin); } } } catch (Exception oException) { logger.error(oException.getMessage(), oException); return false; } finally { StreamHelper.close(oOutput); } return true; }
Code Sample 2:
public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } } |
11
| Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
@Override public 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; }
Code Sample 2:
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(); } |
00
| Code Sample 1:
public static final InputStream openStream(Bundle bundle, IPath file, boolean localized) throws IOException { URL url = null; if (!localized) { url = findInPlugin(bundle, file); if (url == null) url = findInFragments(bundle, file); } else { url = FindSupport.find(bundle, file); } if (url != null) return url.openStream(); throw new IOException("Cannot find " + file.toString()); }
Code Sample 2:
public static String md5(String s) { try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(s.getBytes()); return new BigInteger(1, digester.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } |
11
| Code Sample 1:
public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
Code Sample 2:
private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); } |
11
| Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } } |
00
| Code Sample 1:
public void sendMessage(Message m) throws IOException { URL url = new URL(strURL); urlcon = (HttpURLConnection) url.openConnection(); urlcon.setUseCaches(false); urlcon.setDefaultUseCaches(false); urlcon.setDoOutput(true); urlcon.setDoInput(true); urlcon.setRequestProperty("Content-type", "application/octet-stream"); urlcon.setAllowUserInteraction(false); HttpURLConnection.setDefaultAllowUserInteraction(false); urlcon.setRequestMethod("POST"); ObjectOutputStream oos = new ObjectOutputStream(urlcon.getOutputStream()); oos.writeObject(m); oos.flush(); oos.close(); }
Code Sample 2:
public static int sendMessage(String auth_token, String registrationId, String message) throws IOException { StringBuilder postDataBuilder = new StringBuilder(); postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId); postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0"); postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, UTF8)); byte[] postData = postDataBuilder.toString().getBytes(UTF8); URL url = new URL(C2DM_SEND_ENDPOINT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(postData.length)); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token); OutputStream out = conn.getOutputStream(); out.write(postData); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpServletResponse.SC_UNAUTHORIZED || responseCode == HttpServletResponse.SC_FORBIDDEN) { AuthenticationUtil.getTokenFromServer(Util.USER, Util.PASSWORD); sendMessage(auth_token, registrationId, message); } String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH); if (updatedAuthToken != null && !auth_token.equals(updatedAuthToken)) { Util.updateToken(updatedAuthToken); } return responseCode; } |
00
| Code Sample 1:
public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { URL url = configuration.get(publicID); try { if (url != null) return url.openStream(); } catch (IOException ex) { throw new XMLStreamException(String.format("Unable to open stream for resource %s: %s", url, InternalUtils.toMessage(ex)), ex); } return null; }
Code Sample 2:
public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } } |
11
| Code Sample 1:
public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } }
Code Sample 2:
public static String crypt(String passwd, boolean pad) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(passwd.getBytes()); String c = new String(sha.digest()); return toNumeric(c, pad, true); } catch (java.security.NoSuchAlgorithmException e) { Log.error(Login.class, "couldn't crypt()", e); return ""; } } |
00
| Code Sample 1:
public void transform(String style, String spec, OutputStream out) throws IOException { URL url = new URL(rootURL, spec); InputStream in = new PatchXMLSymbolsStream(new StripDoctypeStream(url.openStream())); transform(style, in, out); in.close(); }
Code Sample 2:
public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; } |
11
| Code Sample 1:
private boolean keysMatch(String keyNMinusOne, String keyN) { boolean match = false; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(keyNMinusOne.getBytes()); byte[] hashedBytes = digest.digest(); String encodedHashedKey = new String(com.Ostermiller.util.Base64.encode(hashedBytes)); match = encodedHashedKey.equals(keyN); } catch (NoSuchAlgorithmException e) { } return match; }
Code Sample 2:
private static String doHash(String frase, String algorithm) { try { String ret; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(frase.getBytes()); BigInteger bigInt = new BigInteger(1, md.digest()); ret = bigInt.toString(16); return ret; } catch (NoSuchAlgorithmException e) { return null; } } |
11
| Code Sample 1:
public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
Code Sample 2:
public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; } |
00
| Code Sample 1:
@Test public void test20_badSmtp() throws Exception { Db db = DbConnection.defaultCieDbRW(); try { db.begin(); oldSmtp = Config.getProperty(db, "com.entelience.mail.MailHelper.hostName", "localhost"); oldSupport = Config.getProperty(db, "com.entelience.esis.feature.SupportNotifier", false); Config.setProperty(db, "com.entelience.mail.MailHelper.hostName", "127.0.10.1", 1); Config.setProperty(db, "com.entelience.esis.feature.SupportNotifier", "true", 1); PreparedStatement pst = db.prepareStatement("DELETE FROM t_client_errors"); db.executeUpdate(pst); db.commit(); } catch (Exception e) { db.rollback(); } finally { db.safeClose(); } }
Code Sample 2:
@Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; } |
11
| Code Sample 1:
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
Code Sample 2:
public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
protected void innerProcess(CrawlURI curi) throws InterruptedException { if (!curi.isHttpTransaction()) { return; } if (!TextUtils.matches("^text.*$", curi.getContentType())) { return; } long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue(); try { maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue(); } catch (AttributeNotFoundException e) { logger.severe("Missing max-size-bytes attribute when processing " + curi.toString()); } if (maxsize < curi.getContentSize() && maxsize > -1) { return; } String regexpr = ""; try { regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR); } catch (AttributeNotFoundException e2) { logger.severe("Missing strip-reg-exp when processing " + curi.toString()); return; } ReplayCharSequence cs = null; try { cs = curi.getHttpRecorder().getReplayCharSequence(); } catch (Exception e) { curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage()); logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName()); return; } MessageDigest digest = null; try { try { digest = MessageDigest.getInstance(SHA1); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); return; } digest.reset(); String s = null; if (regexpr.length() == 0) { s = cs.toString(); } else { Matcher m = TextUtils.getMatcher(regexpr, cs); s = m.replaceAll(" "); TextUtils.recycleMatcher(m); } digest.update(s.getBytes()); byte[] newDigestValue = digest.digest(); if (logger.isLoggable(Level.FINEST)) { logger.finest("Recalculated content digest for " + curi.toString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue)); } curi.setContentDigest(SHA1, newDigestValue); } finally { if (cs != null) { try { cs.close(); } catch (IOException ioe) { logger.warning(TextUtils.exceptionToString("Failed close of ReplayCharSequence.", ioe)); } } } }
Code Sample 2:
public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception ex) { throw new RuntimeException(ex); } } |
11
| Code Sample 1:
private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } }
Code Sample 2:
private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; } |
00
| Code Sample 1:
public static List<String> list() throws IOException { List<String> providers = new ArrayList<String>(); Enumeration<URL> urls = ClassLoader.getSystemResources("sentrick.classifiers"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); String provider = null; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); while ((provider = in.readLine()) != null) { provider = provider.trim(); if (provider.length() > 0) providers.add(provider); } in.close(); } return providers; }
Code Sample 2:
public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); } |
00
| Code Sample 1:
protected int getResponseCode(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); return con.getResponseCode(); } finally { con.disconnect(); } }
Code Sample 2:
public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; } |
11
| Code Sample 1:
public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
Code Sample 2:
private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } |
11
| Code Sample 1:
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } }
Code Sample 2:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } } |
11
| Code Sample 1:
private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } }
Code Sample 2:
public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } } |
11
| Code Sample 1:
private void writeResponse(final Collection<? extends Resource> resources, final HttpServletResponse response) throws IOException { for (final Resource resource : resources) { InputStream in = null; try { in = resource.getInputStream(); final OutputStream out = response.getOutputStream(); final long bytesCopied = IOUtils.copyLarge(in, out); if (bytesCopied < 0L) throw new StreamCorruptedException("Bad number of copied bytes (" + bytesCopied + ") for resource=" + resource.getFilename()); if (logger.isDebugEnabled()) logger.debug("writeResponse(" + resource.getFile() + ") copied " + bytesCopied + " bytes"); } finally { if (in != null) in.close(); } } }
Code Sample 2:
@Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } } |
00
| Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public Component loadComponent(URI uri, URI origuri) throws ComponentException { try { Component comp = null; InputStream is = null; java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { if (url.getProtocol().equals("ftp")) is = ftpHandler.getInputStream(url); else { java.net.URLConnection conn = url.openConnection(); conn.connect(); is = conn.getInputStream(); } } catch (IOException e) { if (is != null) is.close(); throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + e.getMessage()); } try { comp = componentIO.loadComponent(origuri, uri, is, isSavable(uri)); } catch (ComponentException e) { if (is != null) is.close(); throw new ComponentException("Error loading component " + origuri + " from " + url + ":\n " + e.getMessage()); } is.close(); return comp; } catch (IOException ioe) { Tracer.debug("didn't manage to close inputstream...."); return null; } } |
00
| Code Sample 1:
@Nullable @Override public InputSource resolveEntity(final String publicId, final String systemId) throws IOException { if (systemId.endsWith(".xml")) { return null; } InputSource inputSource = null; final URL url = IOUtils.getResource(new File("system/dtd"), PATTERN_DIRECTORY_PART.matcher(systemId).replaceAll("")); final InputStream inputStream = url.openStream(); try { final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); try { inputSource = new InputSource(bufferedInputStream); } finally { if (inputSource == null) { bufferedInputStream.close(); } } } finally { if (inputSource == null) { inputStream.close(); } } return inputSource; }
Code Sample 2:
private static void run(Display display, int x) { Shell shell = new Shell(display); shell.setBounds(0, 0, 350, 350); shell.setLayout(new FillLayout(SWT.VERTICAL)); ERDiagramEditPartFactory editPartFactory = new ERDiagramEditPartFactory(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.setControl(new FigureCanvas(shell)); ScalableFreeformRootEditPart rootEditPart = new PagableFreeformRootEditPart(diagram); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(editPartFactory); viewer.setContents(diagram); viewer.getContents().refresh(); shell.pack(); shell.open(); int count = 0; while (count < x) { if (!display.readAndDispatch()) { try { Thread.sleep(1000); count++; } catch (InterruptedException e) { e.printStackTrace(); } } } viewer.getContents().deactivate(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.