label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException { try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.update(string.getBytes(encoding)); byte[] encodedPassword = digest.digest(); return new BigInteger(1, encodedPassword).toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Code Sample 2: private String readLine(final String urlStr) { BufferedReader reader; String line = null; try { URL url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); } catch (MalformedURLException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } return line; }
00
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: public static Image readImage(URL url, ImageMimeType type, int page) throws IOException { if (type.javaNativeSupport()) { return ImageIO.read(url.openStream()); } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) { com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url); doc.setAsync(false); DjVuPage[] p = new DjVuPage[1]; int size = doc.size(); if ((page != 0) && (page >= size)) { page = 0; } p[0] = doc.getPage(page, 1, true); p[0].setAsync(false); DjVuImage djvuImage = new DjVuImage(p, true); Rectangle pageBounds = djvuImage.getPageBounds(0); Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height)); if (images.length == 1) { Image img = images[0]; return img; } else return null; } else if (type.equals(ImageMimeType.PDF)) { PDDocument document = null; try { document = PDDocument.load(url.openStream()); int resolution = 96; List<?> pages = document.getDocumentCatalog().getAllPages(); PDPage pdPage = (PDPage) pages.get(page); BufferedImage image = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, resolution); return image; } finally { if (document != null) { document.close(); } } } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'"); }
00
Code Sample 1: @Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
11
Code Sample 1: public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); } Code Sample 2: public void process(String t) { try { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(t.getBytes()); callback.display(null, digestToHexString(md5.digest())); } catch (Exception ex) { callback.display(null, "[failed]"); } }
11
Code Sample 1: public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } } Code Sample 2: private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException { final File dstFolder = dstFile.getParentFile(); dstFolder.mkdirs(); if (!dstFolder.exists()) { throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath()); } final InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(dstFile); if (gzipContent) { out = new GZIPOutputStream(out); } try { final byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { in.close(); out.close(); } }
00
Code Sample 1: public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; } 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; }
00
Code Sample 1: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } Code Sample 2: public static void updateTableData(Connection dest, TableMetaData tableMetaData, Row r) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "UPDATE " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " SET "; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + " = ? ,"; } sql = sql.substring(0, sql.length() - 1); sql += " WHERE "; for (String pkColumnName : tableMetaData.getPkColumns()) { sql += pkColumnName + " = ? AND "; } sql = sql.substring(0, sql.length() - 4); System.out.println("UPDATE: " + sql); ps = dest.prepareStatement(sql); int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { ps.setObject(param, r.getRowData().get(columnName)); } param++; } for (String pkColumnName : tableMetaData.getPkColumns()) { ps.setObject(param, r.getRowData().get(pkColumnName)); param++; } if (ps.executeUpdate() != 1) { dest.rollback(); throw new Exception("Erro no update"); } ps.clearParameters(); dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
00
Code Sample 1: public static void main(String[] args) { FileInputStream fr = null; FileOutputStream fw = null; BufferedInputStream br = null; BufferedOutputStream bw = null; try { fr = new FileInputStream("D:/5.xls"); fw = new FileOutputStream("c:/Dxw.java"); br = new BufferedInputStream(fr); bw = new BufferedOutputStream(fw); int read = br.read(); while (read != -1) { bw.write(read); read = br.read(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: private static void loadEmoticons() { emoticons = new Hashtable(); URL url = ChatPanel.class.getResource("/resources/text/emoticon.properties"); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = br.readLine()) != null) { if (line.trim().length() == 0 || line.charAt(0) == '#') continue; int i0 = line.indexOf('='); if (i0 != -1) { String key = line.substring(0, i0).trim(); String value = line.substring(i0 + 1).trim(); value = StringUtil.replaceString(value, "\\n", "\n"); URL eUrl = ChatPanel.class.getResource("/resources/emoticon/" + value); if (eUrl != null) emoticons.put(key, new ImageIcon(eUrl)); } } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { } } } }
00
Code Sample 1: @Override public List<String> getNamedEntitites(String sentence) { List<String> namedEntities = new ArrayList<String>(); try { URL url = new URL(SERVICE_URL + "text=" + URLEncoder.encode(sentence, "UTF-8") + "&confidence=" + CONFIDENCE + "&support=" + SUPPORT); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "application/json"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); JSONObject json = new JSONObject(sb.toString()); if (!json.isNull("Resources")) { JSONArray array = json.getJSONArray("Resources"); JSONObject entityObject; for (int i = 0; i < array.length(); i++) { entityObject = array.getJSONObject(i); System.out.println("Entity: " + entityObject.getString("@surfaceForm")); System.out.println("DBpedia URI: " + entityObject.getString("@URI")); System.out.println("Types: " + entityObject.getString("@types")); namedEntities.add(entityObject.getString("@surfaceForm")); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return namedEntities; } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } 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: private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
00
Code Sample 1: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnRegister) { Error.log(6002, "Bot�o cadastrar pressionado por " + login + "."); if (nameUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo nome requerido"); nameUser.setFocusable(true); return; } if (loginUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo login requerido"); loginUser.setFocusable(true); return; } String group = ""; if (groupUser.getSelectedIndex() == 0) group = "admin"; else if (groupUser.getSelectedIndex() == 1) group = "user"; else { JOptionPane.showMessageDialog(null, "Campo grupo n�o selecionado"); return; } if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int i = 1; for (i = 1; i < password1.length(); i++) { if (passwordUser1.getPassword()[i] != c) { break; } c = passwordUser1.getPassword()[i]; } if (i == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } ResultSet rs; Statement stmt; String sql; String result = ""; sql = "select login from Usuarios where login='" + loginUser.getText() + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("login"); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (result.compareTo("") != 0) { JOptionPane.showMessageDialog(null, "Login " + result + " j� existe"); loginUser.setText(""); loginUser.setFocusable(true); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } sql = "insert into Usuarios (login,password,tries_personal,tries_one_use," + "grupo,description) values " + "('" + loginUser.getText() + "','" + outputDigest + "',0,0,'" + group + "','" + nameUser.getText() + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(loginUser.getText() + ".txt", false)); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + loginUser.getText() + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + loginUser.getText() + " foi cadastrado com sucesso."); dispose(); } if (e.getSource() == btnCancel) { Error.log(6003, "Bot�o voltar de cadastrar para o menu principal pressionado por " + login + "."); dispose(); } }
00
Code Sample 1: protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String realUrl = "http:/" + request.getPathInfo(); if (request.getQueryString() != null) { realUrl += "?" + request.getQueryString(); } URL url = new URL(realUrl); URLConnection connection = url.openConnection(); HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); } boolean hasContent = false; Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String header = (String) headers.nextElement(); if ("content-type".equals(header.toLowerCase())) hasContent = true; Enumeration values = request.getHeaders(header); while (values.hasMoreElements()) { String value = (String) values.nextElement(); if (value != null) { connection.addRequestProperty(header, value); } } } try { connection.setDoInput(true); if (hasContent) { InputStream proxyRequest = request.getInputStream(); connection.setDoOutput(true); IO.copy(proxyRequest, connection.getOutputStream()); } connection.connect(); } catch (Exception e) { context.log("proxy", e); } InputStream proxyResponse = null; int code = 500; if (http != null) { proxyResponse = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); } if (proxyResponse == null) { try { proxyResponse = connection.getInputStream(); } catch (Exception e) { if (http != null) proxyResponse = http.getErrorStream(); context.log("stream", e); } } int i = 0; String header = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); while (header != null || value != null) { if (header != null && value != null) { response.addHeader(header, value); } ++i; header = connection.getHeaderFieldKey(i); value = connection.getHeaderField(i); } if (proxyResponse != null) { IO.copy(proxyResponse, response.getOutputStream()); } } Code Sample 2: public static String getHighlightBaseLib() throws Exception { StringBuffer highlightKey = new StringBuffer(); highlightKey.append("<c color=\"" + COLOR_BASELIB + "\">\n\t"); URL url = AbstractRunner.class.getResource("baselib.js"); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is, "UTF-8"); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { if (tmp.indexOf("function") > -1) { highlightKey.append("<w>" + (tmp.substring(tmp.indexOf("function") + 8, tmp.indexOf("(")).trim()) + "</w>\n\t"); } } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } highlightKey.append("</c>"); return highlightKey.toString(); }
00
Code Sample 1: public static void compressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml", ".xml.gz")); System.out.println(" Compressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); FileInputStream fileinputstream = new FileInputStream(file); GZIPOutputStream gzipoutputstream = new GZIPOutputStream(new FileOutputStream(target)); byte abyte0[] = new byte[1024]; int i; while ((i = fileinputstream.read(abyte0)) != -1) gzipoutputstream.write(abyte0, 0, i); fileinputstream.close(); gzipoutputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Compressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); } Code Sample 2: public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile, boolean overwrite) throws IOException, DirNotFoundException, FileNotFoundException, FileExistsAlreadyException { File destDir = new File(destFile.getParent()); if (!destDir.exists()) { throw new DirNotFoundException(destDir.getAbsolutePath()); } if (!sourceFile.exists()) { throw new FileNotFoundException(sourceFile.getAbsolutePath()); } if (!overwrite && destFile.exists()) { throw new FileExistsAlreadyException(destFile.getAbsolutePath()); } FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[8 * 1024]; int count = 0; do { out.write(buffer, 0, count); count = in.read(buffer, 0, buffer.length); } while (count != -1); in.close(); out.close(); } Code Sample 2: public void postProcess() throws StopWriterVisitorException { shpWriter.postProcess(); try { FileChannel fcinShp = new FileInputStream(fTemp).getChannel(); FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel(); DriverUtilities.copy(fcinShp, fcoutShp); File shxFile = SHP.getShxFile(fTemp); FileChannel fcinShx = new FileInputStream(shxFile).getChannel(); FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel(); DriverUtilities.copy(fcinShx, fcoutShx); File dbfFile = getDataFile(fTemp); short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset()); RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); shxFile.delete(); dbfFile.delete(); reload(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (ReloadDriverException e) { throw new StopWriterVisitorException(getName(), e); } }
11
Code Sample 1: public static void reset() throws Exception { Session session = DataStaticService.getHibernateSessionFactory().openSession(); try { Connection connection = session.connection(); try { Statement statement = connection.createStatement(); try { statement.executeUpdate("delete from Tag"); connection.commit(); } finally { statement.close(); } } catch (HibernateException e) { connection.rollback(); throw new Exception(e); } catch (SQLException e) { connection.rollback(); throw new Exception(e); } } catch (SQLException e) { throw new Exception(e); } finally { session.close(); } } Code Sample 2: @Override public boolean saveCart(Carrito cart, boolean completado, String date, String formPago) { Connection conexion = null; PreparedStatement insertHistorial = null; PreparedStatement insertCarrito = null; boolean exito = false; try { conexion = pool.getConnection(); conexion.setAutoCommit(false); insertHistorial = conexion.prepareStatement("INSERT INTO " + nameBD + ".HistorialCarritos VALUES (?,?,?,?,?,?)"); insertHistorial.setString(1, cart.getUser()); insertHistorial.setString(2, cart.getCodigo()); insertHistorial.setString(3, date); insertHistorial.setDouble(4, cart.getPrecio()); insertHistorial.setString(5, formPago); insertHistorial.setBoolean(6, completado); int filasAfectadas = insertHistorial.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); } else { insertCarrito = conexion.prepareStatement("INSERT INTO " + nameBD + ".Carritos VALUES (?,?,?,?,?)"); Iterator<String> iteradorProductos = cart.getArticulos().keySet().iterator(); while (iteradorProductos.hasNext()) { String key = iteradorProductos.next(); Producto prod = getProduct(key); int cantidad = cart.getArticulos().get(key); insertCarrito.setString(1, cart.getCodigo()); insertCarrito.setString(2, prod.getCodigo()); insertCarrito.setString(3, prod.getNombre()); insertCarrito.setDouble(4, prod.getPrecio()); insertCarrito.setInt(5, cantidad); filasAfectadas = insertCarrito.executeUpdate(); if (filasAfectadas != 1) { conexion.rollback(); break; } insertCarrito.clearParameters(); } conexion.commit(); exito = true; } } catch (SQLException ex) { logger.log(Level.SEVERE, "Error añadiendo carrito al registro", ex); try { conexion.rollback(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Error haciendo rollback de la transacción para insertar carrito en el registro", ex1); } } finally { cerrarConexionYStatement(conexion, insertCarrito, insertHistorial); } return exito; }
00
Code Sample 1: private void work(int timeout) throws Exception { Thread.currentThread().setName("Update - " + mod.getName()); if (mod.getUpdateCheckUrl() != null && mod.getUpdateDownloadUrl() != null) { URL url = new URL(mod.getUpdateCheckUrl().trim()); URLConnection connection = url.openConnection(); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String str = in.readLine(); in.close(); if (str != null && !str.toLowerCase().trim().contains("error") && !str.toLowerCase().trim().contains("Error") && !Manager.getInstance().compareModsVersions(str, "*-" + mod.getVersion())) { InputStream is = new URL(mod.getUpdateDownloadUrl().trim()).openStream(); file = new File(System.getProperty("java.io.tmpdir") + File.separator + new File(mod.getPath()).getName()); FileOutputStream fos = new FileOutputStream(file, false); FileUtils.copyInputStream(is, fos); is.close(); fos.flush(); fos.close(); } } } Code Sample 2: public static boolean insert(final Departamento ObjDepartamento) { 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 departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: private InputStream getInputStream() throws URISyntaxException, MalformedURLException, IOException { InputStream inStream = null; try { URL url = new URI(wsdlFile).toURL(); URLConnection connection = url.openConnection(); connection.connect(); inStream = connection.getInputStream(); } catch (IllegalArgumentException ex) { inStream = new FileInputStream(wsdlFile); } return inStream; } Code Sample 2: private void saveFile(InputStream in, String fullPath) { try { File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(in, out); out.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
00
Code Sample 1: private String readJsonString() { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(SERVER_URL); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(TAG, "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } Code Sample 2: private static void testTidy() { try { String url = "http://groups.google.com/group/dengues/files"; java.io.InputStream is = new java.net.URL(url).openStream(); org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is); org.w3c.dom.NodeList list = doc.getElementsByTagName("td"); org.w3c.dom.Element stockTypeElement = null; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node item = list.item(i); String content = dengues.system.HTMLWebHelper.getContent(item); String convert = dengues.system.HTMLWebHelper.convert(content); if (convert.equals("zDevil")) { stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode(); break; } } if (stockTypeElement != null) { org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr"); for (int i = 0; i < trList.getLength(); i++) { org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes(); if (trListChildren.getLength() > 2) { org.w3c.dom.Node node_0 = trListChildren.item(0); org.w3c.dom.Node node_1 = trListChildren.item(1); String content = dengues.system.HTMLWebHelper.getContent(node_0); String convert_0 = dengues.system.HTMLWebHelper.convert(content); content = dengues.system.HTMLWebHelper.getContent(node_1); String convert_1 = dengues.system.HTMLWebHelper.convert(content); if (!"".equals(convert_0)) { System.out.println(convert_0 + " => " + convert_1); } } } } is.close(); } catch (java.net.MalformedURLException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } }
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: public void open(String server, String user, String pass, int port, String option) throws Exception { log.info("Login to FTP: " + server); this.port = port; ftp = new FTPClient(); ftp.connect(server, port); ftp.login(user, pass); checkReply("FTP server refused connection." + server); modeBINARY(); this.me = this; }
00
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void populateDefaultIcons() { DomainNameTree defaultmap = this.getDefaultIconMap(); DomainNameTree newmap = new DomainNameTree(); File iconDir = new File(this.usrIconDir); if (!(iconDir.exists() && iconDir.isDirectory())) { int s = JOptionPane.showConfirmDialog(null, "Create icon directory " + this.usrIconDir + "?", "Icon directory does not exist!", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { iconDir.mkdir(); } else { return; } } Set domains = defaultmap.domainSet(); Iterator iter = domains.iterator(); while (iter.hasNext()) { String dname = (String) iter.next(); String fname = defaultmap.getImageFile(dname); if (fname != null) { System.out.println("Attempting to populate with:" + fname); if (!fname.equals("null")) { File file = new File(fname); String newname = this.usrIconDir.concat(File.separator).concat(file.getName()); File newfile = new File(newname); URL url = this.getClass().getResource(fname); if (url != null) { InputStream from = null; FileOutputStream to = null; try { byte[] buffer = new byte[4096]; from = url.openStream(); to = new FileOutputStream(newfile); int bytes_read = 0; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } newmap.insert(new DomainNameNode(dname, newname)); } catch (Exception err) { throw new RuntimeException("Problem saving image to file.", err); } finally { if (from != null) { try { from.close(); } catch (IOException err) { throw new RuntimeException("Problem closing URL input stream."); } } if (to != null) { try { to.close(); } catch (IOException err) { throw new RuntimeException("Problem closing file output stream."); } } } } else { throw new RuntimeException("Trying to copy the default icon " + fname + " from " + this.getClass().getPackage() + " but it does not exist."); } } } } int s = JOptionPane.showConfirmDialog(null, "Save default mappings in " + this.usrConfigFile + "?", "Icon directory populated...", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { saveToRegistry(newmap); } }
00
Code Sample 1: public synchronized String getSerialNumber() { if (serialNum != null) return serialNum; final StringBuffer buf = new StringBuffer(); Iterator it = classpath.iterator(); while (it.hasNext()) { ClassPathEntry entry = (ClassPathEntry) it.next(); buf.append(entry.getResourceURL().toString()); buf.append(":"); } serialNum = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } } }); return serialNum; } Code Sample 2: private static Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
11
Code Sample 1: public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } } Code Sample 2: public RandomGUID() { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } try { long time = System.currentTimeMillis(); long rand = 0; rand = myRand.nextLong(); StringBuffer sb = new StringBuffer(); sb.append(s_id); sb.append(":"); sb.append(Long.toString(time)); sb.append(":"); sb.append(Long.toString(rand)); md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); sb.setLength(0); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage()); } }
11
Code Sample 1: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); } Code Sample 2: @Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
11
Code Sample 1: public static byte[] encrypt(String x) throws Exception { java.security.MessageDigest d = null; d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); } Code Sample 2: private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { FileChannel sourceChannel = new FileInputStream(src).getChannel(); FileChannel destinationChannel = new FileOutputStream(dst).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
11
Code Sample 1: protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); } 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(); } }
11
Code Sample 1: public void testAllowClosingInputStreamTwice() throws IOException { OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE); outputStream.write(new byte[] { 1, 2, 3 }); outputStream.close(); InputStream inputStream = fileSystem.createInputStream(_("hello")); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copy(inputStream, buffer); inputStream.close(); inputStream.close(); } 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 run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public void copyJarContent(File jarPath, File targetDir) throws IOException { log.info("Copying natives from " + jarPath.getName()); JarFile jar = new JarFile(jarPath); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry file = entries.nextElement(); File f = new File(targetDir, file.getName()); log.info("Copying native - " + file.getName()); File parentFile = f.getParentFile(); parentFile.mkdirs(); if (file.isDirectory()) { f.mkdir(); continue; } InputStream is = null; FileOutputStream fos = null; try { is = jar.getInputStream(file); fos = new FileOutputStream(f); IOUtils.copy(is, fos); } finally { if (fos != null) fos.close(); if (is != null) is.close(); } } }
00
Code Sample 1: private ByteBuffer readProgram(URL url) throws IOException { StringBuilder program = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { program.append(line).append("\n"); } } finally { if (in != null) in.close(); } ByteBuffer buffer = BufferUtils.createByteBuffer(program.length()); for (int i = 0; i < program.length(); i++) { buffer.put((byte) (program.charAt(i) & 0xFF)); } buffer.flip(); return buffer; } Code Sample 2: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
11
Code Sample 1: public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req, ActionResponse res) throws Exception { boolean editor = false; req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, false); User user = _getUser(req); List<Role> roles = RoleFactory.getAllRolesForUser(user.getUserId()); for (Role role : roles) { if (role.getName().equals("Report Administrator") || role.getName().equals("Report Editor") || role.getName().equals("CMS Administrator")) { req.setAttribute(ViewReportsAction.REPORT_EDITOR_OR_ADMIN, true); editor = true; break; } } requiresInput = false; badParameters = false; newReport = false; ActionRequestImpl reqImpl = (ActionRequestImpl) req; HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); String cmd = req.getParameter(Constants.CMD); Logger.debug(this, "Inside EditReportAction cmd=" + cmd); ReportForm rfm = (ReportForm) form; ArrayList<String> ds = (DbConnectionFactory.getAllDataSources()); ArrayList<DataSource> dsResults = new ArrayList<DataSource>(); for (String dataSource : ds) { DataSource d = rfm.getNewDataSource(); if (dataSource.equals(com.dotmarketing.util.Constants.DATABASE_DEFAULT_DATASOURCE)) { d.setDsName("DotCMS Datasource"); } else { d.setDsName(dataSource); } dsResults.add(d); } rfm.setDataSources(dsResults); httpReq.setAttribute("dataSources", rfm.getDataSources()); Long reportId = UtilMethods.parseLong(req.getParameter("reportId"), 0); String referrer = req.getParameter("referrer"); if (reportId > 0) { report = ReportFactory.getReport(reportId); ArrayList<String> adminRoles = new ArrayList<String>(); adminRoles.add(com.dotmarketing.util.Constants.ROLE_REPORT_ADMINISTRATOR); if (user.getUserId().equals(report.getOwner())) { _checkWritePermissions(report, user, httpReq, adminRoles); } if (cmd == null || !cmd.equals(Constants.EDIT)) { rfm.setSelectedDataSource(report.getDs()); rfm.setReportName(report.getReportName()); rfm.setReportDescription(report.getReportDescription()); rfm.setReportId(report.getInode()); rfm.setWebFormReport(report.isWebFormReport()); httpReq.setAttribute("selectedDS", report.getDs()); } } else { if (!editor) { throw new DotRuntimeException("user not allowed to create a new report"); } report = new Report(); report.setOwner(_getUser(req).getUserId()); newReport = true; } req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, report); if ((cmd != null) && cmd.equals(Constants.EDIT)) { if (Validator.validate(req, form, mapping)) { report.setReportName(rfm.getReportName()); report.setReportDescription(rfm.getReportDescription()); report.setWebFormReport(rfm.isWebFormReport()); if (rfm.isWebFormReport()) report.setDs("None"); else report.setDs(rfm.getSelectedDataSource()); String jrxmlPath = ""; String jasperPath = ""; try { HibernateUtil.startTransaction(); ReportFactory.saveReport(report); _applyPermissions(req, report); if (!rfm.isWebFormReport()) { if (UtilMethods.isSet(Config.getStringProperty("ASSET_REAL_PATH"))) { jrxmlPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"; jasperPath = Config.getStringProperty("ASSET_REAL_PATH") + File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"; } else { jrxmlPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jrxml"); jasperPath = Config.CONTEXT.getRealPath(File.separator + Config.getStringProperty("REPORT_PATH") + File.separator + report.getInode() + ".jasper"); } UploadPortletRequest upr = PortalUtil.getUploadPortletRequest(req); File importFile = upr.getFile("jrxmlFile"); if (importFile.exists()) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(importFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); File f = new File(jrxmlPath); FileChannel channelTo = new FileOutputStream(f).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); try { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } catch (Exception e) { Logger.error(this, "Unable to compile or save jrxml: " + e.toString()); try { f = new File(jrxmlPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jrxml. This is usually a permissions problem."); } try { f = new File(jasperPath); f.delete(); } catch (Exception ex) { Logger.info(this, "Unable to delete jasper. This is usually a permissions problem."); } HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", UtilMethods.htmlLineBreak(e.getMessage())); setForward(req, "portlet.ext.report.edit_report"); return; } JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperPath); ReportParameterFactory.deleteReportsParameters(report); _loadReportParameters(jasperReport.getParameters()); report.setRequiresInput(requiresInput); HibernateUtil.save(report); } else if (newReport) { HibernateUtil.rollbackTransaction(); SessionMessages.add(req, "error", "message.report.compile.error"); setForward(req, "portlet.ext.report.edit_report"); return; } } HibernateUtil.commitTransaction(); HashMap params = new HashMap(); SessionMessages.add(req, "message", "message.report.upload.success"); params.put("struts_action", new String[] { "/ext/report/view_reports" }); referrer = com.dotmarketing.util.PortletURLUtil.getRenderURL(((ActionRequestImpl) req).getHttpServletRequest(), javax.portlet.WindowState.MAXIMIZED.toString(), params); _sendToReferral(req, res, referrer); return; } catch (Exception ex) { HibernateUtil.rollbackTransaction(); Logger.error(this, "Unable to save Report: " + ex.toString()); File f; Logger.info(this, "Trying to delete jrxml"); try { f = new File(jrxmlPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jrxml. This is usually because the file doesn't exist."); } try { f = new File(jasperPath); f.delete(); } catch (Exception e) { Logger.info(this, "Unable to delete jasper. This is usually because the file doesn't exist."); } if (badParameters) { SessionMessages.add(req, "error", ex.getMessage()); } else { SessionMessages.add(req, "error", "message.report.compile.error"); } setForward(req, "portlet.ext.report.edit_report"); return; } } else { setForward(req, "portlet.ext.report.edit_report"); } } if ((cmd != null) && cmd.equals("downloadReportSource")) { ActionResponseImpl resImpl = (ActionResponseImpl) res; HttpServletResponse response = resImpl.getHttpServletResponse(); if (!downloadSourceReport(reportId, httpReq, response)) { SessionMessages.add(req, "error", "message.report.source.file.not.found"); } } setForward(req, "portlet.ext.report.edit_report"); } Code Sample 2: @Test public void testCopy() throws IOException { final byte[] input = { 0x00, 0x01, 0x7F, 0x03, 0x40 }; final byte[] verification = input.clone(); Assert.assertNotSame("Expecting verification to be a new array.", input, verification); final ByteArrayInputStream in = new ByteArrayInputStream(input); final ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); final byte[] output = out.toByteArray(); Assert.assertTrue("Expecting input to be unchanged.", Arrays.equals(verification, input)); Assert.assertTrue("Expecting output to be like input.", Arrays.equals(verification, output)); Assert.assertNotSame("Expecting output to be a new array.", input, output); Assert.assertNotSame("Expecting output to be a new array.", verification, output); }
00
Code Sample 1: public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } } Code Sample 2: @Override public Response executeGet(String url) throws IOException { if (logger.isLoggable(INFO)) logger.info("Making a GET request to " + url); HttpURLConnection httpUrlConnection = null; InputStream inputStream = null; try { httpUrlConnection = openConnection(new URL(url)); httpUrlConnection.setReadTimeout(DEFAULT_READ_TIMEOUT_IN_MS); httpUrlConnection.setUseCaches(false); customizeConnection(httpUrlConnection); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.connect(); if (logger.isLoggable(FINER)) logger.finer("Response headers: " + httpUrlConnection.getHeaderFields()); try { inputStream = httpUrlConnection.getResponseCode() != HTTP_OK ? httpUrlConnection.getErrorStream() : httpUrlConnection.getInputStream(); } catch (IOException e) { if (logger.isLoggable(WARNING)) logger.warning("An error occurred while making a GET request to " + url + ": " + e); } return new Response(httpUrlConnection.getResponseCode(), fromInputStream(inputStream)); } finally { closeQuietly(httpUrlConnection); } }
11
Code Sample 1: public void copyFile2(String src, String dest) throws IOException { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + MM.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(MM.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
11
Code Sample 1: public int unindexRecord(String uuid) throws SQLException, CatalogIndexException { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; int nRows = 0; StringSet fids = new StringSet(); if (cswRemoteRepository.isActive()) { StringSet uuids = new StringSet(); uuids.add(uuid); fids = queryFileIdentifiers(uuids); } try { con = returnConnection().getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); String sSql = "DELETE FROM " + getResourceDataTableName() + " WHERE DOCUUID=?"; logExpression(sSql); st = con.prepareStatement(sSql); st.setString(1, uuid); nRows = st.executeUpdate(); con.commit(); } catch (SQLException ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } CatalogIndexAdapter indexAdapter = getCatalogIndexAdapter(); if (indexAdapter != null) { indexAdapter.deleteDocument(uuid); if (cswRemoteRepository.isActive()) { if (fids.size() > 0) cswRemoteRepository.onRecordsDeleted(fids); } } return nRows; } Code Sample 2: public void exe2(String[] args) { Connection con = null; Connection con2 = null; Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con = getConnection("mis030dv"); con2 = getConnection("mis030db"); con2.setAutoCommit(false); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM MIS.MAP_PUR0101 WHERE NOT EXISTS (SELECT 1 FROM MIS.RSCMGOOD@MIS030DB@DEVU01 WHERE GOODCD = PUM_CODE OR GOODCD = NEW_PUM_CODE)"); pstmt = con2.prepareStatement("INSERT INTO MIS.RSCMGOOD ( GOODCD,GOODFLAG,GOODNM,GOODHNGNM,GOODENGNM,GOODSPEC,GOODMODEL,ASETFLAG,LRGCD,MDLCD,SMLCD,EDICD,PRODCMPYCD,CMT,FSTRGSTRID,FSTRGSTDT,LASTUPDTRID,LASTUPDTDT,APPINSTDATA,MNGTFLAG) " + "VALUES ( ?,SUBSTR(?,1,1),?,?,?,?,NULL,'1',substr(?,2,2),substr(?,4,3),NULL,NULL,NULL,'OCS �����빰ǰ','MISASIS',TO_DATE('20111231','YYYYMMDD'),'MISASIS',TO_DATE('20111231','YYYYMMDD'),NULL,'N')"); int count = 0; String goodcd = null; String goodnm = null; while (rs.next()) { count++; goodcd = rs.getString("PUM_CODE").toUpperCase(); goodnm = rs.getString("PUM_HNAME"); StringUtils.trimWhitespace(goodnm); if (goodnm == null || goodnm.equals("")) goodnm = "-"; pstmt.setString(1, goodcd); pstmt.setString(2, goodcd); pstmt.setString(3, goodnm); pstmt.setString(4, goodnm); pstmt.setString(5, rs.getString("PUM_ENAME")); pstmt.setString(6, rs.getString("KYUKYEOK")); pstmt.setString(7, goodcd); pstmt.setString(8, goodcd); pstmt.executeUpdate(); if (count % 100 == 0) System.out.println("Copy Row : " + count); } System.out.println("Commit Copy Rows : " + count); con2.commit(); } catch (Exception e) { try { con2.rollback(); } catch (Exception ee) { ee.printStackTrace(); } e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); if (con2 != null) con2.close(); } catch (Exception e) { e.printStackTrace(); } } }
00
Code Sample 1: private void copy(String url, File toDir) throws IOException { System.err.println("url=" + url + " dir=" + toDir); if (url.endsWith("/")) { String basename = url.substring(url.lastIndexOf("/", url.length() - 2) + 1); File directory = new File(toDir, basename); directory.mkdir(); LineNumberReader reader = new LineNumberReader(new InputStreamReader(new URL(url).openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { System.err.println(line.replace('\t', '|')); int tab = line.lastIndexOf('\t', line.lastIndexOf('\t', line.lastIndexOf('\t') - 1) - 1); System.err.println(tab); char type = line.charAt(tab + 1); String file = line.substring(0, tab); copy(url + URIUtil.encodePath(file) + (type == 'd' ? "/" : ""), directory); } } else { String basename = url.substring(url.lastIndexOf("/") + 1); File file = new File(toDir, basename); System.err.println("copy " + url + " --> " + file); IO.copy(new URL(url).openStream(), new FileOutputStream(file)); } } Code Sample 2: public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } }
00
Code Sample 1: public Image storeImage(String title, String pathToImage, Map<String, Object> additionalProperties) { File collectionFolder = ProjectManager.getInstance().getFolder(PropertyHandler.getInstance().getProperty("_default_collection_name")); File imageFile = new File(pathToImage); String filename = ""; String format = ""; File copiedImageFile; while (true) { filename = "image" + UUID.randomUUID().hashCode(); if (!DbEntryProvider.INSTANCE.idExists(filename)) { Path path = new Path(pathToImage); format = path.getFileExtension(); copiedImageFile = new File(collectionFolder.getAbsolutePath() + File.separator + filename + "." + format); if (!copiedImageFile.exists()) break; } } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(imageFile), 4096); out = new BufferedOutputStream(new FileOutputStream(copiedImageFile), 4096); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } Image image = new ImageImpl(); image.setId(filename); image.setFormat(format); image.setEntryDate(new Date()); image.setTitle(title); image.setAdditionalProperties(additionalProperties); boolean success = DbEntryProvider.INSTANCE.storeNewImage(image); if (success) return image; return null; } Code Sample 2: public void addUserToRealm(final NewUser user) { try { connection.setAutoCommit(false); final String pass, salt; final List<RealmWithEncryptedPass> realmPass = new ArrayList<RealmWithEncryptedPass>(); Realm realm; String username; username = user.username.toLowerCase(locale); PasswordHasher ph = PasswordFactory.getInstance().getPasswordHasher(); pass = ph.hashPassword(user.password); salt = ph.getSalt(); realmPass.add(new RealmWithEncryptedPass(cm.getRealm("null"), PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, "", user.password))); if (user.realms != null) { for (String realmName : user.realms) { realm = cm.getRealm(realmName); realmPass.add(new RealmWithEncryptedPass(realm, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, realm.getFullRealmName(), user.password))); } user.realms = null; } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); psImpl.setString(1, pass); psImpl.setString(2, salt); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); } }); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.addUser")); RealmWithEncryptedPass rwep; RealmDb realm; Iterator<RealmWithEncryptedPass> iter1 = realmPass.iterator(); while (iter1.hasNext()) { rwep = iter1.next(); realm = (RealmDb) rwep.realm; psImpl.setInt(1, realm.getRealmId()); psImpl.setInt(2, user.userId); psImpl.setInt(3, user.domainId); psImpl.setString(4, rwep.password); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUser(user.userId); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
00
Code Sample 1: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); } Code Sample 2: static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); }
00
Code Sample 1: @Override public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException { if (soapAction == null) { soapAction = "\"\""; } byte[] requestData = createRequestData(envelope); requestDump = debug ? new String(requestData) : null; responseDump = null; HttpPost method = new HttpPost(url); method.addHeader("User-Agent", "kSOAP/2.0-Excilys"); method.addHeader("SOAPAction", soapAction); method.addHeader("Content-Type", "text/xml"); HttpEntity entity = new ByteArrayEntity(requestData); method.setEntity(entity); HttpResponse response = httpClient.execute(method); InputStream inputStream = response.getEntity().getContent(); if (debug) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[256]; while (true) { int rd = inputStream.read(buf, 0, 256); if (rd == -1) { break; } bos.write(buf, 0, rd); } bos.flush(); buf = bos.toByteArray(); responseDump = new String(buf); inputStream.close(); inputStream = new ByteArrayInputStream(buf); } parseResponse(envelope, inputStream); inputStream.close(); } Code Sample 2: private void insert(Connection c) throws SQLException { if (m_fromDb) throw new IllegalStateException("The record already exists in the database"); StringBuffer names = new StringBuffer("INSERT INTO ifServices (nodeID,ipAddr,serviceID"); StringBuffer values = new StringBuffer("?,?,?"); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) { values.append(",?"); names.append(",ifIndex"); } if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) { values.append(",?"); names.append(",status"); } if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { values.append(",?"); names.append(",lastGood"); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { values.append(",?"); names.append(",lastFail"); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) { values.append(",?"); names.append(",source"); } if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) { values.append(",?"); names.append(",notify"); } if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) { values.append(",?"); names.append(",qualifier"); } names.append(") VALUES (").append(values).append(')'); if (log().isDebugEnabled()) log().debug("DbIfServiceEntry.insert: SQL insert statment = " + names.toString()); PreparedStatement stmt = null; PreparedStatement delStmt = null; final DBUtils d = new DBUtils(getClass()); try { stmt = c.prepareStatement(names.toString()); d.watch(stmt); names = null; int ndx = 1; stmt.setInt(ndx++, m_nodeId); stmt.setString(ndx++, m_ipAddr.getHostAddress()); stmt.setInt(ndx++, m_serviceId); if ((m_changed & CHANGED_IFINDEX) == CHANGED_IFINDEX) stmt.setInt(ndx++, m_ifIndex); if ((m_changed & CHANGED_STATUS) == CHANGED_STATUS) stmt.setString(ndx++, new String(new char[] { m_status })); if ((m_changed & CHANGED_LASTGOOD) == CHANGED_LASTGOOD) { stmt.setTimestamp(ndx++, m_lastGood); } if ((m_changed & CHANGED_LASTFAIL) == CHANGED_LASTFAIL) { stmt.setTimestamp(ndx++, m_lastFail); } if ((m_changed & CHANGED_SOURCE) == CHANGED_SOURCE) stmt.setString(ndx++, new String(new char[] { m_source })); if ((m_changed & CHANGED_NOTIFY) == CHANGED_NOTIFY) stmt.setString(ndx++, new String(new char[] { m_notify })); if ((m_changed & CHANGED_QUALIFIER) == CHANGED_QUALIFIER) stmt.setString(ndx++, m_qualifier); int rc; try { rc = stmt.executeUpdate(); } catch (SQLException e) { log().warn("ifServices DB insert got exception; will retry after " + "deletion of any existing records for this ifService " + "that are marked for deletion.", e); c.rollback(); String delCmd = "DELETE FROM ifServices WHERE status = 'D' " + "AND nodeid = ? AND ipAddr = ? AND serviceID = ?"; delStmt = c.prepareStatement(delCmd); d.watch(delStmt); delStmt.setInt(1, m_nodeId); delStmt.setString(2, m_ipAddr.getHostAddress()); delStmt.setInt(3, m_serviceId); rc = delStmt.executeUpdate(); rc = stmt.executeUpdate(); } log().debug("insert(): SQL update result = " + rc); } finally { d.cleanUp(); } m_fromDb = true; m_changed = 0; }
00
Code Sample 1: public static void uploadFile(File in, String out, String host, int port, String path, String login, String password, boolean renameIfExist) throws IOException { FTPClient ftp = null; try { m_logCat.info("Uploading " + in + " to " + host + ":" + port + " at " + path); ftp = new FTPClient(); int reply; ftp.connect(host, port); m_logCat.info("Connected to " + host + "... Trying to authenticate"); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); m_logCat.error("FTP server " + host + " refused connection."); throw new IOException("Cannot connect to the FTP Server: connection refused."); } if (!ftp.login(login, password)) { ftp.logout(); throw new IOException("Cannot connect to the FTP Server: login / password is invalid!"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); if (!ftp.changeWorkingDirectory(path)) { m_logCat.warn("Remote working directory: " + path + "does not exist on the FTP Server ..."); m_logCat.info("Trying to create remote directory: " + path); if (!ftp.makeDirectory(path)) { m_logCat.error("Failed to create remote directory: " + path); throw new IOException("Failed to store " + in + " in the remote directory: " + path); } if (!ftp.changeWorkingDirectory(path)) { m_logCat.error("Failed to change directory. Unexpected error"); throw new IOException("Failed to change to remote directory : " + path); } } if (out == null) { out = in.getName(); if (out.startsWith("/")) { out = out.substring(1); } } if (renameIfExist) { String[] files = ftp.listNames(); String f = in + out; for (int i = 0; i < files.length; i++) { if (files[i].equals(out)) { m_logCat.debug("Found existing file on the server: " + out); boolean rename_ok = false; String bak = "_bak"; int j = 0; String newExt = null; while (!rename_ok) { if (j == 0) newExt = bak; else newExt = bak + j; if (ftp.rename(out, out + newExt)) { m_logCat.info(out + " renamed to " + out + newExt); rename_ok = true; } else { m_logCat.warn("Renaming to " + out + newExt + " has failed!, trying again ..."); j++; } } break; } } } InputStream input = new FileInputStream(in); m_logCat.info("Starting transfert of " + in); ftp.storeFile(out, input); m_logCat.info(in + " uploaded successfully"); input.close(); ftp.logout(); } catch (FTPConnectionClosedException e) { m_logCat.error("Server closed connection.", e); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } } } Code Sample 2: public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public static String encryptMD5(String str) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); byte[] hash = md5.digest(); md5.reset(); return Format.hashToHex(hash); } catch (java.security.NoSuchAlgorithmException nsae0) { return null; } } Code Sample 2: public boolean refresh() { try { URLConnection conn = url.openConnection(); conn.setUseCaches(false); if (credential != null) conn.setRequestProperty("Authorization", credential); conn.connect(); int status = ((HttpURLConnection) conn).getResponseCode(); if (status == 401 || status == 403) errorMessage = (credential == null ? PASSWORD_MISSING : PASSWORD_INCORRECT); else if (status == 404) errorMessage = NOT_FOUND; else if (status != 200) errorMessage = COULD_NOT_RETRIEVE; else { InputStream in = conn.getInputStream(); byte[] httpData = TinyWebServer.slurpContents(in, true); synchronized (this) { data = httpData; dataProvider = null; } errorMessage = null; refreshDate = new Date(); String owner = conn.getHeaderField(OWNER_HEADER_FIELD); if (owner != null) setLocalAttr(OWNER_ATTR, owner); store(); return true; } } catch (UnknownHostException uhe) { errorMessage = NO_SUCH_HOST; } catch (ConnectException ce) { errorMessage = COULD_NOT_CONNECT; } catch (IOException ioe) { errorMessage = COULD_NOT_RETRIEVE; } return false; }
11
Code Sample 1: public static String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new WebDocRuntimeException(ex); } md.update(text.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); return hash.toString(HEX); } Code Sample 2: public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); }
00
Code Sample 1: public static String md5(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); return convertToHex(md.digest()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); } Code Sample 2: @Test public void testWrite() throws Exception { MrstkXmlFileReader reader = new MrstkXmlFileReader(); reader.setFileName("..//data//MrstkXML//prototype3.xml"); reader.read(); SpectrumArray sp = reader.getOutput(); File tmp = File.createTempFile("mrstktest", ".xml"); System.out.println("Writing temp file: " + tmp.getAbsolutePath()); MrstkXmlFileWriter writer = new MrstkXmlFileWriter(sp); writer.setFile(tmp); writer.write(); MrstkXmlFileReader reader2 = new MrstkXmlFileReader(); reader2.setFileName(writer.getFile().getAbsolutePath()); reader2.read(); SpectrumArray sp2 = reader2.getOutput(); assertTrue(sp.equals(sp2)); }
11
Code Sample 1: public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } } Code Sample 2: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
00
Code Sample 1: private void createCanvas() { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.setRootEditPart(new ScalableRootEditPart()); viewer.setEditPartFactory(new BlockEditPartFactory()); viewer.createControl(this); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); ActionRegistry actionRegistry = new ActionRegistry(); createActions(actionRegistry); ContextMenuProvider cmProvider = new BlockContextMenuProvider(viewer, actionRegistry); viewer.setContextMenu(cmProvider); Block b = new Block(); b.addChild(new ChartItem()); viewer.setContents(b); PaletteViewer paletteViewer = new PaletteViewer(); paletteViewer.createControl(this); } Code Sample 2: void execute(HttpClient client, MonitoredService svc) { try { URI uri = getURI(svc); PageSequenceHttpMethod method = getMethod(); method.setURI(uri); if (getVirtualHost() != null) { method.getParams().setVirtualHost(getVirtualHost()); } if (getUserAgent() != null) { method.addRequestHeader("User-Agent", getUserAgent()); } if (m_parms.length > 0) { method.setParameters(m_parms); } if (m_page.getUserInfo() != null) { String userInfo = m_page.getUserInfo(); String[] streetCred = userInfo.split(":", 2); if (streetCred.length == 2) { client.getState().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(streetCred[0], streetCred[1])); method.setDoAuthentication(true); } } int code = client.executeMethod(method); if (!getRange().contains(code)) { throw new PageSequenceMonitorException("response code out of range for uri:" + uri + ". Expected " + getRange() + " but received " + code); } InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } String responseString = outputStream.toString(); if (getFailurePattern() != null) { Matcher matcher = getFailurePattern().matcher(responseString); if (matcher.find()) { throw new PageSequenceMonitorException(getResolvedFailureMessage(matcher)); } } if (getSuccessPattern() != null) { Matcher matcher = getSuccessPattern().matcher(responseString); if (!matcher.find()) { throw new PageSequenceMonitorException("failed to find '" + getSuccessPattern() + "' in page content at " + uri); } } } catch (URIException e) { throw new IllegalArgumentException("unable to construct URL for page: " + e, e); } catch (HttpException e) { throw new PageSequenceMonitorException("HTTP Error " + e, e); } catch (IOException e) { throw new PageSequenceMonitorException("I/O Error " + e, e); } }
00
Code Sample 1: public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; } Code Sample 2: public static File copyFile(File file) { File src = file; 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; }
00
Code Sample 1: public void createCodeLocation() { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectname); try { IProjectDescription projectDescription = null; IJavaProject javaProject = JavaCore.create(project); if (project.exists()) { project.delete(true, null); } projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectname); project.create(projectDescription, new NullProgressMonitor()); String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID }; } else { boolean hasJavaNature = false; boolean hasPDENature = false; for (int i = 0; i < natureIds.length; ++i) { if (JavaCore.NATURE_ID.equals(natureIds[i])) { hasJavaNature = true; } if ("org.eclipse.pde.PluginNature".equals(natureIds[i])) { hasPDENature = true; } } if (!hasJavaNature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!hasPDENature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.open(new NullProgressMonitor()); project.setDescription(projectDescription, new NullProgressMonitor()); sourceContainer = project.getFolder("src"); sourceContainer.create(false, true, new NullProgressMonitor()); IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(new Path("/" + projectname + "/src")); classpathEntries.add(0, sourceClasspathEntry); String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); javaProject.setOutputLocation(new Path("/" + projectname + "/bin"), new NullProgressMonitor()); javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new NullProgressMonitor()); } catch (CoreException e) { e.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(e); } } Code Sample 2: protected final String H(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(data.getBytes("UTF8")); byte[] bytes = digest.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { int aByte = bytes[i]; if (aByte < 0) aByte += 256; if (aByte < 16) sb.append('0'); sb.append(Integer.toHexString(aByte)); } return sb.toString(); }
11
Code Sample 1: public void testMemberSeek() throws IOException { GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz)); gzin.setEofEachMember(true); gzin.compressedSeek(noise1k_gz.length + noise32k_gz.length); int count2 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 1-byte member count", 1, count2); assertEquals("wrong Member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int count3 = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong 5-byte member count", 5, count3); assertEquals("wrong Member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart()); assertEquals("wrong Member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd()); gzin.nextMember(); int countEnd = IOUtils.copy(gzin, new NullOutputStream()); assertEquals("wrong eof count", 0, countEnd); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } } Code Sample 2: private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
00
Code Sample 1: public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from Instructions where InstructionId = " + id; stmt.executeUpdate(sql); sql = "delete from InstructionGroups where InstructionId = " + id; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public String uploadVideo(String ticketId, String filePath) { TreeMap<String, String> uploadParams = new TreeMap<String, String>(); String url = "http://www.vimeo.com/services/upload/"; uploadParams.put("api_key", apiKey); uploadParams.put("auth_token", this.TEMP_AUTH_TOKEN); uploadParams.put("ticket_id", ticketId); uploadParams.put("format", "json"); String signature = this.generateAppSignature(uploadParams); uploadParams.put("api_sig", signature); ClientHttpRequest request = null; try { request = new ClientHttpRequest(new URL(url).openConnection()); } catch (IOException e) { e.printStackTrace(); } for (Entry<String, String> param : uploadParams.entrySet()) { try { request.setParameter(param.getKey(), param.getValue()); } catch (IOException e) { e.printStackTrace(); } } InputStream videoInput = null; try { videoInput = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { request.setParameter("video", filePath, videoInput); } catch (IOException e) { e.printStackTrace(); } InputStream response = null; try { response = request.post(); } catch (IOException e) { e.printStackTrace(); } try { InputStreamReader inR = new InputStreamReader(response); BufferedReader buf = new BufferedReader(inR); String line; try { while ((line = buf.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return "hey"; }
11
Code Sample 1: public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); }
11
Code Sample 1: public boolean crear() { int result = 0; String sql = "insert into torneo" + "(nombreTorneo, ciudad, fechaInicio, fechaFinal, organizador, numeroDivisiones, terminado)" + "values (?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(eltorneo); result = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (result > 0); } Code Sample 2: public boolean update(int idJugador, jugador jugadorModificado) { int intResult = 0; String sql = "UPDATE jugador " + "SET apellidoPaterno = ?, apellidoMaterno = ?, nombres = ?, fechaNacimiento = ?, " + " pais = ?, rating = ?, sexo = ? " + " WHERE idJugador = " + idJugador; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(jugadorModificado); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
11
Code Sample 1: public static String md5Encode(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return s; } } Code Sample 2: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
11
Code Sample 1: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: public static void copy(URL url, String outPath) throws IOException { System.out.println("copying from: " + url + " to " + outPath); InputStream in = url.openStream(); FileOutputStream fout = new FileOutputStream(outPath); byte[] data = new byte[8192]; int read = -1; while ((read = in.read(data)) != -1) { fout.write(data, 0, read); } fout.close(); } Code Sample 2: public static String createHash(String seed) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Can't happen!", e); } try { md.update(seed.getBytes(CHARSET)); md.update(String.valueOf(System.currentTimeMillis()).getBytes(CHARSET)); return toHexString(md.digest()); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Can't happen!", e); } }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); }
00
Code Sample 1: private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: @Override public VocabularyLocation next() { try { if (!urls.isEmpty()) { final URL url = urls.poll(); return new VocabularyLocation(url.toExternalForm(), VocabularyFormat.RDFXML, 0, url.openStream()); } if (!files.isEmpty()) { File file = files.poll(); return new VocabularyLocation(file.getCanonicalPath(), file.getName().endsWith(".ntriples") ? VocabularyFormat.NTRIPLES : VocabularyFormat.RDFXML, file.lastModified(), new FileInputStream(file)); } if (nextZipEntry != null) { String zipEntryAsString = IOUtils.toString(new CloseShieldInputStream(in), "UTF-8"); VocabularyLocation location = new VocabularyLocation(nextZipEntry.getName(), nextZipEntry.getName().endsWith(".rdf") ? VocabularyFormat.RDFXML : null, nextZipEntry.getTime(), IOUtils.toInputStream(zipEntryAsString, "UTF-8")); findNextZipEntry(); return location; } } catch (Exception e) { throw new RuntimeException(e); } throw new NoSuchElementException(); }
00
Code Sample 1: void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: private String hashSong(Song s) { if (s == null) return null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(s.getTitle().getBytes()); digest.update(s.getAllLyrics().getBytes()); String hash = Base64.encodeBytes(digest.digest()); return hash; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: private void onDhReply(final SshDhReply msg) throws GeneralSecurityException, IOException { if ((this.keyPair == null) || this.connection.isServer()) throw new SshException("%s: unexpected %s", this.connection.uri, msg.getType()); final BigInteger k; { final DHPublicKeySpec remoteKeySpec = new DHPublicKeySpec(new BigInteger(msg.f), P1, G); final KeyFactory dhKeyFact = KeyFactory.getInstance("DH"); final DHPublicKey remotePubKey = (DHPublicKey) dhKeyFact.generatePublic(remoteKeySpec); final KeyAgreement dhKex = KeyAgreement.getInstance("DH"); dhKex.init(this.keyPair.getPrivate()); dhKex.doPhase(remotePubKey, true); k = new BigInteger(dhKex.generateSecret()); } final MessageDigest md = createMessageDigest(); final byte[] h; { updateByteArray(md, SshVersion.LOCAL.toString().getBytes()); updateByteArray(md, this.connection.getRemoteSshVersion().toString().getBytes()); updateByteArray(md, this.keyExchangeInitLocal.getPayload()); updateByteArray(md, this.keyExchangeInitRemote.getPayload()); updateByteArray(md, msg.hostKey); updateByteArray(md, ((DHPublicKey) this.keyPair.getPublic()).getY().toByteArray()); updateByteArray(md, msg.f); updateBigInt(md, k); h = md.digest(); } if (this.sessionId == null) this.sessionId = h; this.keyExchangeInitLocal = null; this.keyExchangeInitRemote = null; this.h = h; this.k = k; this.connection.send(new SshKeyExchangeNewKeys()); }
11
Code Sample 1: public static boolean changeCredentials() { boolean passed = false; boolean credentials = false; HashMap info = null; Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write the credentials to file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { System.out.println(ex.toString()); if (ex.getMessage().toLowerCase().contains("unable")) { JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE); passed = true; testVar = false; } else { passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } while (!passed) { Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write credentials to local xml file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { Debug.log("Main.changeCredentials", "credential validation failed"); passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } } return credentials; } Code Sample 2: public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
11
Code Sample 1: public void run() { BufferedReader inp = null; try { String urlString = "http://www.hubtracker.com/query.php?action=add&username=" + user + "&password=" + pass + "&email=" + e_mail + "&address=" + Vars.Hub_Host; URL url = new URL(urlString); URLConnection conn; if (!Vars.Proxy_Host.equals("")) conn = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Vars.Proxy_Host, Vars.Proxy_Port))); else conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); inp = new BufferedReader(new InputStreamReader(conn.getInputStream())); String xx; while ((xx = inp.readLine()) != null) PluginMain.result += "\n" + xx; if (curCmd != null) this.curCmd.cur_client.sendFromBot("[hubtracker:] " + PluginMain.result); else PluginMain.curFrame.showMsg(); inp.close(); inp = null; } catch (MalformedURLException ue) { PluginMain.result = ue.toString(); } catch (Exception e) { PluginMain.result = e.toString(); } done = true; } 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; }
00
Code Sample 1: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } } Code Sample 2: public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
11
Code Sample 1: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); } Code Sample 2: public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).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) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
11
Code Sample 1: public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams) throws SQLException, ClassNotFoundException { getConnection(); boolean flag = false; try { pstmt = con.prepareStatement(strSql); setParamet(pstmt, prams); logger.info("###############::执行SQL语句操作(更新数据 有参数):" + strSql); if (0 < pstmt.executeUpdate()) { close_DB_Object(); flag = true; con.commit(); } } catch (SQLException ex) { logger.info("###############Error DBManager Line121::执行SQL语句操作(更新数据 无参数):" + strSql + "失败!"); flag = false; con.rollback(); throw ex; } catch (ClassNotFoundException ex) { logger.info("###############Error DBManager Line152::执行SQL语句操作(更新数据 无参数):" + strSql + "失败! 参数设置类型错误!"); con.rollback(); throw ex; } return flag; } Code Sample 2: public static boolean insereMidia(final Connection con, Midia mid, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodMidia(con, mid); GeraID.gerarCodDescricao(con, desc); String titulo = mid.getTitulo().replaceAll("['\"]", ""); String coment = mid.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO midia VALUES(" + mid.getCodigo() + ", '" + titulo + "', '" + coment + "','" + mid.getUrl() + "', '" + mid.getTipo() + "', " + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO mid_aut VALUES(" + mid.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "MIDIA: Database error", JOptionPane.ERROR_MESSAGE); System.err.print(e.getMessage()); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getMessage()); } } }
00
Code Sample 1: public static RecordResponse loadRecord(RecordRequest recordRequest) { RecordResponse recordResponse = new RecordResponse(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(recordRequest.isContact() ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", recordRequest.getToken())); nameValuePairs.add(new BasicNameValuePair("id", recordRequest.getId())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); String line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, recordRequest.isContact() ? "Name__Last__First_" : "Name"); String phone = ""; if (!recordRequest.isContact()) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, recordRequest.isContact() ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, recordRequest.isContact() ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); recordResponse.setName(Name__Last__First_); recordResponse.setPhone(phone); recordResponse.setEmail(Email1); recordResponse.setHomeFax(Home_Fax); recordResponse.setAddress1(Address1); recordResponse.setAddress2(Address2); recordResponse.setCity(City); recordResponse.setState(State); recordResponse.setZip(Zip); recordResponse.setProfile(Profile); recordResponse.setCountry(Country); recordResponse.setSuccess(success); recordResponse.setError(error); } catch (Exception e) { } return recordResponse; } Code Sample 2: private static void prepare() { System.err.println("PREPARING-----------------------------------------"); deleteHome(); InputStream configStream = null; FileOutputStream tempStream = null; try { configStream = AllTests.class.getClassLoader().getResourceAsStream("net/sf/archimede/test/resources/repository.xml"); new File("temp").mkdir(); tempStream = new FileOutputStream(new File("temp/repository.xml")); IOUtils.copy(configStream, tempStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (configStream != null) { configStream.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (tempStream != null) { try { tempStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } String repositoryName = "jackrabbit.repository"; Properties jndiProperties = new Properties(); jndiProperties.put("java.naming.provider.url", "http://sf.net/projects/archimede#1"); jndiProperties.put("java.naming.factory.initial", "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory"); startupUtil = new StartupJcrUtil(REPOSITORY_HOME, "temp/repository.xml", repositoryName, jndiProperties); startupUtil.init(); }
11
Code Sample 1: private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); } Code Sample 2: @Override protected void write(InputStream in, OutputStream out, javax.sound.sampled.AudioFormat javaSoundFormat) throws IOException { if (USE_JAVASOUND) { super.write(in, out, javaSoundFormat); } else { try { byte[] header = JavaSoundCodec.createWavHeader(javaSoundFormat); if (header == null) throw new IOException("Unable to create wav header"); out.write(header); IOUtils.copyStream(in, out); } catch (InterruptedIOException e) { logger.log(Level.FINE, "" + e, e); throw e; } catch (IOException e) { logger.log(Level.WARNING, "" + e, e); throw e; } } }
00
Code Sample 1: public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; } Code Sample 2: public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; }
00
Code Sample 1: protected String readFileUsingFileUrl(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } 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: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public static File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
00
Code Sample 1: public static void writeURLToFile(String url, String path) throws MalformedURLException, IOException { java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(path); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte data[] = new byte[1024]; int count; while ((count = in.read(data, 0, 1024)) != -1) { ; bout.write(data, 0, count); } bout.close(); in.close(); } Code Sample 2: public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.getDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; }
00
Code Sample 1: public static URLConnection getURLConnection(URL url, boolean ignoreBadCertificates) throws KeyManagementException, NoSuchAlgorithmException, UnknownHostException, IOException { SSLSocketFactory sslSocketFactory = null; if (ignoreBadCertificates) { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, getAllTrustingTrustManager(), new java.security.SecureRandom()); sslSocketFactory = sslContext.getSocketFactory(); } else { sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory); return url.openConnection(); } Code Sample 2: public void run(IAction action) { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
11
Code Sample 1: private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } } 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:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
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) { Logger.error(FileUtil.class, ioe.getMessage(), ioe); } } Code Sample 2: void execute(HttpClient client, MonitoredService svc) { try { URI uri = getURI(svc); PageSequenceHttpMethod method = getMethod(); method.setURI(uri); if (getVirtualHost() != null) { method.getParams().setVirtualHost(getVirtualHost()); } if (getUserAgent() != null) { method.addRequestHeader("User-Agent", getUserAgent()); } if (m_parms.length > 0) { method.setParameters(m_parms); } if (m_page.getUserInfo() != null) { String userInfo = m_page.getUserInfo(); String[] streetCred = userInfo.split(":", 2); if (streetCred.length == 2) { client.getState().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(streetCred[0], streetCred[1])); method.setDoAuthentication(true); } } int code = client.executeMethod(method); if (!getRange().contains(code)) { throw new PageSequenceMonitorException("response code out of range for uri:" + uri + ". Expected " + getRange() + " but received " + code); } InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } String responseString = outputStream.toString(); if (getFailurePattern() != null) { Matcher matcher = getFailurePattern().matcher(responseString); if (matcher.find()) { throw new PageSequenceMonitorException(getResolvedFailureMessage(matcher)); } } if (getSuccessPattern() != null) { Matcher matcher = getSuccessPattern().matcher(responseString); if (!matcher.find()) { throw new PageSequenceMonitorException("failed to find '" + getSuccessPattern() + "' in page content at " + uri); } } } catch (URIException e) { throw new IllegalArgumentException("unable to construct URL for page: " + e, e); } catch (HttpException e) { throw new PageSequenceMonitorException("HTTP Error " + e, e); } catch (IOException e) { throw new PageSequenceMonitorException("I/O Error " + e, e); } }
11
Code Sample 1: public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); } Code Sample 2: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
11
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: private void handleNodeDown(long eventID, long nodeID, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1) { log.warn(EventConstants.NODE_DOWN_EVENT_UEI + " ignored - info incomplete - eventid/nodeid: " + eventID + "/" + nodeID); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement activeSvcsStmt = dbConn.prepareStatement(OutageConstants.DB_GET_ACTIVE_SERVICES_FOR_NODE); PreparedStatement openStmt = dbConn.prepareStatement(OutageConstants.DB_OPEN_RECORD); PreparedStatement newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); PreparedStatement getNextOutageIdStmt = dbConn.prepareStatement(OutageManagerConfigFactory.getInstance().getGetNextOutageID()); newOutageWriter = dbConn.prepareStatement(OutageConstants.DB_INS_NEW_OUTAGE); if (log.isDebugEnabled()) log.debug("handleNodeDown: creating new outage entries..."); activeSvcsStmt.setLong(1, nodeID); ResultSet activeSvcsRS = activeSvcsStmt.executeQuery(); while (activeSvcsRS.next()) { String ipAddr = activeSvcsRS.getString(1); long serviceID = activeSvcsRS.getLong(2); if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) { if (log.isDebugEnabled()) log.debug("handleNodeDown: " + nodeID + "/" + ipAddr + "/" + serviceID + " already down"); } else { long outageID = -1; ResultSet seqRS = getNextOutageIdStmt.executeQuery(); if (seqRS.next()) { outageID = seqRS.getLong(1); } seqRS.close(); newOutageWriter.setLong(1, outageID); newOutageWriter.setLong(2, eventID); newOutageWriter.setLong(3, nodeID); newOutageWriter.setString(4, ipAddr); newOutageWriter.setLong(5, serviceID); newOutageWriter.setTimestamp(6, convertEventTimeIntoTimestamp(eventTime)); newOutageWriter.executeUpdate(); if (log.isDebugEnabled()) log.debug("handleNodeDown: Recording outage for " + nodeID + "/" + ipAddr + "/" + serviceID); } } activeSvcsRS.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Outage recorded for all active services for " + nodeID); } catch (SQLException se) { log.warn("Rolling back transaction, nodeDown could not be recorded for nodeId: " + nodeID, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } activeSvcsStmt.close(); openStmt.close(); newOutageWriter.close(); } catch (SQLException sqle) { log.warn("SQL exception while handling \'nodeDown\'", sqle); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: private static void loadCommandList() { final URL url; try { url = IOUtils.getResource(null, PYTHON_MENU_FILE); } catch (final FileNotFoundException ex) { log.error("File '" + PYTHON_MENU_FILE + "': " + ex.getMessage()); return; } final List<String> cmdList = new ArrayList<String>(); try { final InputStream inputStream = url.openStream(); try { final Reader reader = new InputStreamReader(inputStream, IOUtils.MAP_ENCODING); try { final BufferedReader bufferedReader = new BufferedReader(reader); try { while (true) { final String inputLine = bufferedReader.readLine(); if (inputLine == null) { break; } final String line = inputLine.trim(); if (line.length() > 0 && !line.startsWith("#")) { final int k = line.indexOf('('); if (k > 0) { cmdList.add(line.substring(0, k) + "()"); } else { log.error("Parse error in " + url + ":"); log.error(" \"" + line + "\" missing '()'"); cmdList.add(line + "()"); } } } Collections.sort(cmdList, String.CASE_INSENSITIVE_ORDER); if (!cmdList.isEmpty()) { menuEntries = cmdList.toArray(new String[cmdList.size()]); } } finally { bufferedReader.close(); } } finally { reader.close(); } } finally { inputStream.close(); } } catch (final FileNotFoundException ex) { log.error("File '" + url + "' not found: " + ex.getMessage()); } catch (final EOFException ignored) { } catch (final UnsupportedEncodingException ex) { log.error("Cannot decode file '" + url + "': " + ex.getMessage()); } catch (final IOException ex) { log.error("Cannot read file '" + url + "': " + ex.getMessage()); } } Code Sample 2: private void copyFileNFS(String sSource, String sTarget) throws Exception { FileInputStream fis = new FileInputStream(sSource); FileOutputStream fos = new FileOutputStream(sTarget); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buf = new byte[2048]; int i = 0; while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i); bis.close(); bos.close(); fis.close(); fos.close(); }
00
Code Sample 1: public void connect(final URLConnectAdapter urlAdapter) { if (this.connectSettings == null) { throw new IllegalStateException("Invalid Connect Settings (is null)"); } final HttpURLConnection httpConnection = (HttpURLConnection) urlAdapter.openConnection(); BufferedReader in; try { in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); final StringBuilder buf = new StringBuilder(200); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append('\n'); } final ConnectResult result = new ConnectResult(httpConnection.getResponseCode(), buf.toString()); final Map<String, List<String>> headerFields = httpConnection.getHeaderFields(); for (Map.Entry<String, List<String>> entry : headerFields.entrySet()) { final String key = entry.getKey(); final List<String> val = entry.getValue(); if ((val != null) && (val.size() > 1)) { System.out.println("WARN: Invalid header value : " + key + " url=" + this.connectSettings.getUrl()); } if (key != null) { result.addHeader(key, val.get(0), val); } else { result.addHeader("Status", val.get(0), val); } } this.lastResult = result; } catch (IOException e) { throw new ConnectException(e); } } Code Sample 2: private static void downloadImage(URL url, String localFileName) { FileOutputStream fos = null; URL fileUrl = null; Bundle bundle = Activator.getDefault().getBundle(); Path path = new Path("album covers/empty_disk.jpg"); URL localUrl = FileLocator.find(bundle, path, Collections.EMPTY_MAP); try { fileUrl = FileLocator.toFileURL(localUrl); } catch (IOException e) { e.printStackTrace(); } try { InputStream is = url.openStream(); String actualPath = fileUrl.getPath(); actualPath = actualPath.substring(1); actualPath = actualPath.substring(0, actualPath.lastIndexOf("/")); fos = new FileOutputStream(actualPath + "/" + localFileName); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { OutputStream out = new FileOutputStream(new File(directory, entry.getName())); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; } Code Sample 2: public Function findFunction(String functionName) { String code = ""; UserFunction function = (UserFunction) getCachedFunction(functionName); if (function != null) return function; ErrorLogger.debugLine("MFileWebLoader: loading >" + functionName + ".m<"); try { URL url = new URL(codeBase, directory + "/" + functionName + ".m"); InputStream in = url.openStream(); BufferedReader inReader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = inReader.readLine()) != null) { code += line + "\n"; } inReader.close(); } catch (Exception e) { Errors.throwMathLibException("MFileWebLoader: m-file exception via web"); } ErrorLogger.debugLine("MFileWebLoader: code: begin \n" + code + "\ncode end"); FunctionParser funcParser = new FunctionParser(); function = funcParser.parseFunction(code); function.setName(functionName); cacheFunction(function); ErrorLogger.debugLine("MFileWebLoader: finished webloading >" + functionName + ".m<"); return function; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
00
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 String getSource(String urlAdd) throws Exception { HttpURLConnection urlConnection = null; URL url = new URL(urlAdd); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(timeout); if (!urlConnection.getContentType().contains("text/html")) { throw new Exception(); } if (urlConnection.getResponseCode() != 200) { throw new Exception(); } encoding = getPageEncoding(urlConnection); if (encoding == null) { encoding = defaultEncoding; } InputStream in = url.openStream(); byte[] buffer = new byte[12288]; StringBuffer sb = new StringBuffer(); int bytesRead = 0; while ((bytesRead = in.read(buffer)) != -1) { String reads = new String(buffer, 0, bytesRead, encoding); sb.append(reads); } in.close(); return sb.toString(); }
00
Code Sample 1: private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5; StringBuilder sbValueBeforeHash = new StringBuilder(); try { md5 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new ApplicationIllegalArgumentException(e); } long time = System.nanoTime(); long rand = 0; if (secure) { rand = MySecureRand.nextLong(); } else { rand = MyRand.nextLong(); } sbValueBeforeHash.append(SId); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(time)); sbValueBeforeHash.append(":"); sbValueBeforeHash.append(Long.toString(rand)); valueBeforeHash = sbValueBeforeHash.toString(); md5.update(valueBeforeHash.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterHash = sb.toString(); }
00
Code Sample 1: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } } Code Sample 2: protected static int[] sort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }
00
Code Sample 1: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } } Code Sample 2: public static String crypt(String password, String salt) { if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } int saltEnd = salt.indexOf('$'); if (saltEnd != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } MessageDigest md5_1, md5_2; try { md5_1 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_1.update(password.getBytes()); md5_1.update(magic.getBytes()); md5_1.update(salt.getBytes()); try { md5_2 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } md5_2.update(password.getBytes()); md5_2.update(salt.getBytes()); md5_2.update(password.getBytes()); byte[] md5_2_digest = md5_2.digest(); int md5Size = md5_2_digest.length; int pwLength = password.length(); for (int i = pwLength; i > 0; i -= md5Size) { md5_1.update(md5_2_digest, 0, i > md5Size ? md5Size : i); } md5_2.reset(); byte[] pwBytes = password.getBytes(); for (int i = pwLength; i > 0; i >>= 1) { if ((i & 1) == 1) { md5_1.update((byte) 0); } else { md5_1.update(pwBytes[0]); } } StringBuffer output = new StringBuffer(magic); output.append(salt); output.append("$"); byte[] md5_1_digest = md5_1.digest(); byte[] saltBytes = salt.getBytes(); for (int i = 0; i < 1000; i++) { md5_2.reset(); if ((i & 1) == 1) { md5_2.update(pwBytes); } else { md5_2.update(md5_1_digest); } if (i % 3 != 0) { md5_2.update(saltBytes); } if (i % 7 != 0) { md5_2.update(pwBytes); } if ((i & 1) != 0) { md5_2.update(md5_1_digest); } else { md5_2.update(pwBytes); } md5_1_digest = md5_2.digest(); } int value; value = ((md5_1_digest[0] & 0xff) << 16) | ((md5_1_digest[6] & 0xff) << 8) | (md5_1_digest[12] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[1] & 0xff) << 16) | ((md5_1_digest[7] & 0xff) << 8) | (md5_1_digest[13] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[2] & 0xff) << 16) | ((md5_1_digest[8] & 0xff) << 8) | (md5_1_digest[14] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[3] & 0xff) << 16) | ((md5_1_digest[9] & 0xff) << 8) | (md5_1_digest[15] & 0xff); output.append(cryptTo64(value, 4)); value = ((md5_1_digest[4] & 0xff) << 16) | ((md5_1_digest[10] & 0xff) << 8) | (md5_1_digest[5] & 0xff); output.append(cryptTo64(value, 4)); value = md5_1_digest[11] & 0xff; output.append(cryptTo64(value, 2)); md5_1 = null; md5_2 = null; md5_1_digest = null; md5_2_digest = null; pwBytes = null; saltBytes = null; password = salt = null; return output.toString(); }
00
Code Sample 1: private InputStream getStreamFromUrl(URL url, String notFoundMessage) throws ApolloAdapterException { InputStream stream = null; if (url == null) { String message = "Couldn't find url for " + filename; logger.error(message); throw new ApolloAdapterException(message); } if (url != null) { try { stream = url.openStream(); } catch (IOException e) { logger.error(e.getMessage(), e); stream = null; throw new ApolloAdapterException(e); } } return stream; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } } Code Sample 2: void readData(URL url) throws IOException { int i = 0, j = 0, k = 0; double xvalue, yvalue; double xindex, yindex; InputStream is = url.openStream(); is.mark(0); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int columnsize = 0; double temp_prev = 0; double temp_new = 0; int first = 0; s = br.readLine(); StringTokenizer st = new StringTokenizer(s); columnsize = Integer.parseInt(st.nextToken()); data = new double[columnsize][100][100]; isize = 0; jsize = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); for (k = 0; k < columnsize; k++) { temp_new = Double.parseDouble(st.nextToken()); if (first == 0) { temp_prev = temp_new; first = 1; } if (k == 0) { if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } } data[k][i][j] = temp_new; } j++; } isize = i + 1; jsize = j; }
00
Code Sample 1: public static String md5(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[FOUR_BYTES]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public ProcessorOutput createOutput(String name) { ProcessorOutput output = new ProcessorImpl.CacheableTransformerOutputImpl(getClass(), name) { protected void readImpl(org.orbeon.oxf.pipeline.api.PipelineContext context, final ContentHandler contentHandler) { ProcessorInput i = getInputByName(INPUT_DATA); try { Grammar grammar = (Grammar) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) { final Locator[] locator = new Locator[1]; GrammarReader grammarReader = new XMLSchemaReader(new GrammarReaderController() { public void error(Locator[] locators, String s, Exception e) { throw new ValidationException(s, e, new LocationData(locators[0])); } public void warning(Locator[] locators, String s) { throw new ValidationException(s, new LocationData(locators[0])); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = URLFactory.createURL((locator[0] != null && locator[0].getSystemId() != null) ? locator[0].getSystemId() : null, systemId); InputSource i = new InputSource(url.openStream()); i.setSystemId(url.toString()); return i; } }); readInputAsSAX(context, input, new ForwardingContentHandler(grammarReader) { public void setDocumentLocator(Locator loc) { super.setDocumentLocator(loc); locator[0] = loc; } }); return grammarReader.getResultAsGrammar(); } }); DocumentDeclaration vgm = new REDocumentDeclaration(grammar.getTopLevel(), new ExpressionPool()); Verifier verifier = new Verifier(vgm, new ErrorHandler()) { boolean stopDecorating = false; private void generateErrorElement(ValidationException ve) throws SAXException { if (decorateOutput && ve != null) { if (!stopDecorating) { AttributesImpl a = new AttributesImpl(); a.addAttribute("", ValidationProcessor.MESSAGE_ATTRIBUTE, ValidationProcessor.MESSAGE_ATTRIBUTE, "CDATA", ve.getSimpleMessage()); a.addAttribute("", ValidationProcessor.SYSTEMID_ATTRIBUTE, ValidationProcessor.SYSTEMID_ATTRIBUTE, "CDATA", ve.getLocationData().getSystemID()); a.addAttribute("", ValidationProcessor.LINE_ATTRIBUTE, ValidationProcessor.LINE_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getLine())); a.addAttribute("", ValidationProcessor.COLUMN_ATTRIBUTE, ValidationProcessor.COLUMN_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getCol())); contentHandler.startElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT, a); contentHandler.endElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT); stopDecorating = true; } } else { throw ve; } } public void characters(char[] chars, int i, int i1) throws SAXException { try { super.characters(chars, i, i1); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.characters(chars, i, i1); } public void endDocument() throws SAXException { try { super.endDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endDocument(); } public void endElement(String s, String s1, String s2) throws SAXException { try { super.endElement(s, s1, s2); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endElement(s, s1, s2); } public void startDocument() throws SAXException { try { super.startDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startDocument(); } public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException { ((ErrorHandler) getErrorHandler()).setElement(s, s1); try { super.startElement(s, s1, s2, attributes); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startElement(s, s1, s2, attributes); } public void endPrefixMapping(String s) { try { super.endPrefixMapping(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.endPrefixMapping(s); } catch (SAXException se) { throw new OXFException(se.getException()); } } public void processingInstruction(String s, String s1) { try { super.processingInstruction(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.processingInstruction(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) { try { super.skippedEntity(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getMessage()); } } try { contentHandler.skippedEntity(s); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void startPrefixMapping(String s, String s1) { try { super.startPrefixMapping(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.startPrefixMapping(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } }; readInputAsSAX(context, getInputByName(INPUT_DATA), verifier); } catch (Exception e) { throw new OXFException(e); } } }; addOutput(name, output); return output; }
11
Code Sample 1: private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } } Code Sample 2: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
00
Code Sample 1: public RobotList<Float> sort_incr_Float(RobotList<Float> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i)); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Float> sol = new RobotList<Float>(Float.class); for (int i = 0; i < length; i++) { sol.addLast(new Float(distri[i].value)); } return sol; } Code Sample 2: public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } }
00
Code Sample 1: private void SaveLoginInfo() { int iSize; try { if (m_bSavePwd) { byte[] MD5PWD = new byte[80]; java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal"; java.io.File file = new java.io.File(szPath); if (!file.exists()) file.mkdirs(); file = new java.io.File(file, "user.dat"); if (!file.exists()) file.createNewFile(); java.io.FileOutputStream pw = new java.io.FileOutputStream(file); iSize = m_PwdList.size(); for (int iIndex = 0; iIndex < iSize; iIndex++) { md.reset(); md.update(((String) m_UsrList.get(iIndex)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i = 0; i < DESUSR.length; i++) alpha += DESUSR[i]; String pwd = (String) m_PwdList.get(iIndex); if (pwd.length() > 0) { java.util.Arrays.fill(MD5PWD, (byte) 0); int iLen = pwd.length(); pw.write(iLen); for (int i = 0; i < iLen; i++) { int iDiff = (int) pwd.charAt(i) + (int) alpha; int c = iDiff % 256; MD5PWD[i] = (byte) c; pw.write((byte) c); } } else pw.write(0); } pw.flush(); } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } } Code Sample 2: private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } }
11
Code Sample 1: @Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } } Code Sample 2: private boolean downloadFile(Proxy proxy, URL url, File file) { try { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = new File(file.getAbsolutePath() + ".update"); ; FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); file.delete(); destFile.renameTo(file); return true; } catch (Exception e) { logger.error("Failed to get remote hosts file.", e); } return false; }
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 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: private void insert() throws SQLException, NamingException { Logger logger = getLogger(); if (logger.isDebugEnabled()) { logger.debug("enter - " + getClass().getName() + ".insert()"); } try { if (logger.isInfoEnabled()) { logger.info("insert(): Create new sequencer record for " + getName()); } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dataSourceName); conn = ds.getConnection(); conn.setReadOnly(false); stmt = conn.prepareStatement(INSERT_SEQ); stmt.setString(INS_NAME, getName()); stmt.setLong(INS_NEXT_KEY, defaultInterval * 2); stmt.setLong(INS_INTERVAL, defaultInterval); stmt.setLong(INS_UPDATE, System.currentTimeMillis()); try { if (stmt.executeUpdate() != 1) { nextId = -1L; logger.warn("insert(): Failed to create sequencer entry for " + getName() + " (no error message)"); } else if (logger.isInfoEnabled()) { nextId = defaultInterval; nextSeed = defaultInterval * 2; interval = defaultInterval; logger.info("insert(): First ID will be " + nextId); } } catch (SQLException e) { logger.warn("insert(): Error inserting row into database, possible concurrency issue: " + e.getMessage()); if (logger.isDebugEnabled()) { e.printStackTrace(); } nextId = -1L; } if (!conn.getAutoCommit()) { conn.commit(); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (conn != null) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException ignore) { } } try { conn.close(); } catch (SQLException ignore) { } } } } finally { if (logger.isDebugEnabled()) { logger.debug("exit - " + getClass().getName() + ".insert()"); } } } Code Sample 2: public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
00
Code Sample 1: public String load(URL url) throws LoaderException { log.debug("loading content"); log.trace("opening connection: " + url); BufferedReader in = null; URLConnection conn = null; try { conn = url.openConnection(); in = null; if (encodedProxyLogin != null) { conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedProxyLogin); } } catch (IOException ioe) { log.warn("Error create connection"); throw new LoaderException("Error create connection", ioe); } log.trace("connection opened, reading ... "); StringBuilder buffer = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } catch (IOException ioe) { log.warn("Error loading content"); throw new LoaderException("Error reading content. ", ioe); } finally { try { in.close(); } catch (Exception e) { } } log.debug("content loaded"); return buffer.toString(); } Code Sample 2: public static final String generate(String value) { try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(value.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } value = hexString.toString(); } catch (Exception nsae) { nsae.printStackTrace(); } return value; }
11
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
00
Code Sample 1: public void copyFile(File source, File destination) { try { FileInputStream sourceStream = new FileInputStream(source); try { FileOutputStream destinationStream = new FileOutputStream(destination); try { FileChannel sourceChannel = sourceStream.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationStream.getChannel()); } finally { try { destinationStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } finally { try { sourceStream.close(); } catch (Exception e) { throw new RuntimeIoException(e, IoMode.CLOSE); } } } catch (IOException e) { throw new RuntimeIoException(e, IoMode.COPY); } } Code Sample 2: public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
00
Code Sample 1: public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } Code Sample 2: private static void identify(ContentNetwork cn, String str) { try { URL url = new URL(str); HttpURLConnection con = (HttpURLConnection) url.openConnection(); UrlUtils.setBrowserHeaders(con, null); String key = "cn." + cn.getID() + ".identify.cookie"; String cookie = COConfigurationManager.getStringParameter(key, null); if (cookie != null) { con.setRequestProperty("Cookie", cookie + ";"); } con.setRequestProperty("Connection", "close"); con.getResponseCode(); cookie = con.getHeaderField("Set-Cookie"); if (cookie != null) { String[] bits = cookie.split(";"); if (bits.length > 0 && bits[0].length() > 0) { COConfigurationManager.setParameter(key, bits[0]); } } } catch (Throwable e) { } }
00
Code Sample 1: public String getSHA1(String input) { byte[] output = null; try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes()); output = md.digest(); } catch (Exception e) { System.out.println("Exception: " + e); } return StringUtils.byte2hex(output); } Code Sample 2: private URL resolveRedirects(URL url, int redirectCount) throws IOException { URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) uc; huc.setInstanceFollowRedirects(false); huc.connect(); int responseCode = huc.getResponseCode(); String location = huc.getHeaderField("location"); huc.disconnect(); if ((responseCode == HttpURLConnection.HTTP_MOVED_TEMP) && (redirectCount < 5)) { try { URL newUrl = new URL(location); return resolveRedirects(newUrl, redirectCount + 1); } catch (MalformedURLException ex) { return url; } } else return url; } else return url; }
00
Code Sample 1: public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: private void getViolationsReportBySLATIdYearMonth() throws IOException { String xmlFile10Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportBySLATIdYearMonth.xml"; URL url10; url10 = new URL(bmReportingWSUrl); URLConnection connection10 = url10.openConnection(); HttpURLConnection httpConn10 = (HttpURLConnection) connection10; FileInputStream fin10 = new FileInputStream(xmlFile10Send); ByteArrayOutputStream bout10 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin10, bout10); fin10.close(); byte[] b10 = bout10.toByteArray(); httpConn10.setRequestProperty("Content-Length", String.valueOf(b10.length)); httpConn10.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn10.setRequestProperty("SOAPAction", soapAction); httpConn10.setRequestMethod("POST"); httpConn10.setDoOutput(true); httpConn10.setDoInput(true); OutputStream out10 = httpConn10.getOutputStream(); out10.write(b10); out10.close(); InputStreamReader isr10 = new InputStreamReader(httpConn10.getInputStream()); BufferedReader in10 = new BufferedReader(isr10); String inputLine10; StringBuffer response10 = new StringBuffer(); while ((inputLine10 = in10.readLine()) != null) { response10.append(inputLine10); } in10.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: getViolationsReportBySLATIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response10.toString()); }
11
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: public String copyImages(Document doc, String sXML, String newPath, String tagName, String itemName) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { nl = doc.getElementsByTagName(tagName); for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem(itemName); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath; if (itemName.equals("data")) sSourcePath = sOldPath; else sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = newPath + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).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(); } sXML = sXML.replace(nsrc.getTextContent(), sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sXML; }