label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public static boolean compress(ArrayList sources, File target, Manifest manifest) { try { if (sources == null || sources.size() == 0) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); String baseDir = ((File) sources.get(0)).getParentFile().getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); ArrayList list = new ArrayList(); for (Iterator it = sources.iterator(); it.hasNext(); ) { File fileOrDir = (File) it.next(); if (isJar && (manifest != null) && fileOrDir.getName().equals("META-INF")) continue; if (fileOrDir.isDirectory()) list.addAll(getContents(fileOrDir)); else list.add(fileOrDir); } byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
Code Sample 2:
protected UnicodeList(URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); String line; line = br.readLine(); chars = new ArrayList(); while ((line = br.readLine()) != null) { String[] parts = GUIHelper.split(line, ";"); if (parts[0].length() >= 5) continue; if (parts.length < 2 || parts[0].length() != 4) { System.out.println("Strange line: " + line); } else { if (parts.length > 10 && parts[1].equals("<control>")) { parts[1] = parts[1] + ": " + parts[10]; } try { Integer.parseInt(parts[0], 16); chars.add(parts[0] + parts[1]); } catch (NumberFormatException ex) { System.out.println("No number: " + line); } } } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
public void test2() throws Exception { SpreadsheetDocument document = new SpreadsheetDocument(); Sheet sheet = new Sheet("Planilha 1"); sheet.setLandscape(true); Row row = new Row(); row.setHeight(20); sheet.getMerges().add(new IntegerCellMerge(0, 0, 0, 5)); sheet.getImages().add(new Image(new FileInputStream("D:/image001.jpg"), 0, 0, ImageType.JPEG, 80, 60)); for (int i = 0; i < 10; i++) { Cell cell = new Cell(); cell.setValue("Celula " + i); cell.setBackgroundColor(new Color(192, 192, 192)); cell.setUnderline(true); cell.setBold(true); cell.setItalic(true); cell.setFont("Times New Roman"); cell.setFontSize(10); cell.setFontColor(new Color(255, 0, 0)); Border border = new Border(); border.setWidth(1); border.setColor(new Color(0, 0, 0)); cell.setLeftBorder(border); cell.setTopBorder(border); cell.setRightBorder(border); cell.setBottomBorder(border); row.getCells().add(cell); sheet.getColumnsWith().put(new Integer(i), new Integer(25)); } sheet.getRows().add(row); document.getSheets().add(sheet); FileOutputStream fos = new FileOutputStream("D:/teste2.xls"); SpreadsheetDocumentWriter writer = HSSFSpreadsheetDocumentWriter.getInstance(); writer.write(document, fos); fos.close(); }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
|
00
|
Code Sample 1:
public synchronized void checkout() throws SQLException, InterruptedException { Connection con = this.session.open(); con.setAutoCommit(false); String sql_stmt = DB2SQLStatements.shopping_cart_getAll(this.customer_id); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sql_stmt); res.last(); int rowcount = res.getRow(); res.beforeFirst(); ShoppingCartItem[] resArray = new ShoppingCartItem[rowcount]; int i = 0; while (res.next()) { resArray[i] = new ShoppingCartItem(); resArray[i].setCustomer_id(res.getInt("customer_id")); resArray[i].setDate_start(res.getDate("date_start")); resArray[i].setDate_stop(res.getDate("date_stop")); resArray[i].setRoom_type_id(res.getInt("room_type_id")); resArray[i].setNumtaken(res.getInt("numtaken")); resArray[i].setTotal_price(res.getInt("total_price")); i++; } this.wait(4000); try { for (int j = 0; j < rowcount; j++) { sql_stmt = DB2SQLStatements.room_date_update(resArray[j]); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } } catch (SQLException e) { e.printStackTrace(); con.rollback(); } for (int j = 0; j < rowcount; j++) { System.out.println(j); sql_stmt = DB2SQLStatements.booked_insert(resArray[j], 2); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } sql_stmt = DB2SQLStatements.shopping_cart_deleteAll(this.customer_id); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); con.commit(); this.session.close(con); }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { LOGGER.info("Copying file '" + src.getAbsolutePath() + "' to '" + dst.getAbsolutePath() + "'"); FileChannel in = null; FileChannel out = null; try { FileInputStream fis = new FileInputStream(src); in = fis.getChannel(); FileOutputStream fos = new FileOutputStream(dst); out = fos.getChannel(); out.transferFrom(in, 0, in.size()); } finally { try { if (in != null) in.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (out != null) { try { out.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
|
11
|
Code Sample 1:
private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
Code Sample 2:
public static String getMD5(String _pwd) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(_pwd.getBytes()); return toHexadecimal(new String(md.digest()).getBytes()); } catch (NoSuchAlgorithmException x) { x.printStackTrace(); return ""; } }
|
00
|
Code Sample 1:
public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private String generateServiceId(ObjectName mbeanName) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(mbeanName.toString().getBytes()); StringBuffer hexString = new StringBuffer(); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString().toUpperCase(); } catch (Exception ex) { RuntimeException runTimeEx = new RuntimeException("Unexpected error during MD5 hash creation, check your JRE"); runTimeEx.initCause(ex); throw runTimeEx; } }
Code Sample 2:
public static String SHA1(String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public APIResponse create(User user) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/user/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(user, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create User Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
@Override public DownloadObject download() throws IOException { final HttpGet findLink = new HttpGet(url.toString()); final HttpResponse response = this.client.execute(findLink); final String body = IOUtil.getString(response); LinkTag linkTag = null; try { linkTag = HtmlParserUtil.findLink(MegaUploadDownloader.DOWNLOAD_LINK_PATTERN, body); } catch (ParserException e) { } if (linkTag != null) { String link = linkTag.extractLink(); final String filename = IOUtil.getBaseName(link).trim(); link = link.replaceAll("&#[0-9]*;", "_"); final URL url = new URL(link); final String newLink = link.replaceAll(Pattern.quote(IOUtil.getBaseName(url.getPath())), URLEncoder.encode(IOUtil.getBaseName(url.getPath()), "UTF-8")); final HttpGet download = new HttpGet(newLink); final HttpResponse downloadResponse = this.client.execute(download); final HttpEntity downloadEntity = downloadResponse.getEntity(); final long filesize = downloadEntity.getContentLength(); return createObject(downloadEntity.getContent(), filename, filesize); } else { throw new RuntimeException("No download link."); } }
|
11
|
Code Sample 1:
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()); }
Code Sample 2:
private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
|
00
|
Code Sample 1:
protected int insertRecord(PutMetadataRequest request, PutMetadataInfo info) throws ImsServiceException, SQLException { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; ResultSet rs = null; int nRows = 0; String sXml = info.getXml(); String sUuid = info.getUuid(); String sName = info.getName(); String sThumbnailBinary = info.getThumbnailBinary(); String sTable = this.getResourceTableName(); String sDataTable = this.getResourceDataTableName(); long id = doesRecordExist(sTable, sUuid); try { ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); if (id < 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO ").append(sTable); sql.append(" ("); sql.append("DOCUUID,"); sql.append("TITLE,"); sql.append("OWNER"); sql.append(")"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; st.setString(n++, sUuid); st.setString(n++, sName); st.setInt(n++, this.publisher.getLocalID()); nRows = st.executeUpdate(); closeStatement(st); if (nRows > 0) { if (getIsDbCaseSensitive(this.getRequestContext())) { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE UPPER(docuuid)=?"); } else { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE docuuid=?"); } st.setString(1, sUuid.toUpperCase()); rs = st.executeQuery(); rs.next(); id = rs.getLong(1); closeStatement(st); request.setActionStatus(ImsRequest.ACTION_STATUS_OK); sql = new StringBuffer(); sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID,ID,XML)"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setLong(2, id); st.setString(3, sXml); st.executeUpdate(); } } else { this.authorize(request, sUuid); StringBuffer sql = new StringBuffer(); sql.append("UPDATE ").append(sTable); sql.append(" SET "); if (!request.getLockTitle()) { sql.append("TITLE=?, "); } sql.append("OWNER=?, "); sql.append("UPDATEDATE=?"); sql.append(" WHERE DOCUUID=?"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; if (!request.getLockTitle()) { st.setString(n++, sName); } st.setInt(n++, this.publisher.getLocalID()); st.setTimestamp(n++, new Timestamp(System.currentTimeMillis())); st.setString(n++, sUuid); nRows = st.executeUpdate(); if (nRows > 0) { request.setActionStatus(ImsRequest.ACTION_STATUS_REPLACED); } closeStatement(st); sql = new StringBuffer(); if (doesRecordExist(sDataTable, sUuid) >= 0) { sql.append("UPDATE ").append(sDataTable); sql.append(" SET DOCUUID=?, XML=?, THUMBNAIL=?"); sql.append(" WHERE ID=?"); } else { sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID, XML,THUMBNAIL,ID)"); sql.append(" VALUES(?,?,?,?)"); } logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setString(2, sXml); st.setBytes(3, null); st.setLong(4, id); st.executeUpdate(); } con.commit(); } catch (ImsServiceException ex) { if (con != null) { con.rollback(); } throw ex; } catch (SQLException ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeResultSet(rs); closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } if ((sThumbnailBinary != null) && (sThumbnailBinary.length() > 0)) { this.updateThumbnail(sThumbnailBinary, sUuid); } return nRows; }
Code Sample 2:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/jar"); byte[] bufor = new byte[BUF_LEN]; ServletContext context = getServletContext(); URL url = context.getResource(FILE_NAME); InputStream in = url.openStream(); OutputStream out = response.getOutputStream(); while (in.read(bufor) != -1) out.write(bufor); in.close(); out.close(); }
|
11
|
Code Sample 1:
public String encryptPassword(String password) { StringBuffer encPasswd = new StringBuffer(); try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } return encPasswd.toString(); }
Code Sample 2:
private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); }
|
00
|
Code Sample 1:
private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); }
|
00
|
Code Sample 1:
public void delete(String remoteFile) { String remotePath = connector.getRemoteDirectory(); remotePath += PATH_SEPARATOR + remoteFile; FTPClient ftp = new FTPClient(); try { String hostname = connector.getUrl().getHost(); ftp.connect(hostname); log.info("Connected to " + hostname); log.info(ftp.getReplyString()); boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword()); if (loggedIn) { ftp.deleteFile(remotePath); ftp.logout(); } ftp.disconnect(); } catch (SocketException e) { log.error("File chmod failed with message: " + e.getMessage()); } catch (IOException e) { log.error("File chmod failed with message: " + e.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
Code Sample 2:
@DeclarePerfMonTimer("SortingTest.bubbleSort") private void bubbleSort(int values[]) { int len = values.length - 1; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i; j++) { if (values[j] > values[j + 1]) { int tmp = values[j]; values[j] = values[j + 1]; values[j + 1] = tmp; } } } }
|
00
|
Code Sample 1:
public static String loadPage(URL url) throws IOException { Reader in = null; URLConnection uc; HttpURLConnection huc = null; try { uc = url.openConnection(); if (uc instanceof HttpURLConnection) { huc = (HttpURLConnection) uc; huc.setInstanceFollowRedirects(false); huc.connect(); in = new InputStreamReader(huc.getInputStream()); StringBuilder sb = new StringBuilder(); int c; while ((c = in.read()) != -1) sb.append((char) c); return sb.toString(); } else return null; } finally { try { if (in != null) in.close(); if (huc != null) huc.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } } }
Code Sample 2:
public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); }
|
11
|
Code Sample 1:
public static String crypt(String password, String salt) throws java.security.NoSuchAlgorithmException { int saltEnd; int len; int value; int i; MessageDigest hash1; MessageDigest hash2; byte[] digest; byte[] passwordBytes; byte[] saltBytes; StringBuffer result; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if ((saltEnd = salt.indexOf('$')) != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } hash1 = MessageDigest.getInstance("MD5"); hash1.update(password.getBytes()); hash1.update(magic.getBytes()); hash1.update(salt.getBytes()); hash2 = MessageDigest.getInstance("MD5"); hash2.update(password.getBytes()); hash2.update(salt.getBytes()); hash2.update(password.getBytes()); digest = hash2.digest(); for (len = password.length(); len > 0; len -= 16) { hash1.update(digest, 0, len > 16 ? 16 : len); } passwordBytes = password.getBytes(); for (i = password.length(); i > 0; i >>= 1) { if ((i & 1) == 1) { hash1.update((byte) 0); } else { hash1.update(passwordBytes, 0, 1); } } result = new StringBuffer(magic); result.append(salt); result.append("$"); digest = hash1.digest(); saltBytes = salt.getBytes(); for (i = 0; i < 1000; i++) { hash2.reset(); if ((i & 1) == 1) { hash2.update(passwordBytes); } else { hash2.update(digest); } if (i % 3 != 0) { hash2.update(saltBytes); } if (i % 7 != 0) { hash2.update(passwordBytes); } if ((i & 1) != 0) { hash2.update(digest); } else { hash2.update(passwordBytes); } digest = hash2.digest(); } value = ((digest[0] & 0xff) << 16) | ((digest[6] & 0xff) << 8) | (digest[12] & 0xff); result.append(to64(value, 4)); value = ((digest[1] & 0xff) << 16) | ((digest[7] & 0xff) << 8) | (digest[13] & 0xff); result.append(to64(value, 4)); value = ((digest[2] & 0xff) << 16) | ((digest[8] & 0xff) << 8) | (digest[14] & 0xff); result.append(to64(value, 4)); value = ((digest[3] & 0xff) << 16) | ((digest[9] & 0xff) << 8) | (digest[15] & 0xff); result.append(to64(value, 4)); value = ((digest[4] & 0xff) << 16) | ((digest[10] & 0xff) << 8) | (digest[5] & 0xff); result.append(to64(value, 4)); value = digest[11] & 0xff; result.append(to64(value, 2)); return result.toString(); }
Code Sample 2:
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); String format = req.getParameter("format"); EntityManager em = EMF.get().createEntityManager(); String uname = (req.getParameter("uname") == null) ? "" : req.getParameter("uname"); String passwd = (req.getParameter("passwd") == null) ? "" : req.getParameter("passwd"); String name = (req.getParameter("name") == null) ? "" : req.getParameter("name"); String email = (req.getParameter("email") == null) ? "" : req.getParameter("email"); if (uname == null || uname.equals("") || uname.length() < 4) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.unameTooShort(uname).toXML(em)); else resp.getWriter().print(Error.unameTooShort(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } if (User.fromUserName(em, uname) != null) { if (format != null && format.equals("xml")) resp.getWriter().print(Error.userExists(uname).toXML(em)); else resp.getWriter().print(Error.userExists(uname).toJSON(em)); resp.setStatus(HttpServletResponse.SC_CONFLICT); em.close(); return; } if (passwd.equals("") || passwd.length() < 6) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.passwdTooShort(uname).toXML(em)); else resp.getWriter().print(Error.passwdTooShort(uname).toJSON(em)); em.close(); return; } User u = new User(); u.setUsername(uname); u.setPasswd(passwd); u.setName(name); u.setEmail(email); u.setPaid(false); StringBuffer apikey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + uname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { apikey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } u.setApiKey(apikey.toString()); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(u); tx.commit(); } catch (Throwable t) { log.severe("Error adding user " + uname + " Reason:" + t.getMessage()); tx.rollback(); resp.setStatus(500); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); return; } log.info("User " + u.getName() + " was created successfully"); resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(u.toXML(em)); else resp.getWriter().print(u.toJSON(em)); em.close(); }
|
11
|
Code Sample 1:
public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("arguments: sourcefile destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); }
|
00
|
Code Sample 1:
private static String processRequest(String request, HttpMethod method) { SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); URI uri = null; try { uri = new URI(request); ClientHttpRequest clientHttpRequest = simpleClientHttpRequestFactory.createRequest(uri, method); ClientHttpResponse response = clientHttpRequest.execute(); InputStream bodyInputStream = response.getBody(); String body = org.apache.commons.io.IOUtils.toString(bodyInputStream); return body; } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
|
00
|
Code Sample 1:
protected InputStream openInputStream(String filename) throws FileNotFoundException { InputStream in = null; try { URL url = new URL(filename); in = url.openConnection().getInputStream(); logger.info("Opening file " + filename); } catch (FileNotFoundException e) { logger.error("Resource file not found: " + filename); throw e; } catch (IOException e) { logger.error("Resource file can not be readed: " + filename); throw new FileNotFoundException("Resource file can not be readed: " + filename); } if (in == null) { logger.error("Resource file not found: " + filename); throw new FileNotFoundException(filename); } return in; }
Code Sample 2:
public static String[] readStats() throws Exception { URL url = null; BufferedReader reader = null; StringBuilder stringBuilder; try { url = new URL("http://localhost:" + port + webctx + "/shared/js/libOO/health_check.sjs"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(10 * 1000); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString().split(","); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } }
|
00
|
Code Sample 1:
public void delete(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { String sql = "delete from LanguageMorphologies " + "where LanguageName = '" + language + "' and MorphologyTag = '" + tag + "' and " + " Rank = " + row; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); bumpAllRowsUp(stmt, language, tag, row); 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:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
|
00
|
Code Sample 1:
public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; }
Code Sample 2:
protected InputStream transform(URL url) throws IOException { TransformerFactory tf = TransformerFactory.newInstance(); InputStream xsl_is = null; InputStream url_is = null; ByteArrayOutputStream os = null; byte[] output; try { xsl_is = Classes.getThreadClassLoader().getResourceAsStream(getStylesheet()); url_is = new BufferedInputStream(url.openStream()); os = new ByteArrayOutputStream(); Transformer tr = tf.newTransformer(new StreamSource(xsl_is)); tr.transform(new StreamSource(url_is), new StreamResult(os)); output = os.toByteArray(); } catch (TransformerConfigurationException tce) { throw new IOException(tce.getLocalizedMessage()); } catch (TransformerException te) { throw new IOException(te.getLocalizedMessage()); } finally { try { if (os != null) os.close(); } catch (Throwable t) { } try { if (url_is != null) url_is.close(); } catch (Throwable t) { } try { if (xsl_is != null) xsl_is.close(); } catch (Throwable t) { } } if (logService.isEnabledFor(LogLevel.TRACE)) logService.log(LogLevel.TRACE, new String(output)); return new ByteArrayInputStream(output); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); }
|
00
|
Code Sample 1:
protected InputStream getInputStream(URL url) { InputStream is = null; if (url != null) { try { is = url.openStream(); } catch (Exception ex) { } } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (is == null) { try { is = classLoader.getResourceAsStream("osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("META-INF/osworkflow.xml"); } catch (Exception e) { } } if (is == null) { try { is = classLoader.getResourceAsStream("/META-INF/osworkflow.xml"); } catch (Exception e) { } } return is; }
Code Sample 2:
protected void writeToResponse(InputStream stream, HttpServletResponse response) throws IOException { OutputStream output = response.getOutputStream(); try { IOUtils.copy(stream, output); } finally { try { stream.close(); } finally { output.close(); } } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
|
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 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:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getLocalPrincipal", args = { }) public final void test_getLocalPrincipal() { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getLocalPrincipal(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } try { HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); assertNull(con.getLocalPrincipal()); con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); assertNotNull("Local principal is null", con.getLocalPrincipal()); } catch (Exception e) { fail("Unexpected exception " + e); } }
Code Sample 2:
public T08OTSDTMInterpositionUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
|
00
|
Code Sample 1:
public static String extractIconPath(String siteURL) throws IOException { siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String iconPath = null; String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; break; } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); siteURL = getHome(siteURL); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = siteURL; if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); } catch (Exception e) { } return iconPath; }
Code Sample 2:
@Override public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { URL baseUrl = this.baseUrl; if (this.baseUrl == null) { baseUrl = url; } InputStream in; try { in = url.openStream(); } catch (IOException ex) { throw new FileNotFoundException("Can't read " + url); } return load(new BufferedInputStream(in), baseUrl); }
|
00
|
Code Sample 1:
public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
Code Sample 2:
public void performSearch(int searchStartIndex) { int index = 0; String searchString = keywords.getText(); searchButton.setEnabled(false); if (!searchString.equals("")) { try { url = new URL(searchURL + "&num=" + maxReturns.getSelectedItem().toString() + "&start=" + searchStartIndex + "&q=" + searchString); System.out.println("Google search = " + url); InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } String googleResultsFile = VueUtil.getDefaultUserFolder().getAbsolutePath() + File.separatorChar + VueResources.getString("save.google.results"); FileWriter fileWriter = new FileWriter(googleResultsFile); fileWriter.write(result); fileWriter.close(); result = ""; GSP gsp = loadGSP(googleResultsFile); Iterator i = gsp.getRES().getResultList().iterator(); Vector resultVector = new Vector(); while (i.hasNext()) { Result r = (Result) i.next(); URLResource urlResource = new URLResource(r.getUrl()); if (r.getTitle() != null) urlResource.setTitle(r.getTitle().replaceAll("</*[a-zA-Z]>", "")); else urlResource.setTitle(r.getUrl().toString()); resultVector.add(urlResource); System.out.println(r.getTitle() + " " + r.getUrl()); } VueDragTree tree = new VueDragTree(resultVector.iterator(), "GoogleSearchResults"); tree.setEditable(true); tree.setRootVisible(false); googleResultsPanel.remove(jsp); jsp = new JScrollPane(tree); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 0)); bottomPanel.add(prevButton); bottomPanel.add(nextButton); googleResultsPanel.add(bottomPanel, BorderLayout.SOUTH); googleResultsPanel.add(jsp, BorderLayout.CENTER); googleResultsPanel.validate(); googlePane.setSelectedComponent(googleResultsPanel); } catch (Exception ex) { System.out.println("cannot connect google"); googleResultsPanel.remove(jsp); JPanel jp = new JPanel(new BorderLayout()); jp.setBackground(Color.WHITE); JLabel jl = new JLabel("No Match Found"); jp.add(jl, BorderLayout.NORTH); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 0)); googleResultsPanel.add(jp, BorderLayout.CENTER); googleResultsPanel.validate(); googlePane.setSelectedComponent(googleResultsPanel); } } searchButton.setEnabled(true); }
|
11
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } }
Code Sample 2:
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
|
11
|
Code Sample 1:
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
Code Sample 2:
public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek (stepan@geek.cz)"); return; } } }
|
00
|
Code Sample 1:
public static String convertToSha1(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public void loadSample(String uid, URL url) throws Exception { AudioInputStream input = AudioSystem.getAudioInputStream(url.openStream()); Clip line = null; DataLine.Info info = new DataLine.Info(Clip.class, input.getFormat()); if (!AudioSystem.isLineSupported(info)) { throw new javax.sound.sampled.UnsupportedAudioFileException(url.toExternalForm()); } line = (Clip) AudioSystem.getLine(info); line.open(input); samples.put(uid, line); }
|
11
|
Code Sample 1:
protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) { String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.'); String methodName = getMethodName(par); String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName; PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey); if (gr != null) { _sharedAddData.cacheInfo.incCombinePredicateCacheHit(); return gr; } else { _sharedAddData.cacheInfo.incCombinePredicateCacheMiss(); } String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred"; ClassFile predicateCF = null; File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class"); if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) { try { predicateCF = new ClassFile(new FileInputStream(clonedFile)); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { _templatePredicateClassFile.write(baos); predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate template class file", ioe); } } clonedFile.getParentFile().mkdirs(); final ArrayList<String> paramNames = new ArrayList<String>(); final HashMap<String, String> paramTypes = new HashMap<String, String>(); performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() { public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) { paramNames.add(param1); paramTypes.put(param1, param2); return null; } }, ""); ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>(); for (String key : par.combinedPredicates.keySet()) { for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) { if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) { memberPARs.add(memberPAR); } else { memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor)); } } } AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool()); int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem }); predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem }); predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null); predicateCF.setThisClass(predicateClassItem); StringBuilder sb = new StringBuilder(); sb.append("(Ljava/lang/Object;"); if (par.passArguments) { sb.append("[Ljava/lang/Object;"); } for (String key : paramNames) { sb.append(paramTypes.get(key)); } sb.append(")Z"); String methodDesc = sb.toString(); MethodInfo templateMI = null; MethodInfo predicateMI = null; for (MethodInfo mi : predicateCF.getMethods()) { if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) { predicateMI = mi; break; } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) { templateMI = mi; } } if ((templateMI == null) && (predicateMI == null)) { throw new ThreadCheckException("Could not find template predicate method in class file"); } if (predicateMI == null) { AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi }); namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi }); descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>(); for (AAttributeInfo a : templateMI.getAttributes()) { try { AAttributeInfo clonedA = (AAttributeInfo) a.clone(); list.add(clonedA); } catch (CloneNotSupportedException e) { throw new InstrumentorException("Could not clone method attributes"); } } predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {})); predicateCF.getMethods().add(predicateMI); CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties(); props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0); InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode()); if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) { il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); } else { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); } boolean res; res = il.advanceIndex(); assert res == true; int accumVarIndex = props.maxLocals - 1; AInstruction loadAccumInstr; AInstruction storeAccumInstr; if (accumVarIndex < 256) { loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex); storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex); } else { byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 }; Types.bytesFromShort((short) accumVarIndex, bytes, 1); loadAccumInstr = new WideInstruction(bytes); bytes[0] = Opcode.ISTORE; storeAccumInstr = new WideInstruction(bytes); } il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int maxStack = 0; int paramIndex = 1; int lvIndex = 1; if (par.passArguments) { lvIndex += 1; } int memberCount = 0; for (PredicateAnnotationRecord memberPAR : memberPARs) { ++memberCount; il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int curStack = 1; if (memberPAR.passArguments) { if (par.passArguments) { il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; curStack += 1; } } for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) { String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex)); if (t.length() == 0) { throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } byte opcode; int nextLVIndex = lvIndex; switch(t.charAt(0)) { case 'I': case 'B': case 'C': case 'S': case 'Z': opcode = Opcode.ILOAD; nextLVIndex += 1; curStack += 1; break; case 'F': opcode = Opcode.FLOAD; nextLVIndex += 1; curStack += 1; break; case '[': case 'L': opcode = Opcode.ALOAD; nextLVIndex += 1; curStack += 1; break; case 'J': opcode = Opcode.LLOAD; nextLVIndex += 2; curStack += 2; break; case 'D': opcode = Opcode.DLOAD; nextLVIndex += 2; curStack += 2; break; default: throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex); il.insertInstr(load, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; ++paramIndex; lvIndex = nextLVIndex; } if (curStack > maxStack) { maxStack = curStack; } ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0); int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString()); predicateCallInstr.setReference(predicateCallIndex); il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if (par.combineMode == Combine.Mode.OR) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) { il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.IMPLIES) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else { assert false; } res = il.advanceIndex(); assert res == true; il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1); il.insertInstr(br2, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int jumpIndex = il.getIndex(); il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; res = il.rewindIndex(3); assert res == true; BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex); il.insertInstr(br1, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(4); assert res == true; } else { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.deleteInstr(predicateMI.getCodeAttributeInfo()); predicateMI.getCodeAttributeInfo().setCode(il.getCode()); props.maxStack = Math.max(maxStack, 2); predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals); try { FileOutputStream fos = new FileOutputStream(clonedFile); predicateCF.write(fos); fos.close(); } catch (IOException e) { throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile); } } gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>()); _generatedPredicateRecords.put(hashKey, gr); return gr; }
Code Sample 2:
private boolean get(String surl, File dst, Get get) throws IOException { boolean ret = false; InputStream is = null; OutputStream os = null; try { try { if (surl.startsWith("file://")) { is = new FileInputStream(surl.substring(7)); } else { URL url = new URL(surl); is = url.openStream(); } if (is != null) { os = new FileOutputStream(dst); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } } catch (ConnectException ex) { log("Connect exception " + ex.getMessage(), ex, 3); if (dst.exists()) dst.delete(); } catch (UnknownHostException ex) { log("Unknown host " + ex.getMessage(), ex, 3); } catch (FileNotFoundException ex) { log("File not found: " + ex.getMessage(), 3); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } if (ret) { try { is = new FileInputStream(dst); os = new FileOutputStream(getCachedFile(get)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
|
11
|
Code Sample 1:
protected void checkWeavingJar() throws IOException { OutputStream out = null; try { final File weaving = new File(getWeavingPath()); if (!weaving.exists()) { new File(getWeavingFolder()).mkdir(); weaving.createNewFile(); final Path src = new Path("weaving/openfrwk-weaving.jar"); final InputStream in = FileLocator.openStream(getBundle(), src, false); out = new FileOutputStream(getWeavingPath(), true); IOUtils.copy(in, out); Logger.log(Logger.INFO, "Put weaving jar at location " + weaving); } else { Logger.getLog().info("File openfrwk-weaving.jar already exists at " + weaving); } } catch (final SecurityException e) { Logger.log(Logger.ERROR, "[SECURITY EXCEPTION] Not enough privilegies to create " + "folder and copy NexOpen weaving jar at location " + getWeavingFolder()); Logger.logException(e); } finally { if (out != null) { out.flush(); out.close(); } } }
Code Sample 2:
public JavaCodeAnalyzer(String filenameIn, String filenameOut, String lineLength) { try { File tmp = File.createTempFile("JavaCodeAnalyzer", "tmp"); BufferedReader br = new BufferedReader(new FileReader(filenameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(tmp)); while (br.ready()) { out.write(br.read()); } br.close(); out.close(); jco = new JavaCodeOutput(tmp, filenameOut, lineLength); SourceCodeParser p = new JavaCCParserFactory().createParser(new FileReader(tmp), null); List statements = p.parseCompilationUnit(); ListIterator it = statements.listIterator(); eh = new ExpressionHelper(this, jco); Node n; printLog("Parsed file " + filenameIn + "\n"); while (it.hasNext()) { n = (Node) it.next(); parseObject(n); } tmp.delete(); } catch (Exception e) { System.err.println(getClass() + ": " + e); } }
|
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 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); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); 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:
protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; }
Code Sample 2:
public static String postRequest(String url, String content) throws IOException { InputStream is = null; ByteArrayOutputStream buf = new ByteArrayOutputStream(); String result = null; try { Object obj = openConnection(url, content, "POST", "text/xml"); if (obj instanceof InputStream) { is = (InputStream) obj; } else { return "Cannot open a connection with " + url + " : " + obj.toString(); } int c = is.read(); while (c != -1) { buf.write(c); c = is.read(); } result = new String(buf.toByteArray()); } finally { if (is != null) { is.close(); } if (buf != null) { buf.close(); } } return result; }
|
00
|
Code Sample 1:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
Code Sample 2:
void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); }
|
11
|
Code Sample 1:
@Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
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; }
|
00
|
Code Sample 1:
public static BufferedReader getUserSolveStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/status/" + name.toLowerCase() + "/signedlist/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
Code Sample 2:
private static boolean loadResources(String ext) { InputStream in; try { URL url = Thread.currentThread().getContextClassLoader().getResource("bg/plambis/dict/local/i18n" + ext + ".xml"); if (url == null) return false; in = url.openStream(); } catch (IOException e1) { e1.printStackTrace(); return false; } try { Serializer serializer = new Persister(); resources = serializer.read(TextResource.class, in); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } }
Code Sample 2:
public HttpURLConnection execute(S3Bucket pBucket, S3Object pObject, S3OperationParameters pOpParams) throws S3Exception { S3OperationParameters opParams = pOpParams; if (opParams == null) opParams = new S3OperationParameters(); HttpURLConnection result = null; URL url = getURL(pBucket, pObject, opParams.getQueryParameters()); mLogger.log(Level.FINEST, "URL: " + url.toString()); opParams.addDateHeader(); switch(mStyle) { case Path: opParams.addHostHeader(BASE_DOMAIN); break; case Subdomain: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName() + "." + BASE_DOMAIN); break; case VirtualHost: if (pBucket == null) opParams.addHostHeader(BASE_DOMAIN); else opParams.addHostHeader(pBucket.getName()); break; } if (opParams.isSign()) { StringBuilder sb = new StringBuilder(); sb.append(opParams.getVerb().toString()); sb.append(NEWLINE); sb.append(posHeader(MD5, opParams.getRequestHeaders())); sb.append(posHeader(TYPE, opParams.getRequestHeaders())); if (opParams.getQueryParameters().has(EXPIRES)) { sb.append(opParams.getQueryParameters().get(EXPIRES).getValue()); sb.append(NEWLINE); } else { sb.append(posHeader(DATE, opParams.getRequestHeaders())); } sb.append(canonicalizeAmazonHeaders(opParams.getRequestHeaders())); try { sb.append("/"); if (pBucket != null) { sb.append(URLEncoder.encode(pBucket.getName(), URL_ENCODING)); sb.append("/"); if (pObject != null) { sb.append(URLEncoder.encode(pObject.getKey(), URL_ENCODING)); } } sb.append(opParams.getQueryParameters().getAmazonSubresources().toQueryString()); String signThis = sb.toString(); mLogger.log(Level.FINEST, "String being signed: " + signThis); String sig = encode(mCredential.getMSecretAccessKey(), signThis, false); sb = new StringBuilder(); sb.append("AWS "); sb.append(mCredential.getMAccessKeyID()); sb.append(":"); sb.append(sig); opParams.addAuthorizationHeader(sb.toString()); } catch (UnsupportedEncodingException e) { throw new S3Exception("URL encoding not supported: " + URL_ENCODING, e); } } try { killHostVerifier(); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) throw new S3Exception("URLConnection is not instance of HttpURLConnection!"); result = (HttpURLConnection) urlConn; result.setRequestMethod(opParams.getVerb().toString()); mLogger.log(Level.FINEST, "HTTP Operation: " + opParams.getVerb().toString()); if (opParams.getVerb() == HttpVerb.PUT) { result.setDoOutput(true); } result.setRequestProperty(TYPE, ""); for (AWSParameter param : opParams.getRequestHeaders()) { result.setRequestProperty(param.getName(), param.getValue()); mLogger.log(Level.FINEST, "Header " + param.getName() + ": " + param.getValue()); } } catch (IOException e) { throw new S3Exception("Problem opening connection to URL: " + url.toString(), e); } return result; }
|
00
|
Code Sample 1:
protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } }
Code Sample 2:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static String getServerVersion() throws IOException { URL url; url = new URL(CHECKVERSIONURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(false); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); InputStream in = httpURLConnection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); out.flush(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); String buffer; String[] lines; String version = ""; buffer = out.toString(); lines = StringUtils.split(buffer); for (int i = 0; i < lines.length; i++) { if (lines[i].startsWith("version=")) { version = lines[i].substring(8).trim(); break; } } return version; }
|
11
|
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:
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.substring(8, 24).toString().toUpperCase(); }
|
00
|
Code Sample 1:
private ResponseStatus performHandshake(String url) throws IOException { HttpURLConnection connection = Caller.getInstance().openConnection(url); InputStream is = connection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); int statusCode = ResponseStatus.codeForStatus(status); ResponseStatus responseStatus; if (statusCode == ResponseStatus.OK) { this.sessionId = r.readLine(); this.nowPlayingUrl = r.readLine(); this.submissionUrl = r.readLine(); responseStatus = new ResponseStatus(statusCode); } else if (statusCode == ResponseStatus.FAILED) { responseStatus = new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } else { return new ResponseStatus(statusCode); } r.close(); return responseStatus; }
Code Sample 2:
public void update(String target, String cfgVersion) throws MalformedURLException, FileNotFoundException, IOException { Debug.log("Config Updater", "Checking for newer configuration..."); URL url = new URL(target); String[] urlSplit = target.split("/"); this.fileName = urlSplit[urlSplit.length - 1]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(Main.getHomeDir() + "tmp-" + this.fileName)); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); fileSize += numRead; } Debug.log("Config Updater", "Read latest configuration: " + fileSize + " bytes"); in.close(); out.close(); XMLController xmlC = new XMLController(); String newFileVersion = xmlC.readCfgVersion(Main.getHomeDir() + "tmp-" + this.fileName); if (new File(Main.getHomeDir() + this.fileName).exists()) { Debug.log("Config Updater", "Local configfile '" + Main.getHomeDir() + this.fileName + "' exists (version " + cfgVersion + ")"); if (Double.parseDouble(newFileVersion) > Double.parseDouble(cfgVersion)) { Debug.log("Config Updater", "Removing old config and replacing it with version " + newFileVersion); new File(Main.getHomeDir() + this.fileName).delete(); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } else { new File(Main.getHomeDir() + "tmp-" + this.fileName).delete(); Debug.log("Config Updater", "I already have the latest version " + cfgVersion); } } else { Debug.log("Config Updater", "Local config doesn't exist. Loading the new one, version " + newFileVersion); new File(Main.getHomeDir() + "tmp-" + this.fileName).renameTo(new File(Main.getHomeDir() + this.fileName)); this.result = "ConfigFile upgraded to version " + newFileVersion; } Debug.log("Config Updater", "Update of configuration done"); }
|
11
|
Code Sample 1:
@Override protected void setUp() throws Exception { this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); File repoFolder = new File("target/repository"); removeRepository(repoFolder); InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE); File tempRepoConfigFile = File.createTempFile("repository", "xml"); tempRepoConfigFile.deleteOnExit(); OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile); try { IOUtils.copy(repoConfigIn, tempRepoConfigOut); } finally { repoConfigIn.close(); tempRepoConfigOut.close(); } Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository"); ServerAdapterFactory factory = new ServerAdapterFactory(); RemoteRepository remoteRepo = factory.getRemoteRepository(repo); reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); reg.rebind(REMOTE_REPO_NAME, remoteRepo); session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE); InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE); JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), ""); }
Code Sample 2:
@Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); }
|
11
|
Code Sample 1:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Account acc = (Account) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ACCOUNT")); pst.setInt(1, acc.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
Code Sample 2:
public int commit() throws TransactionException, SQLException, ConnectionFactoryException { Connection conn = ConnectionFactoryProxy.getInstance().getConnection(_poolName); conn.setAutoCommit(false); int numRowsUpdated = 0; try { Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); PreparedStatement ps = conn.prepareStatement(sd.statement); Iterator params = sd.params.iterator(); int index = 1; while (params.hasNext()) { ps.setString(index++, (String) params.next()); } numRowsUpdated += ps.executeUpdate(); } conn.commit(); } catch (SQLException ex) { System.err.println("com.zenark.zsql.TransactionImpl.commit() failed: Queued Statements follow"); Iterator statements = _statements.iterator(); while (statements.hasNext()) { StatementData sd = (StatementData) statements.next(); System.err.println("+--Statement: " + sd.statement + " with " + sd.params.size() + " parameters"); for (int loop = 0; loop < sd.params.size(); loop++) { System.err.println("+--Param : " + (String) sd.params.get(loop)); } } throw ex; } finally { _statements.clear(); conn.rollback(); conn.clearWarnings(); ConnectionFactoryProxy.getInstance().releaseConnection(conn); } return numRowsUpdated; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws ParseException, FileNotFoundException, IOException { InputStream input = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); Translator t = new Translator(input, "UTF8"); Node template = Translator.Start(); File langs = new File("support/support/translate/languages"); for (File f : langs.listFiles()) { if (f.getName().endsWith(".lng")) { input = new BufferedInputStream(new FileInputStream(f)); try { Translator.ReInit(input, "UTF8"); } catch (java.lang.NullPointerException e) { new Translator(input, "UTF8"); } Node newFile = Translator.Start(); ArrayList<Addition> additions = new ArrayList<Addition>(); syncKeys(template, newFile, additions); ArrayList<String> fileLines = new ArrayList<String>(); Scanner scanner = new Scanner(new BufferedReader(new FileReader(f))); while (scanner.hasNextLine()) { fileLines.add(scanner.nextLine()); } int offset = 0; for (Addition a : additions) { System.out.println("Key added " + a + " to " + f.getName()); if (a.afterLine < 0 || a.afterLine >= fileLines.size()) { fileLines.add(a.getAddition(0)); } else { fileLines.add(a.afterLine + (offset++) + 1, a.getAddition(0)); } } f.delete(); Writer writer = new BufferedWriter(new FileWriter(f)); for (String s : fileLines) writer.write(s + "\n"); writer.close(); System.out.println("Language " + f.getName() + " had " + additions.size() + " additions"); } } File defFile = new File(langs, "language.lng"); defFile.delete(); defFile.createNewFile(); InputStream copyStream = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); OutputStream out = new BufferedOutputStream(new FileOutputStream(defFile)); int c = 0; while ((c = copyStream.read()) >= 0) out.write(c); out.close(); System.out.println("Languages updated."); }
Code Sample 2:
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) { } } } }
|
00
|
Code Sample 1:
private static File copyJarToPool(File file) { File outFile = new File(RizzToolConstants.TOOL_POOL_FOLDER.getAbsolutePath() + File.separator + file.getName()); if (file != null && file.exists() && file.canRead()) { try { FileChannel inChan = new FileInputStream(file).getChannel(); FileChannel outChan = new FileOutputStream(outFile).getChannel(); inChan.transferTo(0, inChan.size(), outChan); return outFile; } catch (Exception ex) { RizzToolConstants.DEFAULT_LOGGER.error("Exception while copying jar file to tool pool [inFile=" + file.getAbsolutePath() + "] [outFile=" + outFile.getAbsolutePath() + ": " + ex); } } else { RizzToolConstants.DEFAULT_LOGGER.error("Could not copy jar file. File does not exist or can't read file. [inFile=" + file.getAbsolutePath() + "]"); } return null; }
Code Sample 2:
public static Vector getKeywordsFromURL(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_lc_line = null; Vector x_words = new Vector(1000); int x_body = -1; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_body = x_lc_line.indexOf("<body"); if (x_body != -1) { x_line = x_line.substring(x_body + 5); break; } } boolean x_status = false; int x_end = -1; if (x_lc_line == null) { System.out.println("No <body start"); return null; } do { x_lc_line = x_line.toLowerCase(); x_end = x_lc_line.indexOf("</body>"); if (x_end != -1) { extractOutsideText(x_line.substring(0, x_end), "<", ">", x_words, x_status); break; } x_status = extractOutsideText(x_line, "<", ">", x_words, x_status); } while ((x_line = x_reader.readLine()) != null); return x_words; }
|
00
|
Code Sample 1:
private void initSerializerFiles(String fileName, HashSet<String> fileList, HashMap<Class, Class> classMap, Class type) { try { ClassLoader classLoader = getClassLoader(); if (classLoader == null) return; Enumeration iter; iter = classLoader.getResources(fileName); while (iter.hasMoreElements()) { URL url = (URL) iter.nextElement(); if (fileList.contains(url.toString())) continue; fileList.add(url.toString()); InputStream is = null; try { is = url.openStream(); Properties props = new Properties(); props.load(is); for (Map.Entry entry : props.entrySet()) { String apiName = (String) entry.getKey(); String serializerName = (String) entry.getValue(); Class apiClass = null; Class serializerClass = null; try { apiClass = Class.forName(apiName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + apiName + " is not available in this context: " + getClassLoader()); continue; } try { serializerClass = Class.forName(serializerName, false, classLoader); } catch (ClassNotFoundException e) { log.fine(url + ": " + serializerName + " is not available in this context: " + getClassLoader()); continue; } if (!type.isAssignableFrom(serializerClass)) throw new HessianException(url + ": " + serializerClass.getName() + " is invalid because it does not implement " + type.getName()); classMap.put(apiClass, serializerClass); } } finally { if (is != null) is.close(); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new HessianException(e); } }
Code Sample 2:
public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + "LDAPBaseServer"); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + "LDAPBaseServer"); Iterator<LDAPModification> it = mods.iterator(); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); int id = this.getId(dn, con); while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() == LDAPModification.REPLACE) { String attributeName = mod.getAttribute().getName(); if (attributeName.equals(db2ldap.get("first")) || attributeName.equals(db2ldap.get("last"))) { PreparedStatement ps = con.prepareStatement("UPDATE USERS SET " + (attributeName.equals(db2ldap.get("first")) ? "first" : "last") + "=? WHERE username=?"); ps.setString(1, mod.getAttribute().getStringValue()); ps.setString(2, uid); ps.executeUpdate(); ps.close(); } else if (attributeName.equals(db2ldap.get("username"))) { throw new LDAPException("Can not modify the rdn", LDAPException.NOT_ALLOWED_ON_RDN, "Can not perform modify"); } else if (attributeName.equals(db2ldap.get("name"))) { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("INSERT INTO locationmap (person,location) VALUES (?,?)"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); String[] vals = mod.getAttribute().getStringValueArray(); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } } else if (mod.getOp() == LDAPModification.DELETE) { if (mod.getAttribute().getName().equals(db2ldap.get("name"))) { String[] vals = mod.getAttribute().getStringValueArray(); if (vals.length == 0) { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=?"); ps.setInt(1, id); ps.executeUpdate(); ps.close(); } else { PreparedStatement ps = con.prepareStatement("DELETE FROM locationmap WHERE person=? and location=?"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } } else { throw new LDAPException("Can not delete attribute " + mod.getAttribute().getName(), LDAPException.INVALID_ATTRIBUTE_SYNTAX, ""); } } else if (mod.getOp() == LDAPModification.ADD) { if (mod.getAttribute().getName().equals(db2ldap.get("name"))) { String[] vals = mod.getAttribute().getStringValueArray(); PreparedStatement ps = con.prepareStatement("INSERT INTO locationmap (person,location) VALUES (?,?)"); PreparedStatement pssel = con.prepareStatement("SELECT id FROM LOCATIONS WHERE name=?"); for (int i = 0; i < vals.length; i++) { pssel.setString(1, vals[i]); ResultSet rs = pssel.executeQuery(); if (!rs.next()) { con.rollback(); throw new LDAPException("Location " + vals[i] + " does not exist", LDAPException.OBJECT_CLASS_VIOLATION, "Location " + vals[i] + " does not exist"); } int lid = rs.getInt("id"); ps.setInt(1, id); ps.setInt(2, lid); ps.executeUpdate(); } ps.close(); pssel.close(); } else { throw new LDAPException("Can not delete attribute " + mod.getAttribute().getName(), LDAPException.INVALID_ATTRIBUTE_SYNTAX, ""); } } } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
|
00
|
Code Sample 1:
private static List<CountryEntry> retrieveCountries() throws IOException { URL url = new URL("http://" + ISO_3166_HOST + ISO_3166_TXT_FILE_PATH); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); List<CountryEntry> countries = new LinkedList<CountryEntry>(); boolean parsing = false; int trCount = 0; int tdCount = 0; CountryEntry current = new CountryEntry(); String nextLine = input.readLine(); while (nextLine != null) { if (nextLine.startsWith("<table")) { parsing = true; } if (nextLine.startsWith("</table>")) { break; } if (parsing) { if (nextLine.startsWith("<tr")) { trCount++; } else { if ((trCount > 1 && nextLine.startsWith("<td"))) { tdCount++; String data = pullData(nextLine); switch(tdCount) { case 1: current.setName(getCountryName(data)); break; case 2: current.setNumber(data); break; case 3: current.setAlpha3(data); break; case 4: current.setAlpha2(data); break; case 5: countries.add(current); current = new CountryEntry(); tdCount = 0; break; default: String msg = "Parsing error. Unexpected column: [" + data + "]"; throw new IllegalStateException(msg); } } } } nextLine = input.readLine(); } input.close(); return countries; }
Code Sample 2:
public static String encrypt(String text) { final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; String result = ""; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes()); byte[] hash = digest.digest(); char buffer[] = new char[hash.length * 2]; for (int i = 0, x = 0; i < hash.length; i++) { buffer[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; buffer[x++] = HEX_CHARS[hash[i] & 0xf]; } result = new String(buffer); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } }
Code Sample 2:
public RemotePolicyMigrator createRemotePolicyMigrator() { return new RemotePolicyMigrator() { public String migratePolicy(InputStream stream, String url) throws ResourceMigrationException, IOException { ByteArrayOutputCreator oc = new ByteArrayOutputCreator(); IOUtils.copyAndClose(stream, oc.getOutputStream()); return oc.getOutputStream().toString(); } }; }
|
00
|
Code Sample 1:
public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "a@b.c"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
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) { } } } }
|
00
|
Code Sample 1:
public static synchronized String encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
private static byte[] get256RandomBits() throws IOException { URL url = null; try { url = new URL(SRV_URL); } catch (MalformedURLException e) { e.printStackTrace(); } HttpsURLConnection hu = (HttpsURLConnection) url.openConnection(); hu.setConnectTimeout(2500); InputStream is = hu.getInputStream(); byte[] content = new byte[is.available()]; is.read(content); is.close(); hu.disconnect(); byte[] randomBits = new byte[32]; String line = new String(content); Matcher m = DETAIL.matcher(line); if (m.find()) { for (int i = 0; i < 32; i++) randomBits[i] = (byte) (Integer.parseInt(m.group(1).substring(i * 2, i * 2 + 2), 16) & 0xFF); } return randomBits; }
|
00
|
Code Sample 1:
public HttpClient(String urlString, String jsonMessage) throws Exception { this.jsonMessage = jsonMessage; connection = (HttpURLConnection) (new URL(urlString)).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "text/plain"); }
Code Sample 2:
protected void copyFile(File from, File to) throws IOException { to.getParentFile().mkdirs(); InputStream in = new FileInputStream(from); try { OutputStream out = new FileOutputStream(to); try { byte[] buf = new byte[1024]; int readLength; while ((readLength = in.read(buf)) > 0) { out.write(buf, 0, readLength); } } finally { out.close(); } } finally { in.close(); } }
|
00
|
Code Sample 1:
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
Code Sample 2:
public In(URL url) { try { URLConnection site = url.openConnection(); InputStream is = site.getInputStream(); scanner = new Scanner(is, charsetName); scanner.useLocale(usLocale); } catch (IOException ioe) { System.err.println("Could not open " + url); } }
|
00
|
Code Sample 1:
public static String openldapDigestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return OPENLDAP_MD5_PREFIX + base64; }
Code Sample 2:
protected void sendDoc(File indir, File outdir, File orig, Document doc, ServiceEndpoint ep) { ep.setMethod("simpleDocumentTransfer"); Document response = null; try { response = protocolHandler.sendMessage(ep, doc); } catch (TransportException e) { logger.warn("Message was not accepted, will try again later"); return; } String serial = String.valueOf(System.currentTimeMillis()); File origCopy = new File(outdir, orig.getName() + "." + serial); File respDrop = new File(outdir, orig.getName() + "." + serial + ".resp"); FileOutputStream respos = null; try { respos = new FileOutputStream(respDrop); serializeDocument(respos, response); } catch (IOException e) { logger.warn("Failed to dump response"); return; } finally { try { respos.close(); } catch (IOException ignored) { } } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[2048]; try { in = new FileInputStream(orig); out = new FileOutputStream(origCopy); int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy original"); return; } finally { try { in.close(); out.close(); } catch (IOException ignored) { } } orig.delete(); logger.info("File processed: " + orig.getName()); }
|
11
|
Code Sample 1:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
Code Sample 2:
private String processFileUploadOperation(boolean isH264File) { String fileType = this.uploadFileFileName.substring(this.uploadFileFileName.lastIndexOf('.')); int uniqueHashCode = UUID.randomUUID().toString().hashCode(); if (uniqueHashCode < 0) { uniqueHashCode *= -1; } String randomFileName = uniqueHashCode + fileType; String fileName = (isH264File) ? getproperty("videoDraftPath") : getproperty("videoDraftPathForNonH264") + randomFileName; File targetVideoPath = new File(fileName + randomFileName); System.out.println("Path: " + targetVideoPath.getAbsolutePath()); try { targetVideoPath.createNewFile(); FileChannel outStreamChannel = new FileOutputStream(targetVideoPath).getChannel(); FileChannel inStreamChannel = new FileInputStream(this.uploadFile).getChannel(); inStreamChannel.transferTo(0, inStreamChannel.size(), outStreamChannel); outStreamChannel.close(); inStreamChannel.close(); return randomFileName; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public void setTypeRefs(Connection conn) { log.traceln("\tProcessing " + table + " references.."); try { String query = " select distinct c.id, c.qualifiedname from " + table + ", CLASSTYPE c " + " where " + table + "." + reffield + " is null and " + table + "." + classnamefield + " = c.qualifiedname"; PreparedStatement pstmt = conn.prepareStatement(query); long start = new Date().getTime(); ResultSet rset = pstmt.executeQuery(); long queryTime = new Date().getTime() - start; log.debug("query time: " + queryTime + " ms"); String update = "update " + table + " set " + reffield + "=? where " + classnamefield + "=? and " + reffield + " is null"; PreparedStatement pstmt2 = conn.prepareStatement(update); int n = 0; start = new Date().getTime(); while (rset.next()) { n++; pstmt2.setInt(1, rset.getInt(1)); pstmt2.setString(2, rset.getString(2)); pstmt2.executeUpdate(); } queryTime = new Date().getTime() - start; log.debug("total update time: " + queryTime + " ms"); log.debug("number of times through loop: " + n); if (n > 0) log.debug("avg update time: " + (queryTime / n) + " ms"); pstmt2.close(); rset.close(); pstmt.close(); conn.commit(); log.verbose("Updated (committed) " + table + " references"); } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
Code Sample 2:
public void download(String target) { try { if (url == null) return; conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "Internet Explorer"); conn.setReadTimeout(10000); conn.connect(); httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); java.io.BufferedWriter out = new BufferedWriter(new FileWriter(target, false)); String str = httpReader.readLine(); while (str != null) { out.write(str); str = httpReader.readLine(); } out.close(); System.out.println("file download successfully: " + url.getHost() + url.getPath()); System.out.println("saved to: " + target); } catch (Exception e) { System.out.println("file download failed: " + url.getHost() + url.getPath()); e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public String getCipherString(String source) throws CadenaNoCifradaException { String encryptedSource = null; MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(source.getBytes(encoding), 0, source.length()); sha1hash = md.digest(); encryptedSource = convertToHex(sha1hash); } catch (Exception e) { throw new CadenaNoCifradaException(e); } return encryptedSource; }
|
00
|
Code Sample 1:
private void loadImage(URL url) { ImageData imageData; Image artworkImage = null; InputStream artworkStream = null; try { artworkStream = new BufferedInputStream(url.openStream()); imageData = new ImageLoader().load(artworkStream)[0]; Image tmpImage = new Image(getDisplay(), imageData); artworkImage = ImageUtilities.scaleImageTo(tmpImage, 128, 128); tmpImage.dispose(); } catch (Exception e) { } finally { if (artworkStream != null) { try { artworkStream.close(); } catch (IOException e) { e.printStackTrace(); } } } loadImage(artworkImage, url); }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
|
00
|
Code Sample 1:
public void bubblesort(String filenames[]) { for (int i = filenames.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { String temp; if (filenames[j].compareTo(filenames[j + 1]) > 0) { temp = filenames[j]; filenames[j] = filenames[j + 1]; filenames[j + 1] = temp; } } } }
Code Sample 2:
public ResourceMigrator createDefaultResourceMigrator(NotificationReporter reporter, boolean strictMode) throws ResourceMigrationException { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException { if (out != null) { close(); } FileChannel fch = new FileInputStream(from).getChannel(); FileChannel rollch = new FileOutputStream(to).getChannel(); long size = mark; int count = 0; try { while ((count += rollch.transferFrom(fch, count, size - count)) < size) { } } finally { fch.close(); rollch.close(); } out = create(to); return out; }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent ae) { Window win = SwingUtilities.getWindowAncestor(invokerInfo.getComponent()); if (ae.getActionCommand().equals(LOAD)) { URLChooser uc; if (win instanceof Frame) { uc = new URLChooser((Frame) win); } else { uc = new URLChooser((Dialog) win); } uc.setTitle("Load Prototype"); uc.setLabelText(" Prototype URL: "); uc.setNullSelectionValid(false); uc.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".xml") || f.isDirectory(); } public String getDescription() { return "XML Prototype Files"; } }); uc.setResourceFilter(new ResourceFilter() { public boolean accept(ResourceDescriptor rd) { return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE); } }); GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc); if (uc.showDialog(null)) { URL url = uc.getSelectedURL(); try { target.applyPrototype(url); } catch (Exception e) { JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Loading Prototype", JOptionPane.ERROR_MESSAGE); } } } else if (ae.getActionCommand().equals(SAVE)) { URLChooser uc; if (win instanceof Frame) { uc = new URLChooser((Frame) win); } else { uc = new URLChooser((Dialog) win); } uc.setTitle("Save Prototype"); uc.setLabelText(" Prototype URL: "); uc.setNullSelectionValid(false); uc.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().endsWith(".xml") || f.isDirectory(); } public String getDescription() { return "XML Prototype Files"; } }); uc.setResourceFilter(new ResourceFilter() { public boolean accept(ResourceDescriptor rd) { return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE); } }); GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc); if (uc.showDialog(null)) { URL url = uc.getSelectedURL(); try { PrintStream ps; HttpURLConnection huc = null; if (url.getProtocol().equals("file")) { ps = new PrintStream(new FileOutputStream(url.getFile())); } else { URLConnection urlc = url.openConnection(); urlc.setDoOutput(true); if (urlc instanceof HttpURLConnection) { huc = ((HttpURLConnection) urlc); huc.setRequestMethod("PUT"); } ps = new PrintStream(urlc.getOutputStream()); } target.writePrototype(ps); if (huc != null) { huc.getResponseCode(); } } catch (Exception e) { JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Saving Prototype", JOptionPane.ERROR_MESSAGE); } } } else if (ae.getActionCommand().equals(PUBLISH)) { PublishPrototypeDialog ppd; if (win instanceof Frame) { ppd = new PublishPrototypeDialog((Frame) win, target); } else { ppd = new PublishPrototypeDialog((Dialog) win, target); } GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), ppd); ppd.show(); } else if (ae.getActionCommand().equals(VIEW_EDIT)) { ViewEditPrototypeDialog vepd; if (win instanceof Frame) { vepd = new ViewEditPrototypeDialog((Frame) win, target); } else { vepd = new ViewEditPrototypeDialog((Dialog) win, target); } GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), vepd); vepd.show(); } }
Code Sample 2:
@NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
|
11
|
Code Sample 1:
public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } }
Code Sample 2:
public static void main(String[] args) throws FileNotFoundException, IOException { String filePath = "/Users/francisbaril/Downloads/test-1.pdf"; String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf"; File file = new File(filePath); final File testFile = new File(testFilePath); if (testFile.exists()) { testFile.delete(); } IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile)); System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID)); }
|
11
|
Code Sample 1:
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
Code Sample 2:
protected void saveSelectedFiles() { if (dataList.getSelectedRowCount() == 0) { return; } if (dataList.getSelectedRowCount() == 1) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow())); AttachFile entry = (AttachFile) obj; JFileChooser fc = new JFileChooser(); fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName())); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File current = entry.getCurrentPath(); File dest = fc.getSelectedFile(); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return; } else { JFileChooser fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { for (Integer idx : dataList.getSelectedRows()) { Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx)); AttachFile entry = (AttachFile) obj; File current = entry.getCurrentPath(); File dest = new File(fc.getSelectedFile(), entry.getName()); try { FileInputStream in = new FileInputStream(current); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return; } }
|
00
|
Code Sample 1:
private static void download(String urlString) throws IOException { URL url = new URL(urlString); url = handleRedirectUrl(url); URLConnection cn = url.openConnection(); Utils.setHeader(cn); long fileLength = cn.getContentLength(); Statics.getInstance().setFileLength(fileLength); long packageLength = fileLength / THREAD_COUNT; long leftLength = fileLength % THREAD_COUNT; String fileName = Utils.decodeURLFileName(url); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength)); CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1); long pos = 0; for (int i = 0; i < THREAD_COUNT; i++) { long endPos = pos + packageLength; if (leftLength > 0) { endPos++; leftLength--; } new Thread(new DownloadThread(latch, url, file, pos, endPos)).start(); pos = endPos; } new Thread(new MoniterThread(latch)).start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
Code Sample 2:
private void resourceDirectoryCopy(String resource, IProject project, String target, IProgressMonitor monitor) throws URISyntaxException, IOException, CoreException { if (!target.endsWith("/")) { target += "/"; } String res = resource; if (!res.endsWith("/")) ; { res += "/"; } Enumeration<URL> it = bundle.findEntries(resource, "*", false); while (it.hasMoreElements()) { URL url = it.nextElement(); File f = new File(FileLocator.toFileURL(url).toURI()); String fName = f.getName(); boolean skip = false; for (String skiper : skipList) { if (fName.equals(skiper)) { skip = true; break; } } if (skip) { continue; } String targetName = target + fName; if (f.isDirectory()) { IFolder folder = project.getFolder(targetName); if (!folder.exists()) { folder.create(true, true, monitor); } resourceDirectoryCopy(res + f.getName(), project, targetName, monitor); } else if (f.isFile()) { IFile targetFile = project.getFile(targetName); InputStream is = null; try { is = url.openStream(); if (targetFile.exists()) { targetFile.setContents(is, true, false, monitor); } else { targetFile.create(is, true, monitor); } } catch (Exception e) { throw new IOException(e); } finally { if (is != null) { is.close(); } } } } }
|
00
|
Code Sample 1:
public Vector _getSiteNames() { Vector _mySites = new Vector(); boolean gotSites = false; while (!gotSites) { try { URL dataurl = new URL(getDocumentBase(), siteFile); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String S = readme.readLine(); if (S == null) break; StringTokenizer st = new StringTokenizer(S); _mySites.addElement(st.nextToken()); } gotSites = true; } catch (IOException e) { _mySites.removeAllElements(); gotSites = false; } } return (_mySites); }
Code Sample 2:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void initialize() { List providers = new ArrayList(); while (this.urls.hasMoreElements()) { URL url = (URL) this.urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { String provider = uncommentLine(line).trim(); if (provider != null && provider.length() > 0) { providers.add(provider); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } this.iterator = providers.iterator(); }
|
11
|
Code Sample 1:
public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; }
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:
public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
Code Sample 2:
public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } }
|
00
|
Code Sample 1:
@SmallTest public void testSha1() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); int numTests = mTestData.length; for (int i = 0; i < numTests; i++) { digest.update(mTestData[i].input.getBytes()); byte[] hash = digest.digest(); String encodedHash = encodeHex(hash); assertEquals(encodedHash, mTestData[i].result); } }
Code Sample 2:
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
|
00
|
Code Sample 1:
public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); }
Code Sample 2:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } }
|
00
|
Code Sample 1:
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
Code Sample 2:
public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
|
11
|
Code Sample 1:
private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); }
Code Sample 2:
private byte[] hash(String data, HashAlg alg) { try { MessageDigest digest = MessageDigest.getInstance(alg.toString()); digest.update(data.getBytes()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { } return null; }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") public static <T> List<T> getServices(String service) { String serviceUri = "META-INF/services/" + service; ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Enumeration<URL> urls = loader.getResources(serviceUri); if (urls.hasMoreElements()) { List<T> services = new ArrayList<T>(1); Set<String> keys = new HashSet<String>(20); do { URL url = urls.nextElement(); if (_LOG.isLoggable(Level.FINEST)) { _LOG.finest("Processing: " + url); } try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); try { while (true) { String line = in.readLine(); if (line == null) break; String className = _parseLine(line); if (className != null && keys.add(className)) { T instance = (T) _getClass(loader, className); services.add(instance); } } } finally { in.close(); } } catch (Exception e) { if (_LOG.isLoggable(Level.WARNING)) { _LOG.log(Level.WARNING, "Error parsing URL: " + url, e); } } } while (urls.hasMoreElements()); if (services.size() == 1) return Collections.singletonList(services.get(0)); return Collections.unmodifiableList(services); } } catch (IOException e) { if (_LOG.isLoggable(Level.SEVERE)) { _LOG.log(Level.SEVERE, "Error loading Resource: " + serviceUri, e); } } return Collections.emptyList(); }
Code Sample 2:
public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); }
|
00
|
Code Sample 1:
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public static String getSignature(String s) { try { final AsciiEncoder coder = new AsciiEncoder(); final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(s.getBytes("UTF-8")); final byte[] digest = msgDigest.digest(); return coder.encode(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException(); } }
Code Sample 2:
private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } }
Code Sample 2:
@Test public void test01_ok_failed_500() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(chartURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
|
11
|
Code Sample 1:
protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = LocalNameGenerator.class.getResource("/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } }
Code Sample 2:
public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
|
00
|
Code Sample 1:
@NotNull public Set<Class<?>> in(Package pack) { String packageName = pack.getName(); String packageOnly = pack.getName(); final boolean recursive = true; Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); String packageDirName = packageOnly.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); } catch (IOException e) { throw new PackageScanFailedException("Could not read from package directory: " + packageDirName, e); } while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { try { findClassesInDirPackage(packageOnly, URLDecoder.decode(url.getFile(), "UTF-8"), recursive, classes); } catch (UnsupportedEncodingException e) { throw new PackageScanFailedException("Could not read from file: " + url, e); } } else if ("jar".equals(protocol)) { JarFile jar; try { jar = ((JarURLConnection) url.openConnection()).getJarFile(); } catch (IOException e) { throw new PackageScanFailedException("Could not read from jar url: " + url, e); } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } if ((idx != -1) || recursive) { if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); add(packageName, classes, className); } } } } } } return classes; }
Code Sample 2:
@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; } }
|
00
|
Code Sample 1:
@Test public void testConfigurartion() { try { Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties"); log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties")); log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml")); log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml")); if (log.isDebugEnabled()) { while (assemblersToRegister.hasMoreElements()) { URL url = (URL) assemblersToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); line = buff.readLine(); } buff.close(); in.close(); } } } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
|
11
|
Code Sample 1:
private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } }
Code Sample 2:
public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
11
|
Code Sample 1:
public static Boolean decompress(File source, File destination) { FileOutputStream outputStream; ZipInputStream inputStream; try { outputStream = null; inputStream = new ZipInputStream(new FileInputStream(source)); int read; byte buffer[] = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = inputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) new File(destination, zipEntry.getName()).mkdirs(); else { File fileEntry = new File(destination, zipEntry.getName()); fileEntry.getParentFile().mkdirs(); outputStream = new FileOutputStream(fileEntry); while ((read = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); outputStream.close(); } } inputStream.close(); } catch (Exception oException) { return false; } return true; }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
|
00
|
Code Sample 1:
private void downloadFile(File file, String url) { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final FileOutputStream outStream = new FileOutputStream(file); out = new BufferedOutputStream(outStream, IO_BUFFER_SIZE); byte[] bytes = new byte[IO_BUFFER_SIZE]; while (in.read(bytes) > 0) { out.write(bytes); } } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Code Sample 2:
public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; }
|
00
|
Code Sample 1:
public ProgramSymbol createNewProgramSymbol(int programID, String module, String symbol, int address, int size) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "INSERT INTO ProgramSymbols " + "(programID, module, symbol, address, size)" + " VALUES (" + programID + ", '" + module + "', '" + symbol + "', " + address + ", " + size + ")"; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * FROM ProgramSymbols WHERE " + "programID = " + programID + " AND " + "module = '" + module + "' AND " + "symbol = '" + symbol + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
Code Sample 2:
public void logout(String cookieString) throws NetworkException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_LOGOUT); if (cookieString != null && cookieString.length() != 0) get.setHeader("Cookie", cookieString); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
|
11
|
Code Sample 1:
public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } }
Code Sample 2:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
|
00
|
Code Sample 1:
public static int validate(String url) { HttpURLConnection con = null; try { con = (HttpURLConnection) (new URL(url)).openConnection(); } catch (MalformedURLException ex) { return -1; } catch (IOException ex) { return -2; } try { if (con != null && con.getResponseCode() != 200) { return con.getResponseCode(); } else if (con == null) { return -3; } } catch (IOException ex) { return -4; } return 1; }
Code Sample 2:
public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static void main(String[] args) { try { URL url = new URL("http://localhost:8080/axis/services/Tripcom?wsdl"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-type", "text/xml; charset=utf-8"); connection.setRequestProperty("SOAPAction", "http://tempuri.org/GetTime"); String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope " + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <rdTest xmlns=\"http://tempuri.org/\"> \n" + " <tns:rdTest message=\"tns:rdTest\"/> \n" + " </rdTest>" + " </soap:Body>\n" + "</soap:Envelope>"; byte[] bytes = msg.getBytes(); connection.setRequestProperty("Content-length", String.valueOf(bytes.length)); System.out.println("\nSOAP Aufruf:"); System.out.println("Content-type:" + connection.getRequestProperty("Content-type")); System.out.println("Content-length:" + connection.getRequestProperty("Content-length")); System.out.println("SOAPAction:" + connection.getRequestProperty("SOAPAction")); System.out.println(msg); OutputStream out = connection.getOutputStream(); out.write(bytes); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; System.out.println("\nServer Antwort:"); while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { System.out.println("FEHLER:" + e); } }
|
11
|
Code Sample 1:
static void copyFile(File file, File destDir) { File destFile = new File(destDir, file.getName()); if (destFile.exists() && (!destFile.canWrite())) { throw new SyncException("Cannot overwrite " + destFile + " because " + "it is read-only"); } try { FileInputStream in = new FileInputStream(file); try { FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new SyncException("I/O error copying " + file + " to " + destDir + " (message: " + e.getMessage() + ")", e); } if (!destFile.setLastModified(file.lastModified())) { throw new SyncException("Could not set last modified timestamp " + "of " + destFile); } }
Code Sample 2:
public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
public final void build() { if (!built_) { built_ = true; final boolean[] done = new boolean[] { false }; Runnable runnable = new Runnable() { public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } }; Thread t = new Thread(runnable, "VfsFileUrl connection " + getContentURL()); t.setPriority(Math.max(Thread.MIN_PRIORITY, t.getPriority() - 1)); t.start(); for (int i = 0; i < 100; i++) { if (done[0]) break; try { Thread.sleep(300L); } catch (InterruptedException ex) { } } if (!done[0]) { t.interrupt(); exists_ = false; canRead_ = false; FuLog.warning("VFS: fail to get " + url_); } } }
Code Sample 2:
protected InputSource loadExternalSdl(String aActualLocation) throws RuntimeException { logger.debug("loadExternalSdl(String) " + aActualLocation); try { URL url = new URL(aActualLocation); return new InputSource(url.openStream()); } catch (MalformedURLException e) { logger.error(e); throw new RuntimeException(aActualLocation + AeMessages.getString("AeWsdlLocator.ERROR_1"), e); } catch (IOException e) { logger.error(e); throw new RuntimeException(AeMessages.getString("AeWsdlLocator.ERROR_2") + aActualLocation, e); } }
|
11
|
Code Sample 1:
public static void copy(String sourceName, String destName, StatusWindow status) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = Utils.parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { if (status != null) { status.setMaximum(100); status.setMessage(Utils.trimFileName(src.toString(), 40), 50); } source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), 100); } if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); if (status != null) { status.setMaximum(files.length); } for (int i = 0; i < files.length; i++) { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), i); } targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath(), status); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
Code Sample 2:
public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); }
|
00
|
Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { log.log(Level.FINE, url.toString()); MSServletRequest urlManager = new MSServletRequest(url); MicroServlet servlet = getServlet(urlManager); return (new MSConnection(url, servlet, urlManager)); }
Code Sample 2:
@Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = new URL(System.getenv("plugg_home") + "/" + systemId); System.out.println("SystemId = " + systemId); return new InputSource(url.openStream()); }
|
00
|
Code Sample 1:
public static String downloadJar(URL url) throws IOException { String localFile = null; char[] buf = new char[4096]; int num; localFile = Settings.getFreeTsUserPath() + "lib" + Settings.SLASH + getURLFileName(url); DebugDialog.print("Downloading jar-file " + url + " to " + localFile + ".", 4); InputStreamReader in = new InputStreamReader(url.openStream()); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(localFile)); do { num = in.read(buf, 0, 4096); if (num > 0) { out.write(buf, 0, num); } } while (num > 0); in.close(); out.close(); return localFile; }
Code Sample 2:
@Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); }
|
11
|
Code Sample 1:
@Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; }
Code Sample 2:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) { System.out.write(x); } if (args.length == 1) { print("Checksum: " + csumi.getChecksum().getValue()); } bis.close(); } }
|
00
|
Code Sample 1:
public void sendShape(String s) { try { URLConnection uc = new URL(url + "&add=" + s).openConnection(); InputStream in = uc.getInputStream(); int b; while ((b = in.read()) != -1) { } in.close(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private static void discoverRegisteryEntries(DataSourceRegistry registry) { try { Enumeration<URL> urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
Code Sample 2:
public static final String getHash(int iterationNb, String password, String salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); byte[] input = digest.digest(password.getBytes("UTF-8")); for (int i = 0; i < iterationNb; i++) { digest.reset(); input = digest.digest(input); } String hashedValue = encoder.encode(input); LOG.finer("Creating hash '" + hashedValue + "' with iterationNb '" + iterationNb + "' and password '" + password + "' and salt '" + salt + "'!!"); return hashedValue; } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("Problem in the getHash method.", ex); } }
|
11
|
Code Sample 1:
public static void addIntegrityEnforcements(Session session) throws HibernateException { Transaction tx = null; try { tx = session.beginTransaction(); Statement st = session.connection().createStatement(); st.executeUpdate("DROP TABLE hresperformsrole;" + "CREATE TABLE hresperformsrole" + "(" + "hresid varchar(255) NOT NULL," + "rolename varchar(255) NOT NULL," + "CONSTRAINT hresperformsrole_pkey PRIMARY KEY (hresid, rolename)," + "CONSTRAINT ResourceFK FOREIGN KEY (hresid) REFERENCES resserposid (id) ON UPDATE CASCADE ON DELETE CASCADE," + "CONSTRAINT RoleFK FOREIGN KEY (rolename) REFERENCES role (rolename) ON UPDATE CASCADE ON DELETE CASCADE" + ");"); tx.commit(); } catch (Exception e) { tx.rollback(); } }
Code Sample 2:
public void setDefaultMailBox(final int domainId, final int userId) { final EmailAddress defaultMailbox = cmDB.getDefaultMailbox(domainId); try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty(defaultMailbox == null ? "domain.setDefaultMailbox" : "domain.updateDefaultMailbox")); if (defaultMailbox == null) { psImpl.setInt(1, domainId); psImpl.setInt(2, userId); } else { psImpl.setInt(1, userId); psImpl.setInt(2, domainId); } psImpl.executeUpdate(); } }); connection.commit(); cmDB.updateDomains(null, null); } 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) { } } } }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private void readFromFile1() throws DException { URL url1 = null; if (url == null) { url = getClass().getResource("/com/daffodilwoods/daffodildb/utils/parser/parser.schema"); try { url = new URL(url.getProtocol() + ":" + url.getPath().substring(0, url.getPath().indexOf("/parser.schema"))); } catch (MalformedURLException ex2) { ex2.printStackTrace(); throw new DException("DSE0", new Object[] { ex2 }); } try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } if (url1 == null) { throw new DException("DSE0", new Object[] { "Parser.schema file is missing in classpath." }); } } else { try { url1 = new URL(url.getProtocol() + ":" + url.getPath() + "/parser.schema"); } catch (MalformedURLException ex) { throw new DException("DSE0", new Object[] { ex }); } } ArrayList arr1 = null; StringBuffer rule = null; try { LineNumberReader raf = new LineNumberReader(new BufferedReader(new InputStreamReader(url1.openStream()))); arr1 = new ArrayList(); rule = new StringBuffer(""); while (true) { String str1 = raf.readLine(); if (str1 == null) { break; } String str = str1.trim(); if (str.length() == 0) { if (rule.length() > 0) { arr1.add(rule.toString()); } rule = new StringBuffer(""); } else { rule.append(" ").append(str); } } raf.close(); } catch (IOException ex1) { ex1.printStackTrace(); throw new DException("DSE0", new Object[] { ex1 }); } if (rule.length() > 0) arr1.add(rule.toString()); for (int i = 0; i < arr1.size(); i++) { String str = (String) arr1.get(i); int index = str.indexOf("::="); if (index == -1) { P.pln("Error " + str); throw new DException("DSE0", new Object[] { "Rule is missing from parser.schema" }); } String key = str.substring(0, index).trim(); String value = str.substring(index + 3).trim(); Object o = fileEntries.put(key, value); if (o != null) { new Exception("Duplicate Defination for Rule [" + key + "] Value [" + value + "] Is Replaced By [" + o + "]").printStackTrace(); } } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.