label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public RobotList<Location> sort_incr_Location(RobotList<Location> list, String field) { int length = list.size(); Index_value[] enemy_dist = new Index_value[length]; Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { enemy_dist[i] = new Index_value(i, distance(cur_loc, list.get(i))); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (enemy_dist[i].value > enemy_dist[i + 1].value) { Index_value a = enemy_dist[i]; enemy_dist[i] = enemy_dist[i + 1]; enemy_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Location> new_location_list = new RobotList<Location>(Location.class); for (int i = 0; i < length; i++) { new_location_list.addLast(list.get(enemy_dist[i].index)); } return new_location_list; } Code Sample 2: private String searchMetabolite(String name) { { BufferedReader in = null; try { String urlName = name; URL url = new URL(urlName); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; Boolean isMetabolite = false; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("Metabolite</h1>")) { isMetabolite = true; } if (inputLine.contains("<td><a href=\"/Metabolites/") && isMetabolite) { String metName = inputLine.substring(inputLine.indexOf("/Metabolites/") + 13, inputLine.indexOf("aspx\" target") + 4); return "http://gmd.mpimp-golm.mpg.de/Metabolites/" + metName; } } in.close(); return name; } catch (IOException ex) { Logger.getLogger(GetGolmIDsTask.class.getName()).log(Level.SEVERE, null, ex); return null; } } }
00
Code Sample 1: public boolean receiveFile(FileDescriptor fileDescriptor) { try { byte[] block = new byte[1024]; int sizeRead = 0; int totalRead = 0; File dir = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dir.exists()) { dir.mkdirs(); } File file = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); if (!file.exists()) { file.createNewFile(); } SSLSocket sslsocket = getFileTransferConectionConnectMode(ServerAdress.getServerAdress()); OutputStream fileOut = new FileOutputStream(file); InputStream dataIn = sslsocket.getInputStream(); while ((sizeRead = dataIn.read(block)) >= 0) { totalRead += sizeRead; fileOut.write(block, 0, sizeRead); propertyChangeSupport.firePropertyChange("fileByte", 0, totalRead); } fileOut.close(); dataIn.close(); sslsocket.close(); if (fileDescriptor.getName().contains(".snapshot")) { try { File fileData = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation() + fileDescriptor.getName()); File dirData = new File(Constants.PREVAYLER_DATA_DIRETORY + Constants.FILE_SEPARATOR); File destino = new File(dirData, fileData.getName()); boolean success = fileData.renameTo(destino); if (!success) { deleteDir(Constants.DOWNLOAD_DIR); return false; } deleteDir(Constants.DOWNLOAD_DIR); } catch (Exception e) { e.printStackTrace(); } } else { if (Server.isServerOpen()) { FileChannel inFileChannel = new FileInputStream(file).getChannel(); File dirServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getLocation()); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.DOWNLOAD_DIR + fileDescriptor.getName()); if (!fileServer.exists()) { fileServer.createNewFile(); } inFileChannel.transferTo(0, inFileChannel.size(), new FileOutputStream(fileServer).getChannel()); inFileChannel.close(); } } if (totalRead == fileDescriptor.getSize()) { return true; } } catch (Exception e) { logger.error("Receive File:", e); } return false; } Code Sample 2: public static String getHashedStringMD5(String value) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(value.getBytes()); byte[] buf = d.digest(); return new String(buf); }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); }
00
Code Sample 1: private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } } Code Sample 2: public static Builder fromURL(URL url) { try { InputStream in = null; try { in = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read = -1; byte[] buf = new byte[4096]; while ((read = in.read(buf)) >= 0) { if (read > 0) { baos.write(buf, 0, read); } } StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray()); try { b.setSystemId(url.toURI().toString()); } catch (URISyntaxException use) { b.setSystemId(url.toString()); } return b; } finally { if (in != null) { in.close(); } } } catch (IOException ex) { throw new XMLUnitException(ex); } }
11
Code Sample 1: public RegionInfo(String name, int databaseID, int units, float xMin, float xMax, float yMin, float yMax, float zMin, float zMax, String imageURL) { this.name = name; this.databaseID = databaseID; this.units = units; this.xMin = xMin; this.xMax = xMax; this.yMin = yMin; this.yMax = yMax; this.zMin = zMin; this.zMax = zMax; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(this.name.getBytes()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); daos.writeInt(this.databaseID); daos.writeInt(this.units); daos.writeDouble(this.xMin); daos.writeDouble(this.xMax); daos.writeDouble(this.yMin); daos.writeDouble(this.yMax); daos.writeDouble(this.zMin); daos.writeDouble(this.zMax); daos.flush(); byte[] hashValue = digest.digest(baos.toByteArray()); int hashCode = 0; for (int i = 0; i < hashValue.length; i++) { hashCode += (int) hashValue[i] << (i % 4); } this.hashcode = hashCode; } catch (Exception e) { throw new IllegalArgumentException("Error occurred while generating hashcode for region " + this.name); } if (imageURL != null) { URL url = null; try { url = new URL(imageURL); } catch (MalformedURLException murle) { } if (url != null) { BufferedImage tmpImage = null; try { tmpImage = ImageIO.read(url); } catch (Exception e) { e.printStackTrace(); } mapImage = tmpImage; } else this.mapImage = null; } else this.mapImage = null; } Code Sample 2: @Override public String encryptString(String passphrase, String message) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bIn = cipher.doFinal(message.getBytes("UTF-8")); String base64Encoded = base64encode(bIn); return base64Encoded; }
00
Code Sample 1: private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); } Code Sample 2: protected Properties load(URL url) { try { InputStream i = url.openStream(); Properties p = new Properties(); p.load(i); i.close(); return p; } catch (IOException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static void main(String[] args) { String logConfiguration = args[2]; DOMConfigurator.configure(logConfiguration); String urlToRun = args[0]; String outputFile = args[1]; InputStream conInput = null; BufferedReader reader = null; BufferedWriter writer = null; if (logger.isDebugEnabled()) { logger.debug("output file is " + outputFile); } try { URL url = new URL(urlToRun); URLConnection urlCon = url.openConnection(); urlCon.connect(); conInput = urlCon.getInputStream(); reader = new BufferedReader(new InputStreamReader(conInput)); File output = new File(outputFile); writer = new BufferedWriter(new FileWriter(output)); String line = null; while ((line = reader.readLine()) != null) { logger.debug(line); writer.write(line); } writer.flush(); } catch (MalformedURLException murle) { logger.error(urlToRun + " is not a valid URL", murle); } catch (IOException ioe) { logger.error("IO Error ocured while opening connection to " + urlToRun, ioe); } finally { try { reader.close(); conInput.close(); writer.close(); } catch (IOException ioe) { throw new RuntimeException("Cannot close readers or streams", ioe); } } } Code Sample 2: public void initGet() throws Exception { cl = new DefaultHttpClient(); GetAuthPromter hp = new GetAuthPromter(); cl.setCredentialsProvider(hp); get = new HttpGet(getURL()); get.setHeader("User-Agent", "test"); get.setHeader("Accept", "*/*"); get.setHeader("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); HttpResponse resp = cl.execute(get); ent = resp.getEntity(); setInputStream(ent.getContent()); }
11
Code Sample 1: public static void copyFile(File srcFile, File destFolder) { try { File destFile = new File(destFolder, srcFile.getName()); if (destFile.exists()) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + " as " + destFile + " already exists"); } FileChannel srcChannel = null; FileChannel destChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); destChannel = new FileOutputStream(destFile).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (destChannel != null) { destChannel.close(); } } destFile.setLastModified((srcFile.lastModified())); } catch (IOException e) { throw new BuildException("Could not copy " + srcFile + " to " + destFolder + ": " + e, e); } } Code Sample 2: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: void loadListFile(String listFileName, String majorType, String minorType, String languages, String annotationType) throws MalformedURLException, IOException { Lookup defaultLookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); URL lurl = new URL(listsURL, listFileName); BufferedReader listReader = new BomStrippingInputStreamReader(lurl.openStream(), encoding); String line; int lines = 0; while (null != (line = listReader.readLine())) { GazetteerNode node = new GazetteerNode(line, unescapedSeparator, false); Lookup lookup = defaultLookup; Map<String, String> fm = node.getFeatureMap(); if (fm != null && fm.size() > 0) { lookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); Set<String> keyset = fm.keySet(); if (keyset.size() <= 4) { Map<String, String> newfm = null; for (String key : keyset) { if (key.equals("majorType")) { String tmp = fm.get("majorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.majorType = tmp; } else if (key.equals("minorType")) { String tmp = fm.get("minorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.minorType = tmp; } else if (key.equals("languages")) { String tmp = fm.get("languages"); if (canonicalizeStrings) { tmp.intern(); } lookup.languages = tmp; } else if (key.equals("annotationType")) { String tmp = fm.get("annotationType"); if (canonicalizeStrings) { tmp.intern(); } lookup.annotationType = tmp; } else { if (newfm == null) { newfm = new HashMap<String, String>(); } String tmp = fm.get(key); if (canonicalizeStrings) { tmp.intern(); } newfm.put(key, tmp); } } if (newfm != null) { lookup.features = newfm; } } else { if (canonicalizeStrings) { for (String key : fm.keySet()) { String tmp = fm.get(key); tmp.intern(); fm.put(key, tmp); } } lookup.features = fm; } } addLookup(node.getEntry(), lookup); lines++; } logger.debug("Lines read: " + lines); } Code Sample 2: public static boolean copy(File src, File dest) { boolean result = true; String files[] = null; if (src.isDirectory()) { files = src.list(); result = dest.mkdir(); } else { files = new String[1]; files[0] = ""; } if (files == null) { files = new String[0]; } for (int i = 0; (i < files.length) && result; i++) { File fileSrc = new File(src, files[i]); File fileDest = new File(dest, files[i]); if (fileSrc.isDirectory()) { result = copy(fileSrc, fileDest); } else { FileChannel ic = null; FileChannel oc = null; try { ic = (new FileInputStream(fileSrc)).getChannel(); oc = (new FileOutputStream(fileDest)).getChannel(); ic.transferTo(0, ic.size(), oc); } catch (IOException e) { log.error(sm.getString("expandWar.copy", fileSrc, fileDest), e); result = false; } finally { if (ic != null) { try { ic.close(); } catch (IOException e) { } } if (oc != null) { try { oc.close(); } catch (IOException e) { } } } } } return result; }
11
Code Sample 1: public static void copyFile(File fileIn, File fileOut) throws IOException { FileChannel chIn = new FileInputStream(fileIn).getChannel(); FileChannel chOut = new FileOutputStream(fileOut).getChannel(); try { chIn.transferTo(0, chIn.size(), chOut); } catch (IOException e) { throw e; } finally { if (chIn != null) chIn.close(); if (chOut != null) chOut.close(); } } Code Sample 2: public static long copyFile(File source, File target) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(target); FileChannel in = fileInputStream.getChannel(); FileChannel out = fileOutputStream.getChannel(); return out.transferFrom(in, 0, source.length()); } finally { if (fileInputStream != null) fileInputStream.close(); if (fileOutputStream != null) fileOutputStream.close(); } }
00
Code Sample 1: 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(); } } Code Sample 2: public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); }
11
Code Sample 1: public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; } Code Sample 2: public String buscaCDE() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDE")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDE: " + miLinea); return miLinea; }
00
Code Sample 1: protected static DynamicJasperDesign generateJasperDesign(DynamicReport dr) throws CoreException { DynamicJasperDesign jd = null; try { if (dr.getTemplateFileName() != null) { log.info("loading template file: " + dr.getTemplateFileName()); log.info("Attemping to find the file directly in the file system..."); File file = new File(dr.getTemplateFileName()); if (file.exists()) { JasperDesign jdesign = JRXmlLoader.load(file); jd = DJJRDesignHelper.downCast(jdesign, dr); } else { log.info("Not found: Attemping to find the file in the classpath..."); URL url = DynamicJasperHelper.class.getClassLoader().getResource(dr.getTemplateFileName()); JasperDesign jdesign = JRXmlLoader.load(url.openStream()); jd = DJJRDesignHelper.downCast(jdesign, dr); } JasperDesignHelper.populateReportOptionsFromDesign(jd, dr); } else { jd = DJJRDesignHelper.getNewDesign(dr); } registerParameters(jd, dr); } catch (JRException e) { throw new CoreException(e.getMessage(), e); } catch (IOException e) { throw new CoreException(e.getMessage(), e); } return jd; } Code Sample 2: public static String createMD5(String str) { String sig = null; String strSalt = str + StaticBox.getsSalt(); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(strSalt.getBytes(), 0, strSalt.length()); byte byteData[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } sig = sb.toString(); } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return sig; }
00
Code Sample 1: @Override public JSONObject runCommand(JSONObject payload, HttpSession session) throws DefinedException { String sessionId = session.getId(); log.debug("Login -> runCommand SID: " + sessionId); JSONObject toReturn = new JSONObject(); boolean isOK = true; String username = null; try { username = payload.getString(ComConstants.LogIn.Request.USERNAME); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing username parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } String password = null; if (isOK) { try { password = payload.getString(ComConstants.LogIn.Request.PASSWORD); } catch (JSONException e) { log.error("SessionId=" + sessionId + ", Missing password parameter", e); throw new DefinedException(StatusCodesV2.PARAMETER_ERROR); } } if (isOK) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("SessionId=" + sessionId + ", MD5 algorithm does not exist", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } m.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, m.digest()).toString(16); UserSession userSession = pli.login(username, password); try { if (userSession != null) { session.setAttribute("user", userSession); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_OK.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_OK.getStatusMessage()); } else { log.error("SessionId=" + sessionId + ", Login failed: username=" + username + " not found"); toReturn.put(ComConstants.Response.STATUS_CODE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusCode()); toReturn.put(ComConstants.Response.STATUS_MESSAGE, StatusCodesV2.LOGIN_USER_OR_PASSWORD_INCORRECT.getStatusMessage()); } } catch (JSONException e) { log.error("SessionId=" + sessionId + ", JSON exception occured in response", e); e.printStackTrace(); throw new DefinedException(StatusCodesV2.INTERNAL_SYSTEM_FAILURE); } } log.debug("Login <- runCommand SID: " + sessionId); return toReturn; } Code Sample 2: 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; }
00
Code Sample 1: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } if (status < 200 || status >= 400) return false; String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password; return true; } Code Sample 2: private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
11
Code Sample 1: public static String digestMd5(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("文字列がNull、または空です。"); } MessageDigest md5; byte[] enclyptedHash; try { md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes()); enclyptedHash = md5.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return ""; } return bytesToHexString(enclyptedHash); } Code Sample 2: public boolean validatePassword(UserType nameMatch, String password) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(nameMatch.getSalt().getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); return encodedString.equals(nameMatch.getPassword()); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); logger.fatal("Shutting down..."); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); assert false : "This should never happen"; return false; } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(ex.getMessage()); logger.fatal(errorMessage); GlobalUITools.displayFatalExceptionMessage(null, "Could not use algorithm " + HASH_ALGORITHM, ex, true); assert false : "This could should never be reached"; return false; } }
00
Code Sample 1: public LOCKSSDaemonStatusTableTO getDataFromDaemonStatusTableByHttps() throws HttpResponseException { LOCKSSDaemonStatusTableXmlStreamParser ldstxp = null; LOCKSSDaemonStatusTableTO ldstTO = null; HttpEntity entity = null; HttpGet httpget = null; xstream.setMode(XStream.NO_REFERENCES); xstream.alias("HttpClientDAO", HttpClientDAO.class); try { httpget = new HttpGet(dataUrl); logger.log(Level.INFO, "executing request {0}", httpget.getURI()); HttpResponse resp = httpClient.execute(httpget); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "response to the request is not OK: skip this IP: status code={0}", statusCode); httpget.abort(); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); return ldstTO; } entity = resp.getEntity(); InputStream is = entity.getContent(); ldstxp = new LOCKSSDaemonStatusTableXmlStreamParser(); ldstxp.read(new BufferedInputStream(is)); ldstTO = ldstxp.getLOCKSSDaemonStatusTableTO(); ldstTO.setIpAddress(this.ip); logger.log(Level.INFO, "After parsing [{0}] table", this.tableId); logger.log(Level.FINEST, "After parsing {0}: contents of ldstTO:\n{1}", new Object[] { this.tableId, ldstTO }); if (ldstTO.hasIncompleteRows) { logger.log(Level.WARNING, "!!!!!!!!! incomplete rows are found for {0}", tableId); if (ldstTO.getTableData() != null && ldstTO.getTableData().size() > 0) { logger.log(Level.FINE, "incomplete rows: table(map) data dump =[\n{0}\n]", xstream.toXML(ldstTO.getTableData())); } } else { logger.log(Level.INFO, "All rows are complete for {0}", tableId); } } catch (ConnectTimeoutException ce) { logger.log(Level.WARNING, "ConnectTimeoutException occurred", ce); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (SocketTimeoutException se) { logger.log(Level.WARNING, "SocketTimeoutException occurred", se); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (ClientProtocolException pe) { logger.log(Level.SEVERE, "The protocol was not http; https is suspected", pe); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); ldstTO.setHttpProtocol(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (IOException ex) { logger.log(Level.SEVERE, "IO exception occurs", ex); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException ex) { logger.log(Level.SEVERE, "io exception when entity was to be" + "consumed", ex); } } } return ldstTO; } Code Sample 2: private HttpURLConnection getConnection(String url, int connTimeout, int readTimeout) throws IOException { HttpURLConnection con = null; con = (HttpURLConnection) new URL(url).openConnection(); if (connTimeout > 0) { if (!isJDK14orEarlier) { con.setConnectTimeout(connTimeout * 1000); } else { System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connTimeout * 1000)); } } if (readTimeout > 0) { if (!isJDK14orEarlier) { con.setReadTimeout(readTimeout * 1000); } else { System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(readTimeout * 1000)); } } con.setInstanceFollowRedirects(false); return con; }
00
Code Sample 1: public static void loginSkyDrive() throws Exception { System.out.println("login "); u = new URL(loginurl); uc = (HttpURLConnection) u.openConnection(); uc.setRequestProperty("Cookie", msprcookie + ";" + mspokcookie); uc.setDoOutput(true); uc.setRequestMethod("POST"); uc.setInstanceFollowRedirects(false); pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true); pw.print("login=dinesh007007%40hotmail.com&passwd=&SI=Sign+in&type=11&LoginOptions=3&NewUser=1&MEST=&PPSX=Passpor&PPFT=" + ppft + "&PwdPad=&sso=&i1=&i2=1&i3=10524&i4=&i12=1&i13=&i14=437&i15=624&i16=3438"); pw.flush(); pw.close(); System.out.println(uc.getResponseCode()); Map<String, List<String>> headerFields = uc.getHeaderFields(); if (headerFields.containsKey("Set-Cookie")) { List<String> header = headerFields.get("Set-Cookie"); for (int i = 0; i < header.size(); i++) { tmp = header.get(i); System.out.println(tmp); } } location = uc.getHeaderField("Location"); System.out.println("Location : " + location); System.out.println("going to open paaport page"); DefaultHttpClient d = new DefaultHttpClient(); HttpGet hg = new HttpGet("https://skydrive.live.com"); hg.setHeader("Cookie", msprcookie + ";" + mspokcookie); HttpResponse execute = d.execute(hg); HttpEntity entity = execute.getEntity(); System.out.println(EntityUtils.toString(entity)); System.out.println(execute.getStatusLine()); Header[] allHeaders = execute.getAllHeaders(); for (int i = 0; i < allHeaders.length; i++) { System.out.println(allHeaders[i].getName() + " : " + allHeaders[i].getValue()); } } Code Sample 2: public RecordIterator get(URL url) { RecordIterator recordIter = null; if (!SUPPORTED_PROTOCOLS.contains(url.getProtocol().toLowerCase())) { return null; } try { URL robotsUrl = new URL(url, ROBOTS_TXT); recordIter = new RecordIterator(urlInputStreamFactory.openStream(robotsUrl)); } catch (IOException e) { LOG.info("Failed to fetch " + url, e); } return recordIter; }
11
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: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
11
Code Sample 1: public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public static boolean copyFile(String src, String dst) { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(new File(src)).getChannel(); outChannel = new FileOutputStream(new File(dst)).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (FileNotFoundException e) { e.printStackTrace(); MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst); return false; } catch (IOException e) { MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst); return false; } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } catch (IOException e) { MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst); return false; } } return true; }
11
Code Sample 1: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); } Code Sample 2: @Override public String getMD5(String host) { String res = ""; Double randNumber = Math.random() + System.currentTimeMillis(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(randNumber.toString().getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void writeToFtp(String login, String password, String address, String directory, String filename) { String newline = System.getProperty("line.separator"); try { URL url = new URL("ftp://" + login + ":" + password + "@ftp." + address + directory + filename + ".html" + ";type=i"); URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); OutputStreamWriter stream = new OutputStreamWriter(urlConn.getOutputStream()); stream.write("<html><title>" + title + "</title>" + newline); stream.write("<h1><b>" + title + "</b></h1>" + newline); stream.write("<h2>Table Of Contents:</h2><ul>" + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<li><i><a href=\"#"); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k)); stream.write("</a></i></li>" + newline); } stream.write("</ul><hr>" + newline + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<h3><b>"); stream.write("<a name=\""); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k) + "</a>"); stream.write("</b></h3>" + newline); stream.write(readNoteBody(k) + newline); } stream.write(newline + "<br><hr><a>This was created using Scribe, a free crutch editor.</a></html>"); stream.close(); } catch (IOException error) { System.out.println("There was an error: " + error); } }
11
Code Sample 1: @Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.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: private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); }
11
Code Sample 1: public static byte[] SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return sha1hash; } Code Sample 2: private void LoadLoginInfo() { m_PwdList.removeAllElements(); String szTemp = null; int iIndex = 0; int iSize = m_UsrList.size(); for (int i = 0; i < iSize; i++) m_PwdList.add(""); try { if ((m_UsrList.size() > 0) && m_bSavePwd) { char[] MD5PWD = new char[80]; java.util.Arrays.fill(MD5PWD, (char) 0); java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + "user.dat"; java.io.File file = new java.io.File(szPath); if (file.exists()) { java.io.FileInputStream br = new java.io.FileInputStream(file); byte[] szEncryptPwd = null; int iLine = 0; while (br.available() > 0) { md.reset(); md.update(((String) m_UsrList.get(iLine)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i2 = 0; i2 < DESUSR.length; i2++) alpha += DESUSR[i2]; iSize = br.read(); if (iSize > 0) { szEncryptPwd = new byte[iSize]; br.read(szEncryptPwd); char[] cPwd = new char[iSize]; for (int i = 0; i < iSize; i++) { int iChar = (int) szEncryptPwd[i] - (int) alpha; if (iChar < 0) iChar += 256; cPwd[i] = (char) iChar; } m_PwdList.setElementAt(new String(cPwd), iLine); } iLine++; } } } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } }
00
Code Sample 1: public static OutputStream getOutputStream(String path) throws ResourceException { URL url = getURL(path); if (url != null) { try { return url.openConnection().getOutputStream(); } catch (IOException e) { throw new ResourceException(e); } } else { throw new ResourceException("Error obtaining resource, invalid path: " + path); } } Code Sample 2: public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
11
Code Sample 1: @Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } } Code Sample 2: public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
00
Code Sample 1: private EventSeries<PhotoEvent> loadIncomingEvents(long reportID) { EventSeries<PhotoEvent> events = new EventSeries<PhotoEvent>(); try { URL url = new URL(SERVER_URL + XML_PATH + "reports.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = reader.readLine()) != null) { String[] values = str.split(","); if (values.length == 2) { long id = Long.parseLong(values[0]); if (id == reportID) { long time = Long.parseLong(values[1]); events.addEvent(new PhotoEvent(time)); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return events; } Code Sample 2: private String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static void readFile(FOUserAgent ua, String uri, OutputStream output) throws IOException { InputStream in = getURLInputStream(ua, uri); try { IOUtils.copy(in, output); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void execute(HttpResponse response) throws HttpException, IOException { StringBuffer content = new StringBuffer(); NodeSet allNodes = membershipRegistry.listAllMembers(); for (Node node : allNodes) { content.append(node.getId().toString()); content.append(SystemUtils.LINE_SEPARATOR); } StringEntity body = new StringEntity(content.toString()); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); } Code Sample 2: public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; }
00
Code Sample 1: public static void main(String[] args) { URL url = null; EventHeap eh = new EventHeap("iw-room2"); Event newEvent; float chan1 = -1, chan2 = -1; try { url = new URL("http://iw--bluetooth-ap/cgi-bin/sens.cgi"); } catch (MalformedURLException e) { } byte buf[] = new byte[1000]; while (true) { try { InputStream in = url.openStream(); int length = in.read(buf); String page = new String(buf); String data = page.substring(290); if (data.startsWith("No Sensors Found")) { Thread.sleep(1000); } else { String sensorID = data.substring(15, 32); String channel1 = data.substring(163, 167); String channel2 = data.substring(266, 270); if (Float.parseFloat(channel1) != chan1) { System.out.println(sensorID); System.out.println("Channel 1:" + channel1); newEvent = new Event("iStuffInputEvent"); newEvent.addField("Device", "Slider"); newEvent.addField("ID", sensorID + ":channel1"); newEvent.addField("Value", channel1); newEvent.addField("Max", String.valueOf(5)); newEvent.addField("Min", String.valueOf(0)); eh.putEvent(newEvent); chan1 = Float.parseFloat(channel1); } } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: 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; }
00
Code Sample 1: public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; } Code Sample 2: public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
00
Code Sample 1: public static NotaFiscal insert(NotaFiscal objNF) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; if (c == null) { return null; } if (objNF == null) { return null; } try { c.setAutoCommit(false); String sql = ""; int idNotaFiscal; idNotaFiscal = NotaFiscalDAO.getLastCodigo(); if (idNotaFiscal < 1) { return null; } sql = "INSERT INTO nota_fiscal " + "(id_nota_fiscal, id_fornecedor, total, data_emissao, data_cadastro, numero) " + "VALUES(?, ?, TRUNCATE(?,2), STR_TO_DATE(?,'%d/%m/%Y'), now(), ?) "; pst = c.prepareStatement(sql); pst.setInt(1, idNotaFiscal); pst.setLong(2, objNF.getFornecedor().getCodigo()); pst.setString(3, new DecimalFormat("#0.00").format(objNF.getValor())); pst.setString(4, objNF.getDataEmissaoFormatada()); pst.setString(5, objNF.getNumero()); result = pst.executeUpdate(); pst = null; if (result > 0) { Iterator<ItemNotaFiscal> itINF = (objNF.getItemNotaFiscal()).iterator(); while ((itINF != null) && (itINF.hasNext())) { ItemNotaFiscal objINF = (ItemNotaFiscal) itINF.next(); sql = ""; sql = "INSERT INTO item_nota_fiscal " + "(id_nota_fiscal, id_produto, quantidade, subtotal) " + "VALUES(?, ?, ?, TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setInt(1, idNotaFiscal); pst.setInt(2, objINF.getProduto().getCodigo()); pst.setInt(3, objINF.getQuantidade()); pst.setString(4, new DecimalFormat("#0.00").format(objINF.getSubtotal())); result = pst.executeUpdate(); } } c.commit(); objNF.setCodigo(idNotaFiscal); } catch (final Exception e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[NotaFiscalDAO.insert.rollback] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[NotaFiscalDAO.insert] Erro ao inserir -> " + e.getMessage()); objNF = null; } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } return objNF; } Code Sample 2: protected static void download(FtpSiteConnector connector, File localFile, String remotePath, final IProgressMonitor monitor) throws FtpException { if (!localFile.exists()) { FTPClient ftp = new FTPClient(); try { FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); 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) { log.info("downloading file: " + remotePath); ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); final long fileSize = getFileSize(ftp, remotePath); FileOutputStream dfile = new FileOutputStream(localFile); ftp.retrieveFile(remotePath, dfile, new CopyStreamListener() { public int worked = 0; public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { int percent = percent(fileSize, totalBytesTransferred); int delta = percent - worked; if (delta > 0) { if (monitor != null) { monitor.worked(delta); } worked = percent; } } public void bytesTransferred(CopyStreamEvent event) { } private int percent(long totalBytes, long totalBytesTransferred) { long percent = (totalBytesTransferred * 100) / totalBytes; return Long.valueOf(percent).intValue(); } }); dfile.flush(); dfile.close(); ftp.logout(); } else { throw new FtpException("Invalid login"); } ftp.disconnect(); } catch (SocketException e) { log.error("File download failed with message: " + e.getMessage()); throw new FtpException("File download failed with message: " + e.getMessage()); } catch (IOException e) { log.error("File download failed with message: " + e.getMessage()); throw new FtpException("File download failed with message: " + e.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { throw new FtpException("File download failed with message: " + ioe.getMessage()); } } } } }
00
Code Sample 1: void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: private static String appletLoad(String file, Output OUT) { if (!urlpath.endsWith("/")) { urlpath += '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = ""; if (file.equals("languages.txt")) { url = urlpath + file; } else { url = urlpath + "users/" + file; } try { StringBuffer sb = new StringBuffer(2000); BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String a; while ((a = br.readLine()) != null) { sb.append(a).append('\n'); } return sb.toString(); } catch (Exception e) { OUT.println("load failed for file->" + file); } return ""; }
11
Code Sample 1: public static int gzipFile(File file_input, String file_output) { File gzip_output = new File(file_output); GZIPOutputStream gzip_out_stream; try { FileOutputStream out = new FileOutputStream(gzip_output); gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_GZIP_FAIL; } try { gzip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: @SuppressWarnings("unchecked") public static <T extends Class> Collection<T> listServices(T serviceType, ClassLoader classLoader) throws IOException, ClassNotFoundException { final Collection<T> result = new LinkedHashSet<T>(); final Enumeration<URL> resouces = classLoader.getResources("META-INF/services/" + serviceType.getName()); while (resouces.hasMoreElements()) { final URL url = resouces.nextElement(); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = reader.readLine(); while (line != null) { if (line.startsWith("#")) { } else if ("".equals(line.trim())) { } else { final T implClass = (T) Class.forName(line, true, classLoader); if (!serviceType.isAssignableFrom(implClass)) { throw new IllegalStateException(String.format("%s: class %s does not implement required interfafce %s", url, implClass, serviceType)); } result.add(implClass); } line = reader.readLine(); } } finally { reader.close(); } } return result; } Code Sample 2: @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(); } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } } Code Sample 2: public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public static void readProperties() throws IOException { URL url1 = cl.getResource("conf/soapuddi.config"); Properties props = new Properties(); if (url1 == null) throw new IOException("soapuddi.config not found"); props.load(url1.openStream()); className = props.getProperty("Class"); url = props.getProperty("URL"); user = props.getProperty("user"); password = props.getProperty("passwd"); operatorName = props.getProperty("operator"); authorisedName = props.getProperty("authorisedName"); isUpdated = true; } Code Sample 2: private int addPollToDB(DataSource database) { int pollid = -2; Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); String add = "insert into polls" + " values( ?, ?, ?, ?)"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getAdmin()); prepStatement.setString(2, selectedCourse.getCourseId()); prepStatement.setString(3, getTitle()); prepStatement.setInt(4, 0); prepStatement.executeUpdate(); String findNewID = "select max(pollid) from polls"; prepStatement = con.prepareStatement(findNewID); ResultSet newID = prepStatement.executeQuery(); pollid = -2; while (newID.next()) { pollid = newID.getInt(1); } if (pollid == -2) { this.sqlError = true; throw new Exception(); } String[] options = getAllOptions(); for (int i = 0; i < 4; i++) { String insertOption = "insert into polloptions values ( ?, ?, ? )"; prepStatement = con.prepareStatement(insertOption); prepStatement.setString(1, options[i]); prepStatement.setInt(2, 0); prepStatement.setInt(3, pollid); prepStatement.executeUpdate(); } prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } return pollid; }
00
Code Sample 1: private Response doLoad(URL url, URL referer, String postData) throws IOException { URLConnection connection = PROXY == null ? url.openConnection() : url.openConnection(PROXY); COOKIES.writeCookies(connection); connection.setRequestProperty("User-Agent", USER_AGENT); if (referer != null) { connection.setRequestProperty("Referer", referer.toString()); } if (postData != null) { connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("CONTENT_LENGTH", "" + postData.length()); OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(postData); osw.flush(); osw.close(); } connection.connect(); COOKIES.readCookies(connection); previouseUrl = url; return responceInstance(url, connection.getInputStream(), connection.getContentType()); } Code Sample 2: @Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); String dir = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { File dir_f = new File(dir); if (!dir_f.exists()) { debug("(0) - make dir: " + dir_f + " - "); org.apache.commons.io.FileUtils.forceMkdir(dir_f); } } catch (IOException ex) { fatal("IOException", ex); } debug("Files:" + this.properties.get("url")); String[] url_to_download = properties.get("url").split(";"); for (String u : url_to_download) { if (StringUtil.isNullOrEmpty(u)) { continue; } u = StringUtil.trim(u); debug("(0) url: " + u); String f_name = u.substring(u.lastIndexOf("/"), u.length()); debug("(1) - start download: " + u + " to file name: " + new File(dir + "/" + f_name).toString()); com.utils.HttpUtil.downloadData(u, new File(dir + "/" + f_name).toString()); } try { conn_stats.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } String[] query_delete = properties.get("query_delete").split(";"); for (String q : query_delete) { if (StringUtil.isNullOrEmpty(q)) { continue; } q = StringUtil.trim(q); debug("(2) - " + q); try { Statement stat = conn_stats.createStatement(); stat.executeUpdate(q); stat.close(); } catch (SQLException e) { try { conn_stats.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } fatal("SQLException", e); } } for (String u : url_to_download) { if (StringUtil.isNullOrEmpty(u)) { continue; } u = StringUtil.trim(u); try { Statement stat = conn_stats.createStatement(); String f_name = new File(dir + "/" + u.substring(u.lastIndexOf("/"), u.length())).toString(); debug("(3) - start import: " + f_name); BigFile lines = new BigFile(f_name); int n = 0; for (String l : lines) { String fields[] = l.split(","); String query = ""; if (f_name.indexOf("hip_countries.csv") != -1) { query = "insert into hip_countries values (" + fields[0] + ",'" + normalize(fields[1]) + "','" + normalize(fields[2]) + "')"; } else if (f_name.indexOf("hip_ip4_city_lat_lng.csv") != -1) { query = "insert into hip_ip4_city_lat_lng values (" + fields[0] + ",'" + normalize(fields[1]) + "'," + fields[2] + "," + fields[3] + ")"; } else if (f_name.indexOf("hip_ip4_country.csv") != -1) { query = "insert into hip_ip4_country values (" + fields[0] + "," + fields[1] + ")"; } debug(n + " - " + query); stat.executeUpdate(query); n++; } debug("(4) tot import per il file" + f_name + " : " + n); stat.close(); new File(f_name).delete(); } catch (SQLException ex) { fatal("SQLException", ex); try { conn_stats.rollback(); } catch (SQLException ex2) { fatal("SQLException", ex2); } } catch (IOException ex) { fatal("IOException", ex); } catch (Exception ex3) { fatal("Exception", ex3); } } try { conn_stats.commit(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_stats.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { debug("(6) Vacuum"); Statement stat = this.conn_stats.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } debug("End execute job " + this.getClass().getName()); }
00
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } Code Sample 2: public List<Template> getTemplates(boolean fromPrivate) { String shared = fromPrivate ? "private" : "public"; List<Template> templates = new ArrayList<Template>(); String restURL = configuration.getBeehiveRESTRootUrl() + "account/" + userService.getAccount().getOid() + "/templates/" + shared; HttpGet httpGet = new HttpGet(restURL); httpGet.setHeader("Accept", "application/json"); this.addAuthentication(httpGet); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) { throw new NotAuthenticatedException("User " + userService.getCurrentUser().getUsername() + " not authenticated! "); } throw new BeehiveNotAvailableException("Beehive is not available right now! "); } InputStreamReader reader = new InputStreamReader(response.getEntity().getContent()); BufferedReader buffReader = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = buffReader.readLine()) != null) { sb.append(line); sb.append("\n"); } String result = sb.toString(); TemplateList templateList = buildTemplateListFromJson(result); List<TemplateDTO> dtoes = templateList.getTemplates(); for (TemplateDTO dto : dtoes) { templates.add(dto.toTemplate()); } } catch (IOException e) { throw new BeehiveNotAvailableException("Failed to get template list, The beehive is not available right now ", e); } return templates; }
00
Code Sample 1: public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", "some realm"); digestAuth.overrideParamter("nonce", "whatever"); localcontext.setAttribute("preemptive-auth", digestAuth); httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); httpclient.addResponseInterceptor(new PersistentDigest()); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent(); } } } Code Sample 2: public void render(ParagraphElement cnt, double x, double y, Graphics2D g, LayoutingContext layoutingContext, FlowContext flowContext) { InlineImageContent ic = (InlineImageContent) cnt; try { URLConnection urlConn = ic.getUrl().openConnection(); urlConn.setConnectTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { System.out.println("loading image " + ic.getUrl()); ImageReader reader = readers.next(); reader.setInput(iis, true); if (flowContext.pdfContext == null) { RenderedImage img = reader.readAsRenderedImage(0, null); renderOnGraphics(img, x, y, ic, g, layoutingContext, flowContext); } else { BufferedImage img = reader.read(0); renderDirectPdf(img, x, y, ic, g, layoutingContext, flowContext); } reader.dispose(); } else System.err.println("cannot render image " + ic.getUrl() + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot render image " + ic.getUrl() + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } }
11
Code Sample 1: public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); } Code Sample 2: public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } }
00
Code Sample 1: protected int executeUpdates(List<UpdateStatement> statements, OlVersionCheck olVersionCheck) throws DaoException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("start executeUpdates"); } PreparedStatement stmt = null; Connection conn = null; int rowsAffected = 0; try { conn = ds.getConnection(); conn.setAutoCommit(false); conn.rollback(); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); if (olVersionCheck != null) { stmt = conn.prepareStatement(olVersionCheck.getQuery()); stmt.setObject(1, olVersionCheck.getId()); ResultSet rs = stmt.executeQuery(); rs.next(); Number olVersion = (Number) rs.getObject("olVersion"); stmt.close(); stmt = null; if (olVersion.intValue() != olVersionCheck.getOlVersionToCheck().intValue()) { rowsAffected = -1; } } if (rowsAffected >= 0) { for (UpdateStatement query : statements) { stmt = conn.prepareStatement(query.getQuery()); if (query.getParams() != null) { for (int parameterIndex = 1; parameterIndex <= query.getParams().length; parameterIndex++) { Object object = query.getParams()[parameterIndex - 1]; stmt.setObject(parameterIndex, object); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug(" **** Sending statement:\n" + query.getQuery()); } rowsAffected += stmt.executeUpdate(); stmt.close(); stmt = null; } } conn.commit(); conn.close(); conn = null; } catch (SQLException e) { if ("23000".equals(e.getSQLState())) { LOGGER.info("Integrity constraint violation", e); throw new UniqueConstaintException(); } throw new DaoException("error.databaseError", e); } finally { try { if (stmt != null) { LOGGER.debug("closing open statement!"); stmt.close(); } } catch (SQLException e) { throw new DaoException("error.databaseError", e); } finally { stmt = null; } try { if (conn != null) { LOGGER.debug("rolling back open connection!"); conn.rollback(); conn.setAutoCommit(true); conn.close(); } } catch (SQLException e) { throw new DaoException("error.databaseError", e); } finally { conn = null; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("finish executeUpdates"); } return rowsAffected; } Code Sample 2: private <T> Collection<T> loadProviders(final Class<T> providerClass) throws ModelException { try { final String providerNamePrefix = providerClass.getName() + "."; final Map<String, T> providers = new TreeMap<String, T>(new Comparator<String>() { public int compare(final String key1, final String key2) { return key1.compareTo(key2); } }); final File platformProviders = new File(this.getPlatformProviderLocation()); if (platformProviders.exists()) { if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", platformProviders.getAbsolutePath()), null); } InputStream in = null; boolean suppressExceptionOnClose = true; final java.util.Properties p = new java.util.Properties(); try { in = new FileInputStream(platformProviders); p.load(in); suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw e; } } } for (Map.Entry<Object, Object> e : p.entrySet()) { if (e.getKey().toString().startsWith(providerNamePrefix)) { final String configuration = e.getValue().toString(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", platformProviders.getAbsolutePath(), providerClass.getName(), configuration), null); } providers.put(e.getKey().toString(), this.createProviderObject(providerClass, configuration, platformProviders.toURI().toURL())); } } } final Enumeration<URL> classpathProviders = this.findResources(this.getProviderLocation() + '/' + providerClass.getName()); int count = 0; final long t0 = System.currentTimeMillis(); while (classpathProviders.hasMoreElements()) { count++; final URL url = classpathProviders.nextElement(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", url.toExternalForm()), null); } BufferedReader reader = null; boolean suppressExceptionOnClose = true; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("#")) { continue; } if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", url.toExternalForm(), providerClass.getName(), line), null); } providers.put(providerNamePrefix + providers.size(), this.createProviderObject(providerClass, line, url)); } suppressExceptionOnClose = false; } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw new ModelException(getMessage(e), e); } } } } if (this.isLoggable(Level.FINE)) { this.log(Level.FINE, getMessage("contextReport", count, this.getProviderLocation() + '/' + providerClass.getName(), Long.valueOf(System.currentTimeMillis() - t0)), null); } return providers.values(); } catch (final IOException e) { throw new ModelException(getMessage(e), e); } }
11
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
00
Code Sample 1: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
00
Code Sample 1: @Test(expected = GadgetException.class) public void malformedGadgetSpecThrows() throws Exception { HttpRequest request = createIgnoreCacheRequest(); expect(pipeline.execute(request)).andReturn(new HttpResponse("malformed junk")); replay(pipeline); specFactory.getGadgetSpec(createContext(SPEC_URL, true)); } Code Sample 2: public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); }
00
Code Sample 1: protected static String md5(String s) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); byte digest[] = md.digest(); StringBuffer result = new StringBuffer(); for (int i = 0; i < digest.length; i++) { result.append(Integer.toHexString(0xFF & digest[i])); } return result.toString(); } Code Sample 2: public ResponseStatus nowPlaying(String artist, String track, String album, int length, int tracknumber) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); String b = album != null ? encode(album) : ""; String l = length == -1 ? "" : String.valueOf(length); String n = tracknumber == -1 ? "" : String.valueOf(tracknumber); String body = String.format("s=%s&a=%s&t=%s&b=%s&l=%s&n=%s&m=", sessionId, encode(artist), encode(track), b, l, n); if (Caller.getInstance().isDebugMode()) System.out.println("now playing: " + body); Proxy proxy = Caller.getInstance().getProxy(); HttpURLConnection urlConnection = Caller.getInstance().openConnection(nowPlayingUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); return new ResponseStatus(ResponseStatus.codeForStatus(status)); }
11
Code Sample 1: public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; } Code Sample 2: public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; }
00
Code Sample 1: 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); } } Code Sample 2: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: @Override public String transformSingleFile(X3DEditorSupport.X3dEditor xed) { Node[] node = xed.getActivatedNodes(); X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject(); FileObject mySrc = dob.getPrimaryFile(); File mySrcF = FileUtil.toFile(mySrc); File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3d.gz"); TransformListener co = TransformListener.getInstance(); co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting")); co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath()); co.moveToFront(); co.setNode(node[0]); try { FileInputStream fis = new FileInputStream(mySrcF); GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF)); byte[] buf = new byte[4096]; int ret; while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret); gzos.close(); } catch (Exception ex) { co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage()); return null; } co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete")); return myOutF.getAbsolutePath(); } Code Sample 2: public void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } }
00
Code Sample 1: private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); } Code Sample 2: public String buscaCDE() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDE")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDE: " + miLinea); return miLinea; }
00
Code Sample 1: public ObservationResult[] call(String url, String servicename, String srsname, String version, String offering, String observed_property, String responseFormat) { System.out.println("GetObservationBasic.call url " + url); URL service = null; URLConnection connection = null; ArrayList<ObservationResult> obsList = new ArrayList<ObservationResult>(); boolean isDataArrayRead = false; try { service = new URL(url); connection = service.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); try { DataOutputStream out = new DataOutputStream(connection.getOutputStream()); GetObservationDocument getobDoc = GetObservationDocument.Factory.newInstance(); GetObservation getob = getobDoc.addNewGetObservation(); getob.setService(servicename); getob.setVersion(version); getob.setSrsName(srsname); getob.setOffering(offering); getob.setObservedPropertyArray(new String[] { observed_property }); getob.setResponseFormat(responseFormat); String request = URLEncoder.encode(getobDoc.xmlText(), "UTF-8"); out.writeBytes(request); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { URL observation_url = new URL("file:///E:/Temp/Observation.xml"); URLConnection urlc = observation_url.openConnection(); urlc.connect(); InputStream observation_url_is = urlc.getInputStream(); ObservationCollectionDocument obsCollDoc = ObservationCollectionDocument.Factory.parse(observation_url_is); ObservationCollectionType obsColl = obsCollDoc.getObservationCollection(); ObservationPropertyType[] aObsPropType = obsColl.getMemberArray(); for (ObservationPropertyType observationPropertyType : aObsPropType) { ObservationType observation = observationPropertyType.getObservation(); if (observation != null) { System.out.println("observation " + observation.getClass().getName()); ObservationResult obsResult = new ObservationResult(); if (observation instanceof GeometryObservationTypeImpl) { GeometryObservationTypeImpl geometryObservation = (GeometryObservationTypeImpl) observation; TimeObjectPropertyType samplingTime = geometryObservation.getSamplingTime(); TimeInstantTypeImpl timeInstant = (TimeInstantTypeImpl) samplingTime.getTimeObject(); TimePositionType timePosition = timeInstant.getTimePosition(); String time = (String) timePosition.getObjectValue(); StringTokenizer date_st; String day = new StringTokenizer(time, "T").nextToken(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse(day); String timetemp = null; date_st = new StringTokenizer(time, "T"); while (date_st.hasMoreElements()) timetemp = date_st.nextToken(); sdf = new SimpleDateFormat("HH:mm:ss"); Date ti = sdf.parse(timetemp.substring(0, timetemp.lastIndexOf(':') + 2)); d.setHours(ti.getHours()); d.setMinutes(ti.getMinutes()); d.setSeconds(ti.getSeconds()); obsResult.setDatetime(d); String textValue = "null"; FeaturePropertyType featureOfInterest = (FeaturePropertyType) geometryObservation.getFeatureOfInterest(); Node fnode = featureOfInterest.getDomNode(); NodeList childNodes = fnode.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node cnode = childNodes.item(j); if (cnode.getNodeName().equals("n52:movingObject")) { NamedNodeMap att = cnode.getAttributes(); Node id = att.getNamedItem("gml:id"); textValue = id.getNodeValue(); obsResult.setTextValue(textValue); obsResult.setIsTextValue(true); } } XmlObject result = geometryObservation.getResult(); if (result instanceof GeometryPropertyTypeImpl) { GeometryPropertyTypeImpl geometryPropertyType = (GeometryPropertyTypeImpl) result; AbstractGeometryType geometry = geometryPropertyType.getGeometry(); String srsName = geometry.getSrsName(); StringTokenizer st = new StringTokenizer(srsName, ":"); String epsg = null; while (st.hasMoreElements()) epsg = st.nextToken(); int sri = Integer.parseInt(epsg); if (geometry instanceof PointTypeImpl) { PointTypeImpl point = (PointTypeImpl) geometry; Node node = point.getDomNode(); PointDocument pointDocument = PointDocument.Factory.parse(node); PointType point2 = pointDocument.getPoint(); XmlCursor cursor = point.newCursor(); cursor.toFirstChild(); CoordinatesDocument coordinatesDocument = CoordinatesDocument.Factory.parse(cursor.xmlText()); CoordinatesType coords = coordinatesDocument.getCoordinates(); StringTokenizer tok = new StringTokenizer(coords.getStringValue(), " ,;", false); double x = Double.parseDouble(tok.nextToken()); double y = Double.parseDouble(tok.nextToken()); double z = 0; if (tok.hasMoreTokens()) { z = Double.parseDouble(tok.nextToken()); } x += 207561; y += 3318814; z += 20; Point3d center = new Point3d(x, y, z); obsResult.setCenter(center); GeometryFactory fact = new GeometryFactory(); Coordinate coordinate = new Coordinate(x, y, z); Geometry g1 = fact.createPoint(coordinate); g1.setSRID(sri); obsResult.setGeometry(g1); String href = observation.getProcedure().getHref(); obsResult.setProcedure(href); obsList.add(obsResult); } } } } } observation_url_is.close(); } catch (IOException e) { e.printStackTrace(); } catch (XmlException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } ObservationResult[] ar = new ObservationResult[obsList.size()]; return obsList.toArray(ar); } Code Sample 2: public InputStream getPage(String page) throws IOException { URL url = new URL(hattrickServerURL + "/Common/" + page); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestProperty("Cookie", sessionCookie); return huc.getInputStream(); }
00
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; }
11
Code Sample 1: private void copy(String inputPath, String outputPath, String name) { try { FileReader in = new FileReader(inputPath + name); FileWriter out = new FileWriter(outputPath + name); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
00
Code Sample 1: public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } } Code Sample 2: public void loadProperties() throws IOException { File file = new File(filename); URL url = file.toURI().toURL(); Properties temp = new Properties(); temp.load(url.openStream()); Point2d start = new Point2d(); Point2d end = new Point2d(); if (temp.getProperty("StartX") != null) try { start.x = Double.valueOf(temp.getProperty("StartX")); } catch (Exception e) { System.out.println("Error loading StartX - leaving as default: " + e); } if (temp.getProperty("StartY") != null) try { start.y = Double.valueOf(temp.getProperty("StartY")); } catch (Exception e) { System.out.println("Error loading StartY - leaving as default: " + e); } if (temp.getProperty("EndX") != null) try { end.x = Double.valueOf(temp.getProperty("EndX")); } catch (Exception e) { System.out.println("Error loading EndX - leaving as default: " + e); } if (temp.getProperty("EndY") != null) try { end.y = Double.valueOf(temp.getProperty("EndY")); } catch (Exception e) { System.out.println("Error loading EndY - leaving as default: " + e); } initialline = new LineSegment2D(start, end); if (temp.getProperty("ReferenceImage") != null) try { referenceimage = Integer.valueOf(temp.getProperty("ReferenceImage")); } catch (Exception e) { System.out.println("Error loading ReferenceImage - leaving as default: " + e); } }
11
Code Sample 1: public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: 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)"); }
11
Code Sample 1: public void save(UploadedFile file, Long student, Long activity) { File destiny = new File(fileFolder, student + "_" + activity + "_" + file.getFileName()); try { IOUtils.copy(file.getFile(), new FileOutputStream(destiny)); } catch (IOException e) { throw new RuntimeException("Erro ao copiar o arquivo.", e); } } Code Sample 2: public void copyFile2(String src, String dest) throws IOException { String newLine = System.getProperty("line.separator"); FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + QZ.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(QZ.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
00
Code Sample 1: public static URL getComponentXmlFileWith(String name) throws Exception { List<URL> all = getComponentXmlFiles(); for (URL url : all) { InputStream stream = null; try { stream = url.openStream(); Element root = XML.getRootElement(stream); for (Element elem : (List<Element>) root.elements()) { String ns = elem.getNamespace().getURI(); if (name.equals(elem.attributeValue("name"))) { return url; } } } finally { Resources.closeStream(stream); } } return null; } Code Sample 2: public static String md5(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exception) { LOGGER.warn(exception.getMessage()); } byte[] md5hash = new byte[32]; try { md.update(string.getBytes("iso-8859-1"), 0, string.length()); } catch (UnsupportedEncodingException exception) { LOGGER.warn(exception.getMessage()); } md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; } Code Sample 2: public TtsTrackImpl(URL url, String voiceName, VoicesCache vc) throws IOException { this.voiceCache = vc; isReady = false; URLConnection connection = url.openConnection(); frameSize = (int) (period * format.getChannels() * format.getSampleSizeInBits() * format.getSampleRate() / 8000); voice = voiceCache.allocateVoice(voiceName); TTSAudioBuffer audioBuffer = new TTSAudioBuffer(); this.voice.setAudioPlayer(audioBuffer); this.voice.speak(connection.getInputStream()); audioBuffer.flip(); }
00
Code Sample 1: public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: protected void addAssetResources(MimeMultipart pkg, MarinerPageContext context) throws PackagingException { boolean includeFullyQualifiedURLs = context.getBooleanDevicePolicyValue("protocol.mime.fully.qualified.urls"); MarinerRequestContext requestContext = context.getRequestContext(); ApplicationContext ac = ContextInternals.getApplicationContext(requestContext); PackageResources pr = ac.getPackageResources(); List encodedURLs = pr.getEncodedURLs(); Map assetURLMap = pr.getAssetURLMap(); Iterator iterator; String encodedURL; PackageResources.Asset asset; String assetURL = null; BodyPart assetPart; if (encodedURLs != null) { iterator = encodedURLs.iterator(); } else { iterator = assetURLMap.keySet().iterator(); } while (iterator.hasNext()) { encodedURL = (String) iterator.next(); asset = (PackageResources.Asset) assetURLMap.get(encodedURL); assetURL = asset.getValue(); if (includeFullyQualifiedURLs || !isFullyQualifiedURL(assetURL)) { if (isToBeAdded(assetURL, context)) { assetPart = new MimeBodyPart(); try { if (!asset.getOnClientSide()) { URL url = null; URLConnection connection; try { url = context.getAbsoluteURL(new MarinerURL(assetURL)); connection = url.openConnection(); if (connection != null) { connection.setDoInput(true); connection.setDoOutput(false); connection.setAllowUserInteraction(false); connection.connect(); connection.getInputStream(); assetPart.setDataHandler(new DataHandler(url)); assetPart.setHeader("Content-Location", assetURL); pkg.addBodyPart(assetPart); } } catch (MalformedURLException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with malformed URL: " + url.toString()); } } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with URL that doesn't " + "exist: " + assetURL + " (" + url.toString() + ")"); } } } else { assetPart.setHeader("Content-Location", "file://" + assetURL); } } catch (MessagingException e) { throw new PackagingException(exceptionLocalizer.format("could-not-add-asset", encodedURL), e); } } } } }
11
Code Sample 1: public void handler(List<GoldenBoot> gbs, TargetPage target) { try { URL url = new URL(target.getUrl()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; String include = "Top Scorers"; while ((line = reader.readLine()) != null) { if (line.indexOf(include) != -1) { buildGildenBoot(line, gbs); break; } } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public static void addClasses(URL url) { BufferedReader reader = null; String line; ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { line = line.trim(); if ((line.length() == 0) || line.startsWith(";")) { continue; } try { classes.add(Class.forName(line, true, cl)); } catch (Throwable t) { } } } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } }
11
Code Sample 1: public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } }
11
Code Sample 1: public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; } Code Sample 2: private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } }
00
Code Sample 1: public static String getPageSource(String url) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder source = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) source.append(line); in.close(); return source.toString(); } Code Sample 2: private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
11
Code Sample 1: protected void unZip() throws PersistenceException { boolean newZip = false; try { if (null == backup) { mode = (String) context.get(Context.MODE); if (null == mode) mode = Context.MODE_NAME_RESTORE; backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY); logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backupDirectory.mkdirs(); } else if (!backupDirectory.exists()) { throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist."); } backup = new File(backupDirectory + "/" + getBackupName() + ".zip"); logger.debug("Got zip file {" + backup.getAbsolutePath() + "}"); } File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip"); _explodedDirectory.mkdirs(); _explodedDirectory.delete(); backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName()); backupDirectory.mkdirs(); logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backup.createNewFile(); } else if (!backup.exists()) { throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist."); } if (newZip) return; ZipFile zip = new ZipFile(backup); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); logger.debug("Inflating: " + entry); File destFile = new File(backupDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zip.getInputStream(entry); out = new FileOutputStream(destFile); IOUtils.copy(in, out); } finally { if (null != out) out.close(); if (null != in) in.close(); } } } } catch (IOException e) { logger.error("Unable to unzip {" + backup + "}", e); throw new PersistenceException(e); } } Code Sample 2: private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: public static 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; } Code Sample 2: private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
11
Code Sample 1: @Override public synchronized void deleteHttpSessionStatistics(String contextName, String project, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHttpSessionInvocationsSchemaAndTableName() + " FROM " + this.getHttpSessionInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHttpSessionElementsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (project != null) { queryString = queryString + " project LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (project != null) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting HTTP session statistics.", e); } finally { this.releaseConnection(connection); } } Code Sample 2: private void addDocToDB(String action, DataSource database) { String typeOfDoc = findTypeOfDoc(action).trim().toLowerCase(); Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); checkDupDoc(typeOfDoc, con); String add = "insert into " + typeOfDoc + " values( ?, ?, ?, ?, ?, ?, ? )"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getCourseId()); prepStatement.setString(2, selectedCourse.getAdmin()); prepStatement.setTimestamp(3, getTimeStamp()); prepStatement.setString(4, getLink()); prepStatement.setString(5, homePage.getUser()); prepStatement.setString(6, getText()); prepStatement.setString(7, getTitle()); prepStatement.executeUpdate(); prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } }
11
Code Sample 1: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); } Code Sample 2: public void backupFile(File fromFile, File toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (IOException e) { log.error(e.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
11
Code Sample 1: public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); } Code Sample 2: @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("sort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("sort :: INPATH not given."); return 3; } final String wrkDir = args.get(0), out = (String) parser.getOptionValue(outputFileOpt); final List<String> strInputs = args.subList(1, args.size()); final List<Path> inputs = new ArrayList<Path>(strInputs.size()); for (final String in : strInputs) inputs.add(new Path(in)); final boolean verbose = parser.getBoolean(verboseOpt); final String intermediateOutName = out == null ? inputs.get(0).getName() : out; final Configuration conf = getConf(); conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0])); conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName); final Path wrkDirPath = new Path(wrkDir); final Timer t = new Timer(); try { for (final Path in : inputs) Utils.configureSampling(in, conf); @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = new Job(conf); job.setJarByClass(Sort.class); job.setMapperClass(Mapper.class); job.setReducerClass(SortReducer.class); job.setMapOutputKeyClass(LongWritable.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(SAMRecordWritable.class); job.setInputFormatClass(BAMInputFormat.class); job.setOutputFormatClass(SortOutputFormat.class); for (final Path in : inputs) FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, wrkDirPath); job.setPartitionerClass(TotalOrderPartitioner.class); System.out.println("sort :: Sampling..."); t.start(); InputSampler.<LongWritable, SAMRecordWritable>writePartitionFile(job, new InputSampler.IntervalSampler<LongWritable, SAMRecordWritable>(0.01, 100)); System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms()); job.submit(); System.out.println("sort :: Waiting for job completion..."); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("sort :: Job failed."); return 4; } System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("sort :: Merging output..."); t.start(); final Path outPath = new Path(out); final FileSystem srcFS = wrkDirPath.getFileSystem(conf); FileSystem dstFS = outPath.getFileSystem(conf); if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem) dstFS).getRaw(); final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File("")); w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true); w.setHeader(getHeaderMerger(conf).getMergedHeader()); w.close(); final OutputStream outs = dstFS.append(outPath); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Output merging failed: %s\n", e); return 5; } return 0; }
11
Code Sample 1: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; }
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 File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
11
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } if (action.equals("login")) { String username = request.getParameter("username"); String password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { error = "There was an error encrypting password."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } String encrypted_password = (new BASE64Encoder()).encode(md.digest()); try { String sql = "SELECT * FROM person WHERE email LIKE '" + username + "' AND password='" + encrypted_password + "'"; dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { Person person = new Person(dbResultSet.getString("fname"), dbResultSet.getString("lname"), dbResultSet.getString("address1"), dbResultSet.getString("address2"), dbResultSet.getString("city"), dbResultSet.getString("state"), dbResultSet.getString("zip"), dbResultSet.getString("email"), dbResultSet.getString("password"), dbResultSet.getInt("is_admin")); String member_type = dbResultSet.getString("member_type"); String person_id = Integer.toString(dbResultSet.getInt("id")); session.setAttribute("person", person); session.setAttribute("member_type", member_type); session.setAttribute("person_id", person_id); } else { notice = "Your username and/or password is incorrect."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } catch (SQLException e) { error = "There was an error trying to login. (SQL Statement)"; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Unable to log you in. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp"); dispatcher.forward(request, response); return; } } Code Sample 2: public synchronized String encrypt(String plaintext) { MessageDigest md = null; String hash = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hash; }
11
Code Sample 1: public static long toFile(final DigitalObject object, final File file) { try { FileOutputStream fOut = new FileOutputStream(file); long bytesCopied = IOUtils.copyLarge(object.getContent().getInputStream(), fOut); fOut.close(); return bytesCopied; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; } Code Sample 2: @Override public File fetchHSMFile(String fsID, String filePath) throws HSMException { log.debug("fetchHSMFile called with fsID=" + fsID + ", filePath=" + filePath); if (absIncomingDir.mkdirs()) { log.info("M-WRITE " + absIncomingDir); } File tarFile; try { tarFile = File.createTempFile("hsm_", ".tar", absIncomingDir); } catch (IOException x) { throw new HSMException("Failed to create temp file in " + absIncomingDir, x); } log.info("Fetching " + filePath + " from cloud storage"); FileOutputStream fos = null; try { if (s3 == null) createClient(); S3Object object = s3.getObject(new GetObjectRequest(bucketName, filePath)); fos = new FileOutputStream(tarFile); IOUtils.copy(object.getObjectContent(), fos); } catch (AmazonClientException ace) { s3 = null; throw new HSMException("Could not list objects for: " + filePath, ace); } catch (Exception x) { throw new HSMException("Failed to retrieve " + filePath, x); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("Couldn't close output stream for: " + tarFile); } } } return tarFile; }
11
Code Sample 1: private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } } Code Sample 2: public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } }
00
Code Sample 1: public static void downloadURLNow(URL url, File to, SHA1Sum sha1, boolean force) throws Exception { { String sep = System.getProperty("file.separator"); String folders = to.getPath(); String path = ""; for (int i = 0; i < folders.length(); i++) { path += folders.charAt(i); if (path.endsWith(sep)) { File f = new File(path); if (!f.exists()) f.mkdir(); if (!f.isDirectory()) { Out.error(URLDownloader.class, path + " is not a directory!"); return; } } } } Out.info(URLDownloader.class, "Downloading " + url.toExternalForm()); URLConnection uc = url.openConnection(); DataInputStream is = new DataInputStream(new BufferedInputStream(uc.getInputStream())); FileOutputStream os = new FileOutputStream(to); byte[] b = new byte[1024]; int fileLength = uc.getHeaderFieldInt("Content-Length", 0) / b.length; Task task = null; if (fileLength > 0) task = TaskManager.createTask(url.toExternalForm(), fileLength, "kB"); do { int c = is.read(b); if (c == -1) break; os.write(b, 0, c); if (task != null) task.advanceProgress(); } while (true); if (task != null) task.complete(); os.close(); is.close(); } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { if (doc instanceof XMLDOMDocument) { writer.writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { ManagedFile result = resolveFileFor(folder, (BinaryDocument) doc); IOUtils.copy(bin.getContent().getInputStream(), result.getContent().getOutputStream()); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
11
Code Sample 1: public static String generateStringSHA256(String content) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ScannerChecksum.class.getName()).log(Level.SEVERE, null, ex); } md.update(content.getBytes()); byte byteData[] = md.digest(); @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } Code Sample 2: public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
00
Code Sample 1: public byte[] uniqueID(String name, String topic) { String key; byte[] id; synchronized (cache_) { key = name + "|" + topic; id = (byte[]) cache_.get(key); if (id == null) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); md.update(name.getBytes()); md.update(topic.getBytes()); id = md.digest(); cache_.put(key, id); if (debug_) { System.out.println("Cached " + key + " [" + id[0] + "," + id[1] + ",...]"); } } catch (NoSuchAlgorithmException e) { throw new Error("SHA not available!"); } } } return id; } Code Sample 2: private static String readJarURL(URL url) throws IOException { JarURLConnection juc = (JarURLConnection) url.openConnection(); InputStream in = juc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { out.write(i); i = in.read(); } return out.toString(); }
00
Code Sample 1: public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream); if (response.contains("<str name=\"status\">success</str>")) { success = true; } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copyFile(File in, File out, boolean read, boolean write, boolean execute) throws FileNotFoundException, IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); File outFile = null; if (out.isDirectory()) { outFile = new File(out.getAbsolutePath() + File.separator + in.getName()); } else { outFile = out; } FileChannel outChannel = new FileOutputStream(outFile).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } outFile.setReadable(read); outFile.setWritable(write); outFile.setExecutable(execute); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
11
Code Sample 1: public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void main(String args[]) { InputStream input = System.in; OutputStream output = System.out; if (args.length > 0) { try { input = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[0]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[0]); System.exit(-1); } } if (args.length > 1) { try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[1]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[1]); System.exit(-1); } } byte buffer[] = new byte[512]; int len; try { while ((len = input.read(buffer)) > 0) output.write(buffer, 0, len); } catch (IOException e) { System.err.println("Error copying file"); } finally { input.close(); 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: private File copyFile(File file, String newName, File folder) { File newFile = null; if (!file.exists()) { System.out.println("File " + file + " does not exist"); return null; } if (file.isFile()) { BufferedOutputStream out = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); newFile = new File(folder, newName); if (!newFile.exists()) { newFile.createNewFile(); } out = new BufferedOutputStream(new FileOutputStream(newFile)); int read; byte[] buffer = new byte[8192]; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } updateTreeUI(); } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } } } else if (file.isDirectory()) { newFile = new File(folder, newName); if (!newFile.exists()) { newFile.mkdir(); } for (File f : file.listFiles()) { copyFile(f, f.getName(), newFile); } } return newFile; }
11
Code Sample 1: public void exportFile() { String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY); File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc"); File f = new File(absPath); try { FileOutputStream fout = new FileOutputStream(out); FileInputStream fin = new FileInputStream(f); int read = 0; byte[] buffer = new byte[1024 * 1024]; while ((read = fin.read(buffer)) > 0) { fout.write(buffer, 0, read); } fin.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } }
11
Code Sample 1: public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; } Code Sample 2: private void getXMLData() { String result = null; URL url = null; URLConnection conn = null; BufferedReader rd = null; StringBuffer sb = new StringBuffer(); String line; try { url = new URL(this.url); conn = url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (MalformedURLException e) { log.error("URL was malformed: {}", url, e); } catch (IOException e) { log.error("IOException thrown: {}", url, e); } this.xmlString = result; }
00
Code Sample 1: public static void main(String[] args) { CookieManager cm = new CookieManager(); try { URL url = new URL("http://www.hccp.org/test/cookieTest.jsp"); URLConnection conn = url.openConnection(); conn.connect(); cm.storeCookies(conn); System.out.println(cm); cm.setCookies(url.openConnection()); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public static boolean downloadFile(String urlString, String outputFile, int protocol) { InputStream is = null; File file = new File(outputFile); FileOutputStream fos = null; if (protocol == HTTP_PROTOCOL) { try { URL url = new URL(urlString); URLConnection ucnn = null; if (BlueXStatics.proxy == null || url.getProtocol().equals("file")) ucnn = url.openConnection(); else ucnn = url.openConnection(BlueXStatics.proxy); is = ucnn.getInputStream(); fos = new FileOutputStream(file); byte[] data = new byte[4096]; int offset; while ((offset = is.read(data)) != -1) { fos.write(data, 0, offset); } return true; } catch (Exception ex) { } finally { try { is.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } } else throw new ProtocolNotSupportedException("The protocol selected is not supported by this version of downloadFile() method."); return false; }
00
Code Sample 1: public static void call(String host, String port, String method, String[] params) { cat.debug("call (host:" + host + " port:" + port + " method:" + method); try { String message = null; StringBuffer bufMessage = new StringBuffer(); bufMessage.append("<?xml version='1.0' encoding='ISO-8859-1'?>"); bufMessage.append("<methodCall>"); bufMessage.append("<methodName>"); bufMessage.append(method); bufMessage.append("</methodName>"); bufMessage.append("<params>"); if (params != null && params.length > 0) { for (int i = 0; i < params.length; i++) { bufMessage.append("<param><value><![CDATA[" + params[i] + "]]></value></param>"); } } bufMessage.append("</params></methodCall>"); message = bufMessage.toString(); bufMessage = null; String stringUrl = "http://" + host + ":" + port + "/RPC2"; cat.debug("Sending message to: " + stringUrl + "\n" + message); URL url = new URL(stringUrl); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.getOutputStream().write(message.getBytes()); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { cat.debug("#server# " + line); } bufferedReader.close(); } catch (Exception e) { cat.debug("Unable to send link to Gnowsis!", e); } } Code Sample 2: public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
11
Code Sample 1: public String get(String s, String encoding) throws Exception { if (!s.startsWith("http")) return ""; StringBuilder sb = new StringBuilder(); try { String result = null; URL url = new URL(s); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); if (encoding == null) encoding = "UTF-8"; BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding)); String inputLine; String contentType = connection.getContentType(); if (contentType.startsWith("text") || contentType.startsWith("application/xml")) { while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw e; } return sb.toString(); } Code Sample 2: private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException { boolean parsed = false; try { InputStream data_stream = url.openStream(); parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp); } catch (OutputMalFormatException ex) { throw new OutputMalFormatException(ex.getMessage(), ex); } catch (Exception ex) { System.out.println(ex.getMessage()); } return parsed; } Code Sample 2: @Test public void test_baseMaterialsForTypeID_NonExistingID() throws Exception { URL url = new URL(baseUrl + "/baseMaterialsForTypeID/1234567890"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
00
Code Sample 1: public static void main(String[] args) { URL url = null; EventHeap eh = new EventHeap("iw-room2"); Event newEvent; float chan1 = -1, chan2 = -1; try { url = new URL("http://iw--bluetooth-ap/cgi-bin/sens.cgi"); } catch (MalformedURLException e) { } byte buf[] = new byte[1000]; while (true) { try { InputStream in = url.openStream(); int length = in.read(buf); String page = new String(buf); String data = page.substring(290); if (data.startsWith("No Sensors Found")) { Thread.sleep(1000); } else { String sensorID = data.substring(15, 32); String channel1 = data.substring(163, 167); String channel2 = data.substring(266, 270); if (Float.parseFloat(channel1) != chan1) { System.out.println(sensorID); System.out.println("Channel 1:" + channel1); newEvent = new Event("iStuffInputEvent"); newEvent.addField("Device", "Slider"); newEvent.addField("ID", sensorID + ":channel1"); newEvent.addField("Value", channel1); newEvent.addField("Max", String.valueOf(5)); newEvent.addField("Min", String.valueOf(0)); eh.putEvent(newEvent); chan1 = Float.parseFloat(channel1); } } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: public static String sha1(String src) { MessageDigest md1 = null; try { md1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { md1.update(src.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hex(md1.digest()); }
00
Code Sample 1: public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } } Code Sample 2: private static String downloadMedia(String mediadir, URL remoteFile) throws Exception, InterruptedException { File tmpDir = new File(System.getProperty("java.io.tmpdir") + "org.ogre4j.examples/" + mediadir); if (!tmpDir.exists()) { tmpDir.mkdirs(); } URLConnection urlConnection = remoteFile.openConnection(); if (urlConnection.getConnectTimeout() != 0) { urlConnection.setConnectTimeout(0); } InputStream content = remoteFile.openStream(); BufferedInputStream bin = new BufferedInputStream(content); String downloaded = tmpDir.getCanonicalPath() + File.separatorChar + new File(remoteFile.getFile()).getName(); File file = new File(downloaded); BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(file)); System.out.println("downloading file " + remoteFile + " ..."); for (long i = 0; i < urlConnection.getContentLength(); i++) { bout.write(bin.read()); } bout.close(); bout = null; bin.close(); return downloaded; }
00
Code Sample 1: private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } } Code Sample 2: public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void main(String[] args) { int[] mas = { 5, 10, 20, -30, 55, -60, 9, -40, -20 }; int next; for (int a = 0; a < mas.length; a++) { for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { next = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = next; } } } for (int i = 0; i < mas.length; i++) System.out.print(" " + mas[i]); }
00
Code Sample 1: private static Map<String, File> loadServiceCache() { ArrayList<String> preferredOrder = new ArrayList<String>(); HashMap<String, File> serviceFileMapping = new HashMap<String, File>(); File file = new File(IsqlToolkit.getBaseDirectory(), CACHE_FILE); if (!file.exists()) { return serviceFileMapping; } if (file.canRead()) { FileReader fileReader = null; try { fileReader = new FileReader(file); BufferedReader lineReader = new BufferedReader(fileReader); while (lineReader.ready()) { String data = lineReader.readLine(); if (data.charAt(0) == '#') { continue; } int idx0 = 0; int idx1 = data.indexOf(SERVICE_FIELD_SEPERATOR); String name = StringUtilities.decodeASCII(data.substring(idx0, idx1)); String uri = StringUtilities.decodeASCII(data.substring(idx1 + 1)); if (name.equalsIgnoreCase(KEY_SERVICE_LIST)) { StringTokenizer st = new StringTokenizer(uri, SERVICE_SEPERATOR); while (st.hasMoreTokens()) { String serviceName = st.nextToken(); preferredOrder.add(serviceName.toLowerCase().trim()); } continue; } try { URL url = new URL(uri); File serviceFile = new File(url.getFile()); if (serviceFile.isDirectory()) { logger.warn(messages.format("compatability_kit.service_mapped_to_directory", name, uri)); continue; } else if (!serviceFile.canRead()) { logger.warn(messages.format("compatability_kit.service_not_readable", name, uri)); continue; } else if (!serviceFile.exists()) { logger.warn(messages.format("compatability_kit.service_does_not_exist", name, uri)); continue; } String bindName = name.toLowerCase().trim(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); bindName = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()).getName(); } catch (Exception error) { continue; } if (serviceFileMapping.put(bindName, serviceFile) != null) { logger.warn(messages.format("compatability_kit.service_duplicate_name_error", name, uri)); } } catch (MalformedURLException e) { logger.error(messages.format("compatability_kit.service_uri_error", name, uri), e); } } } catch (IOException ioe) { logger.error("compatability_kit.service_generic_error", ioe); } finally { if (fileReader != null) { try { fileReader.close(); } catch (Throwable ignored) { } } } } return serviceFileMapping; } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: static synchronized Person lookup(PhoneNumber number, String siteName) { Vector<Person> foundPersons = new Vector<Person>(5); if (number.isFreeCall()) { Person p = new Person("", "FreeCall"); p.addNumber(number); foundPersons.add(p); } else if (number.isSIPNumber() || number.isQuickDial()) { Person p = new Person(); p.addNumber(number); foundPersons.add(p); } else if (ReverseLookup.rlsMap.containsKey(number.getCountryCode())) { nummer = number.getAreaNumber(); rls_list = ReverseLookup.rlsMap.get(number.getCountryCode()); Debug.info("Begin reverselookup for: " + nummer); if (nummer.startsWith(number.getCountryCode())) nummer = nummer.substring(number.getCountryCode().length()); city = ""; for (int i = 0; i < rls_list.size(); i++) { yield(); rls = rls_list.get(i); if (!siteName.equals("") && !siteName.equals(rls.getName())) { Debug.warning("This lookup should be done using a specific site, skipping"); continue; } prefix = rls.getPrefix(); ac_length = rls.getAreaCodeLength(); if (!nummer.startsWith(prefix)) nummer = prefix + nummer; urlstr = rls.getURL(); if (urlstr.contains("$AREACODE")) { urlstr = urlstr.replaceAll("\\$AREACODE", nummer.substring(prefix.length(), ac_length + prefix.length())); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else if (urlstr.contains("$PFXAREACODE")) { urlstr = urlstr.replaceAll("\\$PFXAREACODE", nummer.substring(0, prefix.length() + ac_length)); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else urlstr = urlstr.replaceAll("\\$NUMBER", nummer); Debug.info("Reverse lookup using: " + urlstr); url = null; data = new String[dataLength]; try { url = new URL(urlstr); if (url != null) { try { con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(15000); con.addRequestProperty("User-Agent", userAgent); con.connect(); header = ""; charSet = ""; for (int j = 0; ; j++) { String headerName = con.getHeaderFieldKey(j); String headerValue = con.getHeaderField(j); if (headerName == null && headerValue == null) { break; } if ("content-type".equalsIgnoreCase(headerName)) { String[] split = headerValue.split(";", 2); for (int k = 0; k < split.length; k++) { if (split[k].trim().toLowerCase().startsWith("charset=")) { String[] charsetSplit = split[k].split("="); charSet = charsetSplit[1].trim(); } } } header += headerName + ": " + headerValue + " | "; } Debug.debug("Header of " + rls.getName() + ":" + header); Debug.debug("CHARSET : " + charSet); BufferedReader d; if (charSet.equals("")) { d = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); } else { d = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } int lines = 0; while (null != ((str = d.readLine()))) { data[lines] = str; yield(); if (lines >= dataLength) { System.err.println("Result > " + dataLength + " Lines"); break; } lines++; } d.close(); Debug.info("Begin processing response from " + rls.getName()); for (int j = 0; j < rls.size(); j++) { yield(); firstname = ""; lastname = ""; company = ""; street = ""; zipcode = ""; city = ""; Person p = null; patterns = rls.getEntry(j); Pattern namePattern = null; Pattern streetPattern = null; Pattern cityPattern = null; Pattern zipcodePattern = null; Pattern firstnamePattern = null; Pattern lastnamePattern = null; Matcher nameMatcher = null; Matcher streetMatcher = null; Matcher cityMatcher = null; Matcher zipcodeMatcher = null; Matcher firstnameMatcher = null; Matcher lastnameMatcher = null; if (!patterns[ReverseLookupSite.NAME].equals("") && (patterns[ReverseLookupSite.FIRSTNAME].equals("") && patterns[ReverseLookupSite.LASTNAME].equals(""))) { namePattern = Pattern.compile(patterns[ReverseLookupSite.NAME]); } if (!patterns[ReverseLookupSite.STREET].equals("")) { streetPattern = Pattern.compile(patterns[ReverseLookupSite.STREET]); } if (!patterns[ReverseLookupSite.CITY].equals("")) { cityPattern = Pattern.compile(patterns[ReverseLookupSite.CITY]); } if (!patterns[ReverseLookupSite.ZIPCODE].equals("")) { zipcodePattern = Pattern.compile(patterns[ReverseLookupSite.ZIPCODE]); } if (!patterns[ReverseLookupSite.FIRSTNAME].equals("")) { firstnamePattern = Pattern.compile(patterns[ReverseLookupSite.FIRSTNAME]); } if (!patterns[ReverseLookupSite.LASTNAME].equals("")) { lastnamePattern = Pattern.compile(patterns[ReverseLookupSite.LASTNAME]); } for (int line = 0; line < dataLength; line++) { if (data[line] != null) { int spaceAlternative = 160; data[line] = data[line].replaceAll(new Character((char) spaceAlternative).toString(), " "); if (lastnamePattern != null) { lastnameMatcher = lastnamePattern.matcher(data[line]); if (lastnameMatcher.find()) { str = ""; for (int k = 1; k <= lastnameMatcher.groupCount(); k++) { if (lastnameMatcher.group(k) != null) str = str + lastnameMatcher.group(k).trim() + " "; } lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if ("lastname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setLastName(lastname); } } } yield(); if (firstnamePattern != null) { firstnameMatcher = firstnamePattern.matcher(data[line]); if (firstnameMatcher.find()) { str = ""; for (int k = 1; k <= firstnameMatcher.groupCount(); k++) { if (firstnameMatcher.group(k) != null) str = str + firstnameMatcher.group(k).trim() + " "; } firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); firstname = firstname.trim(); firstname = firstname.replaceAll(",", ""); firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); if ("firstname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); } } } yield(); if (namePattern != null) { nameMatcher = namePattern.matcher(data[line]); if (nameMatcher.find()) { str = ""; for (int k = 1; k <= nameMatcher.groupCount(); k++) { if (nameMatcher.group(k) != null) str = str + nameMatcher.group(k).trim() + " "; } String[] split; split = str.split(" ", 2); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(split[0])); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if (split[1].length() > 0) { firstname = HTMLUtil.stripEntities(split[1]); if ((firstname.indexOf(" ") > -1) && (firstname.indexOf(" u.") == -1)) { company = JFritzUtils.removeLeadingSpaces(firstname.substring(firstname.indexOf(" ")).trim()); firstname = JFritzUtils.removeLeadingSpaces(firstname.substring(0, firstname.indexOf(" ")).trim()); } else { firstname = JFritzUtils.removeLeadingSpaces(firstname.replaceAll(" u. ", " und ")); } } firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); firstname = firstname.trim(); company = company.replaceAll("%20", " "); company = JFritzUtils.replaceSpecialCharsUTF(company); company = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(company)); company = JFritzUtils.removeDuplicateWhitespace(company); company = company.trim(); if ("name".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); if (company.length() > 0) { p.addNumber(number.getIntNumber(), "business"); } else { p.addNumber(number.getIntNumber(), "home"); } foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); p.setLastName(lastname); p.setCompany(company); } } } yield(); if (streetPattern != null) { streetMatcher = streetPattern.matcher(data[line]); if (streetMatcher.find()) { str = ""; for (int k = 1; k <= streetMatcher.groupCount(); k++) { if (streetMatcher.group(k) != null) str = str + streetMatcher.group(k).trim() + " "; } street = str.replaceAll("%20", " "); street = JFritzUtils.replaceSpecialCharsUTF(street); street = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(street)); street = JFritzUtils.removeDuplicateWhitespace(street); street = street.trim(); if ("street".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setStreet(street); } } } yield(); if (cityPattern != null) { cityMatcher = cityPattern.matcher(data[line]); if (cityMatcher.find()) { str = ""; for (int k = 1; k <= cityMatcher.groupCount(); k++) { if (cityMatcher.group(k) != null) str = str + cityMatcher.group(k).trim() + " "; } city = str.replaceAll("%20", " "); city = JFritzUtils.replaceSpecialCharsUTF(city); city = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(city)); city = JFritzUtils.removeDuplicateWhitespace(city); city = city.trim(); if ("city".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setCity(city); } } } yield(); if (zipcodePattern != null) { zipcodeMatcher = zipcodePattern.matcher(data[line]); if (zipcodeMatcher.find()) { str = ""; for (int k = 1; k <= zipcodeMatcher.groupCount(); k++) { if (zipcodeMatcher.group(k) != null) str = str + zipcodeMatcher.group(k).trim() + " "; } zipcode = str.replaceAll("%20", " "); zipcode = JFritzUtils.replaceSpecialCharsUTF(zipcode); zipcode = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(zipcode)); zipcode = JFritzUtils.removeDuplicateWhitespace(zipcode); zipcode = zipcode.trim(); if ("zipcode".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setPostalCode(zipcode); } } } } } if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) break; } yield(); if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) { if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } return foundPersons.get(0); } } catch (IOException e1) { Debug.error("Error while retrieving " + urlstr); } } } catch (MalformedURLException e) { Debug.error("URL invalid: " + urlstr); } } yield(); Debug.warning("No match for " + nummer + " found"); if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } Person p = new Person("", "", "", "", "", city, "", ""); p.addNumber(number.getAreaNumber(), "home"); return p; } else { Debug.warning("No reverse lookup sites for: " + number.getCountryCode()); Person p = new Person(); p.addNumber(number.getAreaNumber(), "home"); if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(number.getIntNumber()); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(number.getIntNumber()); p.setCity(city); return p; } return new Person("not found", "Person"); } Code Sample 2: 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 URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { } } } return url; } Code Sample 2: public String sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException, NotFoundException { logger.debug(request.getRequestLine().toString()); DefaultHttpClient httpclient = HttpUtil.getNewHttpClient(); configureProxy(httpclient); if (login != null) { final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET))); request.addHeader("Authorization", "Basic: " + credentials); } request.addHeader("Accept-Encoding", "gzip,deflate"); HttpResponse httpResponse = httpclient.execute((HttpUriRequest) request); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server."); } if (responseCode == HttpStatus.SC_FORBIDDEN) { throw new AuthenticationException("Forbidden. Please check the user has proper permissions."); } HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); if (responseCode == HttpStatus.SC_NOT_FOUND) { throw new NotFoundException("Server returned '404 not found'. response body:" + responseBody); } if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { List<String> errors = RedmineXMLParser.parseErrors(responseBody); throw new RedmineException(errors); } httpclient.getConnectionManager().shutdown(); return responseBody; }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.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: private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
00
Code Sample 1: public void openJadFile(URL url) { try { setStatusBar("Loading..."); jad.clear(); jad.load(url.openStream()); loadFromJad(url); } catch (FileNotFoundException ex) { System.err.println("Cannot found " + url.getPath()); } catch (NullPointerException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IllegalArgumentException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } catch (IOException ex) { ex.printStackTrace(); System.err.println("Cannot open jad " + url.getPath()); } } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: @Test public void test_baseMaterialsForTypeID_StringInsteadOfID() throws Exception { URL url = new URL(baseUrl + "/baseMaterialsForTypeID/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); } Code Sample 2: public List<String> addLine(String username, String URL, int page) { List<String> rss = new ArrayList<String>(); try { URL url = new URL(URL + page); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; System.out.println(reader.readLine()); while ((line = reader.readLine()) != null) { String string = "<text>"; String string1 = "</text>"; if (line.contains(string) && !line.contains("@") && !line.contains("http")) { String tweet = line.replace(string, "").replace(string1, "").replace("'", "").trim(); final Tweets tweets = new Tweets(username, tweet, page, false); int save = tweets.save(); tweets.setId((long) save); Thread thread = new Thread(new Runnable() { @Override public void run() { Main.addRow(tweets); } }); thread.start(); System.out.println(tweet); } } reader.close(); } catch (MalformedURLException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (IOException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (Exception e) { Log.put(e.toString()); System.out.println(e.toString()); } return rss; }