label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); }
00
Code Sample 1: public byte[] computeMD5(String plainText) throws VHException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new VHException("The MD5 hash algorithm is not available.", ex); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw new VHException("The UTF-8 encoding is not supported.", ex); } return md.digest(); } Code Sample 2: public ArrayList parseFile(File newfile) throws IOException { String s; String firstname; String secondname; String direction; String header; String name = null; String[] tokens; boolean readingHArrays = false; boolean readingVArrays = false; boolean readingAArrays = false; ArrayList xturndat = new ArrayList(); ArrayList yturndat = new ArrayList(); ArrayList ampturndat = new ArrayList(); int nvalues; URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues < 1) continue; firstname = tokens[0]; secondname = tokens[1]; if (secondname.startsWith("BPM")) { if (readingHArrays) dumpxData(name, xturndat); else if (readingVArrays) dumpyData(name, yturndat); else if (readingAArrays) dumpampData(name, ampturndat); direction = tokens[4]; if (direction.equals("HORIZONTAL")) { readingHArrays = true; readingVArrays = false; readingAArrays = false; } if (direction.equals("VERTICAL")) { readingVArrays = true; readingHArrays = false; readingAArrays = false; } if (direction.equals("AMPLITUDE")) { readingVArrays = false; readingHArrays = false; readingAArrays = true; } name = tokens[3]; xturndat.clear(); yturndat.clear(); ampturndat.clear(); } if (secondname.startsWith("WAVEFORM")) continue; if (nvalues == 3) { if (readingHArrays) xturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingVArrays) yturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingAArrays) ampturndat.add(new Double(Double.parseDouble(tokens[2]))); } } dumpampData(name, ampturndat); data.add(xdatamap); data.add(ydatamap); data.add(ampdatamap); return data; }
00
Code Sample 1: private void transferFile(String fileName) throws SocketException, IOException, Exception { FTPClient client = new FTPClient(); client.connect(server.getExternalName(), server.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } client.login(server.getDefaultUserName(), server.getDefaultUserPassword()); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } InputStream stream = getClass().getClassLoader().getResourceAsStream("res/conf/ftpd.properties"); client.storeFile(fileName, stream); File transfferedFile = new File(server.getServerRootDirectory(), fileName); assertTrue(transfferedFile.exists()); assertTrue(transfferedFile.delete()); } Code Sample 2: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
00
Code Sample 1: private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; } Code Sample 2: private List<String> getSignatureResourceNames(URL url) throws IOException, ParserConfigurationException, SAXException, TransformerException, JAXBException { List<String> signatureResourceNames = new LinkedList<String>(); ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true); ZipArchiveEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if ("_rels/.rels".equals(zipEntry.getName())) { break; } } if (null == zipEntry) { LOG.debug("no _rels/.rels relationship part present"); return signatureResourceNames; } String dsOriginPart = null; JAXBElement<CTRelationships> packageRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); CTRelationships packageRelationships = packageRelationshipsElement.getValue(); List<CTRelationship> packageRelationshipList = packageRelationships.getRelationship(); for (CTRelationship packageRelationship : packageRelationshipList) { if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_ORIGIN_REL_TYPE.equals(packageRelationship.getType())) { dsOriginPart = packageRelationship.getTarget(); break; } } if (null == dsOriginPart) { LOG.debug("no Digital Signature Origin part present"); return signatureResourceNames; } LOG.debug("Digital Signature Origin part: " + dsOriginPart); String dsOriginName = dsOriginPart.substring(dsOriginPart.lastIndexOf("/") + 1); LOG.debug("Digital Signature Origin base: " + dsOriginName); String dsOriginSegment = dsOriginPart.substring(0, dsOriginPart.lastIndexOf("/")) + "/"; LOG.debug("Digital Signature Origin segment: " + dsOriginSegment); String dsOriginRels = dsOriginSegment + "_rels/" + dsOriginName + ".rels"; LOG.debug("Digital Signature Origin relationship part: " + dsOriginRels); if (dsOriginRels.startsWith("/")) { dsOriginRels = dsOriginRels.substring(1); } zipInputStream = new ZipArchiveInputStream(url.openStream(), "UTF8", true, true); while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (dsOriginRels.equals(zipEntry.getName())) { break; } } if (null == zipEntry) { LOG.debug("no Digital Signature Origin relationship part present"); return signatureResourceNames; } JAXBElement<CTRelationships> dsoRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); CTRelationships dsoRelationships = dsoRelationshipsElement.getValue(); List<CTRelationship> dsoRelationshipList = dsoRelationships.getRelationship(); for (CTRelationship dsoRelationship : dsoRelationshipList) { if (OOXMLSignatureVerifier.DIGITAL_SIGNATURE_REL_TYPE.equals(dsoRelationship.getType())) { String signatureResourceName; if (dsoRelationship.getTarget().startsWith("/")) { signatureResourceName = dsoRelationship.getTarget(); } else { signatureResourceName = dsOriginSegment + dsoRelationship.getTarget(); } if (signatureResourceName.startsWith("/")) { signatureResourceName = signatureResourceName.substring(1); } LOG.debug("signature resource name: " + signatureResourceName); signatureResourceNames.add(signatureResourceName); } } return signatureResourceNames; }
11
Code Sample 1: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); } Code Sample 2: public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
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 doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static final void newRead() { HTMLDocument html = new HTMLDocument(); html.putProperty("IgnoreCharsetDirective", new Boolean(true)); try { HTMLEditorKit kit = new HTMLEditorKit(); URL url = new URL("http://omega.rtu.lv/en/index.html"); kit.read(new BufferedReader(new InputStreamReader(url.openStream())), html, 0); Reader reader = new FileReader(html.getText(0, html.getLength())); List<String> links = HTMLUtils.extractLinks(reader); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } Code Sample 2: @edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String md5Encode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; }
00
Code Sample 1: public static int sendMessage(String auth_token, String registrationId, String message) throws IOException { StringBuilder postDataBuilder = new StringBuilder(); postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId); postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0"); postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, UTF8)); byte[] postData = postDataBuilder.toString().getBytes(UTF8); URL url = new URL(C2DM_SEND_ENDPOINT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(postData.length)); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token); OutputStream out = conn.getOutputStream(); out.write(postData); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpServletResponse.SC_UNAUTHORIZED || responseCode == HttpServletResponse.SC_FORBIDDEN) { AuthenticationUtil.getTokenFromServer(Util.USER, Util.PASSWORD); sendMessage(auth_token, registrationId, message); } String updatedAuthToken = conn.getHeaderField(UPDATE_CLIENT_AUTH); if (updatedAuthToken != null && !auth_token.equals(updatedAuthToken)) { Util.updateToken(updatedAuthToken); } return responseCode; } Code Sample 2: protected void writeGZippedBytes(byte array[], TupleOutput out) { if (array == null || array.length == 0) { out.writeBoolean(false); writeBytes(array, out); return; } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); GZIPOutputStream gzout = new GZIPOutputStream(baos); ByteArrayInputStream bais = new ByteArrayInputStream(array); IOUtils.copyTo(bais, gzout); gzout.finish(); gzout.close(); bais.close(); byte compressed[] = baos.toByteArray(); if (compressed.length < array.length) { out.writeBoolean(true); writeBytes(compressed, out); } else { out.writeBoolean(false); writeBytes(array, out); } } catch (IOException err) { throw new RuntimeException(err); } }
00
Code Sample 1: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
11
Code Sample 1: public static String 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 convertToHex(sha1hash); } Code Sample 2: private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } }
11
Code Sample 1: private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); } Code Sample 2: private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: @Override public DownloadObject download() throws IOException { final HttpGet findLink = new HttpGet(url.toString()); final HttpResponse response = this.client.execute(findLink); final String body = IOUtil.getString(response); LinkTag linkTag = null; try { linkTag = HtmlParserUtil.findLink(MegaUploadDownloader.DOWNLOAD_LINK_PATTERN, body); } catch (ParserException e) { } if (linkTag != null) { String link = linkTag.extractLink(); final String filename = IOUtil.getBaseName(link).trim(); link = link.replaceAll("&#[0-9]*;", "_"); final URL url = new URL(link); final String newLink = link.replaceAll(Pattern.quote(IOUtil.getBaseName(url.getPath())), URLEncoder.encode(IOUtil.getBaseName(url.getPath()), "UTF-8")); final HttpGet download = new HttpGet(newLink); final HttpResponse downloadResponse = this.client.execute(download); final HttpEntity downloadEntity = downloadResponse.getEntity(); final long filesize = downloadEntity.getContentLength(); return createObject(downloadEntity.getContent(), filename, filesize); } else { throw new RuntimeException("No download link."); } } Code Sample 2: public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } }
00
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
00
Code Sample 1: protected void loadResourceLocations() { try { for (String path : resourceLocations) { if (path.startsWith("${") && path.endsWith("}")) { int start = path.indexOf('{') + 1; int end = path.indexOf('}'); String key = path.substring(start, end).trim(); if (key.equals(ApplicationConstants.RESOURCE_SQL_LOCATION_PROP_NAME)) path = AdminHelper.getRepository().getURI("sql"); else path = AdminHelper.getRepository().getSetupApplicationProperties().get(key); log.debug(key + "=" + path); } FileObject fo = VFSUtils.resolveFile(path); if (fo.exists()) { URL url = fo.getURL(); url.openConnection(); if (fastDeploy) { if (log.isDebugEnabled()) { log.debug("Fast deploy : " + url); AdminSqlQueryFactory builder = null; for (DirectoryListener listener : scanner.getDirectoryListeners()) { if (listener instanceof AdminSqlQueryFactory) { builder = (AdminSqlQueryFactory) listener; } } File file = new File(url.getFile()); fastDeploy(file, builder); } } scanner.addScanURL(url); } } } catch (Exception e) { } } Code Sample 2: private static void discoverRegisteryEntries(DataSourceRegistry registry) { try { Enumeration<URL> urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } urls = DataSetURL.class.getClassLoader().getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine().trim(); while (s != null) { if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException { String filename = null; filename = file.getName(); ZipArchiveEntry zae = new ZipArchiveEntry(filename); zae.setSize(file.length()); zaos.putArchiveEntry(zae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, zaos); zaos.closeArchiveEntry(); } Code Sample 2: private static String sendGetRequest(String endpoint, String requestParameters) throws Exception { String result = null; if (endpoint.startsWith("http://")) { StringBuffer data = new StringBuffer(); String urlStr = prepareUrl(endpoint, requestParameters); URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } return result; }
11
Code Sample 1: public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void write(File file) throws Exception { if (getGEDCOMFile() != null) { size = getGEDCOMFile().length(); if (!getGEDCOMFile().renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(getGEDCOMFile())); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } Code Sample 2: public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
00
Code Sample 1: @Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } } Code Sample 2: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } }
11
Code Sample 1: @Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; } Code Sample 2: public boolean getFiles(String pRemoteDirectory, String pLocalDirectory) throws IOException { final String methodSignature = "boolean getFiles(String,String): "; FTPClient fc = new FTPClient(); fc.connect(getRemoteHost()); fc.login(getUserName(), getPassword()); fc.changeWorkingDirectory(pRemoteDirectory); FTPFile[] files = fc.listFiles(); boolean retrieved = false; logInfo("Listing Files: "); int retrieveCount = 0; File tmpFile = null; for (int i = 0; i < files.length; i++) { tmpFile = new File(files[i].getName()); if (!tmpFile.isDirectory()) { FileOutputStream fos = new FileOutputStream(pLocalDirectory + "/" + files[i].getName()); retrieved = fc.retrieveFile(files[i].getName(), fos); if (false == retrieved) { logInfo("Unable to retrieve file: " + files[i].getName()); } else { logInfo("Successfully retrieved file: " + files[i].getName()); retrieveCount++; } if (null != fos) { fos.flush(); fos.close(); } } } logInfo("Retrieve count: " + retrieveCount); if (retrieveCount > 0) { return true; } return false; }
11
Code Sample 1: public static String md5(String s) { try { MessageDigest digester = MessageDigest.getInstance("MD5"); digester.update(s.getBytes()); return new BigInteger(1, digester.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public static String GetMD5SUM(String s) throws NoSuchAlgorithmException { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes()); byte messageDigest[] = algorithm.digest(); String md5sum = Base64.encode(messageDigest); return md5sum; }
00
Code Sample 1: public static String MD5Encrypt(String OriginalString) { String encryptedString = new String(""); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(OriginalString.getBytes()); byte b[] = md.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; encryptedString += new String(ob); } } catch (NoSuchAlgorithmException nsae) { System.out.println("the algorithm doesn't exist"); } return encryptedString; } 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 proxyRequest(IPageContext context, Writer writer, String proxyPath) throws IOException { URLConnection connection = new URL(proxyPath).openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "text/html; charset=UTF-8"); connection.setReadTimeout(30000); connection.setConnectTimeout(5000); Enumeration<String> e = context.httpRequest().getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (name.equalsIgnoreCase("HOST") || name.equalsIgnoreCase("Accept-Encoding") || name.equalsIgnoreCase("Authorization")) continue; Enumeration<String> headers = context.httpRequest().getHeaders(name); while (headers.hasMoreElements()) { String header = headers.nextElement(); connection.setRequestProperty(name, header); } } if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(context.httpRequest().getMethod()); if ("POST".equalsIgnoreCase(context.httpRequest().getMethod()) || "PUT".equalsIgnoreCase(context.httpRequest().getMethod())) { Enumeration<String> names = context.httpRequest().getParameterNames(); StringBuilder body = new StringBuilder(); while (names.hasMoreElements()) { String key = names.nextElement(); for (String value : context.parameters(key)) { if (body.length() > 0) { body.append('&'); } try { body.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException ex) { } } } if (body.length() > 0) { connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(body.toString()); out.close(); } } } try { IOUtils.copy(connection.getInputStream(), writer); } catch (IOException ex) { writer.write("<span>SSI Error: " + ex.getMessage() + "</span>"); } } Code Sample 2: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); }
00
Code Sample 1: static void copyFile(File file, File file1) throws IOException { byte abyte0[] = new byte[512]; FileInputStream fileinputstream = new FileInputStream(file); FileOutputStream fileoutputstream = new FileOutputStream(file1); int i; while ((i = fileinputstream.read(abyte0)) > 0) fileoutputstream.write(abyte0, 0, i); fileinputstream.close(); fileoutputstream.close(); } Code Sample 2: private void processParameters() throws BadElementException, IOException { type = IMGTEMPLATE; originalType = ORIGINAL_WMF; InputStream is = null; try { String errorID; if (rawData == null) { is = url.openStream(); errorID = url.toString(); } else { is = new java.io.ByteArrayInputStream(rawData); errorID = "Byte array"; } InputMeta in = new InputMeta(is); if (in.readInt() != 0x9AC6CDD7) { throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.placeable.windows.metafile", errorID)); } in.readWord(); int left = in.readShort(); int top = in.readShort(); int right = in.readShort(); int bottom = in.readShort(); int inch = in.readWord(); dpiX = 72; dpiY = 72; scaledHeight = (float) (bottom - top) / inch * 72f; setTop(scaledHeight); scaledWidth = (float) (right - left) / inch * 72f; setRight(scaledWidth); } finally { if (is != null) { is.close(); } plainWidth = getWidth(); plainHeight = getHeight(); } }
00
Code Sample 1: public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request); if (request.getParameter("_debug_") != null) { StringBuffer buffer = new StringBuffer(); Enumeration iter = request.getHeaderNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); buffer.append(name + "=" + request.getHeader(name)).append("\n"); } buffer.append("\n"); iter = request.getParameterNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); String value = request.getParameter(name); if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset()); buffer.append(name).append("=").append(value).append("\n"); } response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(buffer.toString()); return null; } Object resultObj = handleRequest(request); if (resultObj == null) { String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception"); if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0); } else { if (resultObj instanceof DataHandler) { response.setContentType(((DataHandler) resultObj).getContentType()); response.setContentLength(((DataHandler) resultObj).getInputStream().available()); IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream()); } else { String temp = resultObj.toString(); if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset()); byte[] buffer = temp.getBytes(clientInfo.getPreferCharset()); response.setContentLength(buffer.length); response.getOutputStream().write(buffer); } } return null; } Code Sample 2: private void sortWhats(String[] labels, int[] whats, String simplifyString) { int n = whats.length; boolean swapped; do { swapped = false; for (int i = 0; i < n - 1; i++) { int i0_pos = simplifyString.indexOf(labels[whats[i]]); int i1_pos = simplifyString.indexOf(labels[whats[i + 1]]); if (i0_pos > i1_pos) { int temp = whats[i]; whats[i] = whats[i + 1]; whats[i + 1] = temp; swapped = true; } } } while (swapped); }
00
Code Sample 1: public boolean consolidateCrossrefGet(BiblioItem bib, ArrayList<BiblioItem> bib2) throws Exception { boolean result = false; String doi = bib.getDOI(); String aut = bib.getFirstAuthorSurname(); String title = bib.getTitle(); String firstPage = null; String pageRange = bib.getPageRange(); int beginPage = bib.getBeginPage(); if (beginPage != -1) { firstPage = "" + beginPage; } else if (pageRange != null) { StringTokenizer st = new StringTokenizer(pageRange, "--"); if (st.countTokens() == 2) { firstPage = st.nextToken(); } else if (st.countTokens() == 1) firstPage = pageRange; } if (aut != null) { aut = TextUtilities.removeAccents(aut); } if (title != null) { title = TextUtilities.removeAccents(title); } if (doi != null) { if (doi.startsWith("doi:") | doi.startsWith("DOI:")) { doi.substring(4, doi.length()); doi = doi.trim(); } doi = doi.replace(" ", ""); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL3); pstmt.setString(1, doi); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); se.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(DOI_BASE_QUERY, crossref_id, crossref_pw, doi); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { e2.printStackTrace(); urlConn = null; } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL3); pstmt2.setString(1, doi); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((title != null) & (aut != null)) { String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL); pstmt.setString(1, aut); pstmt.setString(2, title); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); se.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(TITLE_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(title), URLEncoder.encode(aut)); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { e2.printStackTrace(); urlConn = null; } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL); pstmt2.setString(1, aut); pstmt2.setString(2, bib.getTitle()); pstmt2.setString(3, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((firstPage != null) & (bib.getJournal() != null) & (bib.getVolume() != null)) { String subpath = String.format(JOURNAL_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(bib.getJournal()), URLEncoder.encode(bib.getVolume()), firstPage); URL url = new URL("http://" + crossref_host + "/" + subpath); String urlmsg = url.toString(); System.out.println(urlmsg); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL2); pstmt.setString(1, urlmsg); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); se.printStackTrace(); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { System.out.println("Sending: " + urlmsg); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { e2.printStackTrace(); urlConn = null; } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser p = spf.newSAXParser(); p.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } in.close(); urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL2); pstmt2.setString(1, urlmsg); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } return result; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
00
Code Sample 1: @Override public void loadData() { try { String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv"; URLConnection conn = (new URL(url)).openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); String str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double open = Double.parseDouble(split[1]); final double high = Double.parseDouble(split[2]); final double low = Double.parseDouble(split[3]); final double close = Double.parseDouble(split[4]); final int volume = Integer.parseInt(split[5]); final double adjClose = Double.parseDouble(split[6]); final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose); historicalPrices.add(price); } in.close(); url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv"; conn = (new URL(url)).openConnection(); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double amount = Double.parseDouble(split[1]); final Dividend dividend = new Dividend(date, amount); dividends.add(dividend); } in.close(); } catch (final IOException ioe) { logger.error("Error parsing historical prices for " + getSymbol(), ioe); } } Code Sample 2: public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
00
Code Sample 1: public void bindDownload(Download download) throws BindingException { List<ChunkDownload> chunks = download.getChunks(); File destination = download.getFile(); FileOutputStream fos = null; try { fos = FileUtils.openOutputStream(destination); for (ChunkDownload chunk : chunks) { String filePath = chunk.getChunkFilePath(); InputStream ins = null; try { File chunkFile = new File(filePath); ins = FileUtils.openInputStream(chunkFile); IOUtils.copy(ins, fos); chunkFile.delete(); } catch (IOException e) { e.printStackTrace(); } finally { ins.close(); } } download.getWorkDir().delete(); download.complete(); } catch (IOException e) { logger.error("IO Exception while copying the chunk " + e.getMessage(), e); e.printStackTrace(); throw new BindingException("IO Exception while copying the chunk " + e.getMessage(), e); } finally { try { fos.close(); } catch (IOException e) { logger.error("IO Exception while copying closing stream of the target file " + e.getMessage(), e); e.printStackTrace(); throw new BindingException("IO Exception while copying closing stream of the target file " + e.getMessage(), e); } } } Code Sample 2: public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } } Code Sample 2: public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException ex) { return password; } }
00
Code Sample 1: static boolean writeProperties(Map<String, String> customProps, File destination) throws IOException { synchronized (PropertiesIO.class) { L.info(Msg.msg("PropertiesIO.writeProperties.start")); File tempFile = null; BufferedInputStream existingCfgInStream = null; FileInputStream in = null; FileOutputStream out = null; PrintStream ps = null; FileChannel fromChannel = null, toChannel = null; String line = null; try { existingCfgInStream = new BufferedInputStream(destination.exists() ? new FileInputStream(destination) : defaultPropertiesStream()); tempFile = File.createTempFile("properties-", ".tmp", null); ps = new PrintStream(tempFile); while ((line = Utils.readLine(existingCfgInStream)) != null) { String lineReady2write = setupLine(line, customProps); ps.println(lineReady2write); } destination.getParentFile().mkdirs(); in = new FileInputStream(tempFile); out = new FileOutputStream(destination, false); fromChannel = in.getChannel(); toChannel = out.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); L.info(Msg.msg("PropertiesIO.writeProperties.done").replace("#file#", destination.getAbsolutePath())); return true; } finally { if (existingCfgInStream != null) existingCfgInStream.close(); if (ps != null) ps.close(); if (fromChannel != null) fromChannel.close(); if (toChannel != null) toChannel.close(); if (out != null) out.close(); if (in != null) in.close(); if (tempFile != null && tempFile.exists()) tempFile.delete(); } } } Code Sample 2: private void doDissemTest(String what, boolean redirectOK) throws Exception { final int num = 30; System.out.println("Getting " + what + " " + num + " times..."); int i = 0; try { URL url = new URL(BASE_URL + "/get/" + what); for (i = 0; i < num; i++) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); in.read(); in.close(); conn.disconnect(); } } catch (Exception e) { fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage()); } }
11
Code Sample 1: @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } } Code Sample 2: public static void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } } Code Sample 2: public static void main(String[] args) { try { { byte[] bytes1 = { (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; byte[] bytes2 = { (byte) 99, (byte) 2, (byte) 2, (byte) 3, (byte) 0, (byte) 9 }; System.out.println("Bytes 2,2,3,0,9 as Base64: " + encodeBytes(bytes1)); System.out.println("Bytes 2,2,3,0,9 w/ offset: " + encodeBytes(bytes2, 1, bytes2.length - 1)); byte[] dbytes = decode(encodeBytes(bytes1)); System.out.print(encodeBytes(bytes1) + " decoded: "); for (int i = 0; i < dbytes.length; i++) System.out.print(dbytes[i] + (i < dbytes.length - 1 ? "," : "\n")); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif.b64"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); byte[] bytes = new byte[0]; int b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[bytes.length + 1]; System.arraycopy(bytes, 0, temp, 0, bytes.length); temp[bytes.length] = (byte) b; bytes = temp; } b64is.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon(bytes); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif.b64", iicon, 0); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif_out"); fos.write(bytes); fos.close(); fis = new java.io.FileInputStream("test.gif_out"); b64is = new Base64.InputStream(fis, ENCODE); byte[] ebytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[ebytes.length + 1]; System.arraycopy(ebytes, 0, temp, 0, ebytes.length); temp[ebytes.length] = (byte) b; ebytes = temp; } b64is.close(); String s = new String(ebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif_out"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.show(); fos = new java.io.FileOutputStream("test.gif.b64_out"); fos.write(ebytes); fis = new java.io.FileInputStream("test.gif.b64_out"); b64is = new Base64.InputStream(fis, DECODE); byte[] edbytes = new byte[0]; b = -1; while ((b = b64is.read()) >= 0) { byte[] temp = new byte[edbytes.length + 1]; System.arraycopy(edbytes, 0, temp, 0, edbytes.length); temp[edbytes.length] = (byte) b; edbytes = temp; } b64is.close(); iicon = new javax.swing.ImageIcon(edbytes); jlabel = new javax.swing.JLabel("Read from test.gif.b64_out", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); } { java.io.FileInputStream fis = new java.io.FileInputStream("test.gif_out"); byte[] rbytes = new byte[0]; int b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rbytes.length + 1]; System.arraycopy(rbytes, 0, temp, 0, rbytes.length); temp[rbytes.length] = (byte) b; rbytes = temp; } fis.close(); java.io.FileOutputStream fos = new java.io.FileOutputStream("test.gif.b64_out2"); Base64.OutputStream b64os = new Base64.OutputStream(fos, ENCODE); b64os.write(rbytes); b64os.close(); fis = new java.io.FileInputStream("test.gif.b64_out2"); byte[] rebytes = new byte[0]; b = -1; while ((b = fis.read()) >= 0) { byte[] temp = new byte[rebytes.length + 1]; System.arraycopy(rebytes, 0, temp, 0, rebytes.length); temp[rebytes.length] = (byte) b; rebytes = temp; } fis.close(); String s = new String(rebytes); javax.swing.JTextArea jta = new javax.swing.JTextArea(s); javax.swing.JScrollPane jsp = new javax.swing.JScrollPane(jta); javax.swing.JFrame jframe = new javax.swing.JFrame(); jframe.setTitle("Read from test.gif.b64_out2"); jframe.getContentPane().add(jsp); jframe.pack(); jframe.show(); fos = new java.io.FileOutputStream("test.gif_out2"); b64os = new Base64.OutputStream(fos, DECODE); b64os.write(rebytes); b64os.close(); javax.swing.ImageIcon iicon = new javax.swing.ImageIcon("test.gif_out2"); javax.swing.JLabel jlabel = new javax.swing.JLabel("Read from test.gif_out2", iicon, 0); jframe = new javax.swing.JFrame(); jframe.getContentPane().add(jlabel); jframe.pack(); jframe.show(); } { java.io.FileInputStream fis = new java.io.FileInputStream("D:\\temp\\testencoding.txt"); Base64.InputStream b64is = new Base64.InputStream(fis, DECODE); java.io.FileOutputStream fos = new java.io.FileOutputStream("D:\\temp\\file.zip"); int b; while ((b = b64is.read()) >= 0) fos.write(b); fos.close(); b64is.close(); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } } Code Sample 2: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static String getDigest(String user, String realm, String password, String method, String uri, String nonce, String nc, String cnonce, String qop) { String digest1 = user + ":" + realm + ":" + password; String digest2 = method + ":" + uri; try { MessageDigest digestOne = MessageDigest.getInstance("md5"); digestOne.update(digest1.getBytes()); String hexDigestOne = getHexString(digestOne.digest()); MessageDigest digestTwo = MessageDigest.getInstance("md5"); digestTwo.update(digest2.getBytes()); String hexDigestTwo = getHexString(digestTwo.digest()); String digest3 = hexDigestOne + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hexDigestTwo; MessageDigest digestThree = MessageDigest.getInstance("md5"); digestThree.update(digest3.getBytes()); String hexDigestThree = getHexString(digestThree.digest()); return hexDigestThree; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
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: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void reconfigureDebug() { useFile = false; logValue = 0; String methodString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.method']/@value"); String levelString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.level']/@value"); String quietString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.quiet']/@value"); String fileString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.file']/@value"); String filemodeString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.filemode']/@value"); String calltraceString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.calltrace']/@value"); String rotateTimeoutString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatetimeout']/@value"); String rotateDestString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedest']/@value"); String rotateCompressString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatecompress']/@value"); String rotateDaysString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedays']/@value"); String rotateArchiveString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatearchive']/@value"); String rotateDeleteString = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.debug']/property[@type='engine.rotatedelete']/@value"); String dirName = "."; if (rotateTimeoutString != null) { rotateTimeout = Integer.parseInt(rotateTimeoutString); } if (rotateDestString != null) { rotateDest = rotateDestString; } if (rotateCompressString != null && rotateCompressString.equalsIgnoreCase("true")) { rotateCompress = true; } if (rotateDaysString != null) { rotateDays = Integer.parseInt(rotateDaysString); } if (rotateArchiveString != null) { rotateArchive = rotateArchiveString; } if (rotateDeleteString != null && rotateDeleteString.equalsIgnoreCase("true")) { rotateDelete = true; } if (fileString != null && fileString.indexOf("/") != -1) { dirName = fileString.substring(0, fileString.lastIndexOf("/")); (new File(dirName)).mkdirs(); } if (methodString != null) { logMethod = methodString; } else { logMethod = "file"; } if (levelString != null) { logValue = Integer.parseInt(levelString); } else { logValue = 0; } if (calltraceString != null && calltraceString.equalsIgnoreCase("true")) { calltrace = true; } else { calltrace = false; } if (logMethod == null) { logMethod = "file"; } if (quietString != null) { if (quietString.equalsIgnoreCase("true")) { beQuiet = true; } } if (logMethod != null) { if (logMethod.equalsIgnoreCase("file")) { if (fileString != null) { logFile = fileString; } else { logFile = "log.txt"; } useFile = true; } } else { System.err.println("*** A debugging method (debug.method) is required in properties file!"); System.err.println("*** Please refer to configuration documentation."); System.exit(-1); } timesRepeated = 0; lastMessage = null; if (useFile) { logfile = new File(logFile); try { if (filemodeString != null && filemodeString.equalsIgnoreCase("append")) { ps = new PrintStream(new FileOutputStream(logfile, true)); } else { ps = new PrintStream(new FileOutputStream(logfile)); } isFile = true; Calendar calendar = new GregorianCalendar(); Date date = calendar.getTime(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); ps.println(); ps.println("--- Log file opened " + format1.format(date) + " ---"); } catch (FileNotFoundException e) { System.out.println("Debug: Unable to instantiate debugger: " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.out.println("Debug: Unable to instantiate debugger - internal error: " + e.getMessage()); System.exit(-1); } } if (!registeredSchedule) { registeredSchedule = true; if (Server.getScheduler() != null) { Server.getScheduler().register("Log File Rotator for '" + logFile + "'", new SchedulerInterface() { public int getScheduleRate() { if (rotateTimeout != 0) { return rotateTimeout / 10; } return 0; } public void handle() { FileChannel srcChannel, destChannel; String destOutFile = logFile + "." + System.currentTimeMillis(); String destOutFileCompressed = logFile + "." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(logFile); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate log file '" + logFile + "': " + e); } } else { try { srcChannel = new FileInputStream(logFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to read log file '" + logFile + "': " + e.getMessage()); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate log file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated log file '" + logFile + "' to '" + destOutFile + "'"); } if (rotateDelete && isFile) { try { ps.close(); } catch (Exception e) { } isFile = false; ps = null; (new File(logFile)).delete(); reconfigureDebug(); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(logFile + ".") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } } public String identString() { return "Debug Rotator for logs"; } }); } } }
00
Code Sample 1: public void sort(int[] mas) { int temp; boolean t = true; while (t) { t = false; for (int i = 0; i < mas.length - 1; i++) { if (mas[i] > mas[i + 1]) { temp = mas[i]; mas[i] = mas[i + 1]; mas[i + 1] = temp; t = true; } } } } Code Sample 2: private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
00
Code Sample 1: private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } } Code Sample 2: private void menuOpenURL() { animate = false; resetScaleCombos(); InputDialog dialog = new InputDialog(shell, "Open URL Dialog", "Enter URL of the image", "http://", new IInputValidator() { @Override public String isValid(String newText) { if (newText.startsWith("http://") || newText.startsWith("https://") || newText.startsWith("ftp://") || newText.startsWith("file://")) return newText; return null; } }); if (dialog.open() == SWT.CANCEL) return; String urlName = dialog.getValue(); Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT); shell.setCursor(waitCursor); imageCanvas.setCursor(waitCursor); try { URL url = new URL(urlName); InputStream stream = url.openStream(); loader = new ImageLoader(); if (incremental) { loader.addImageLoaderListener(new ImageLoaderListener() { public void imageDataLoaded(ImageLoaderEvent event) { incrementalDataLoaded(event); } }); incrementalThreadStart(); } imageDataArray = loader.load(stream); stream.close(); if (imageDataArray.length > 0) { currentName = urlName; fileName = null; previousButton.setEnabled(imageDataArray.length > 1); nextButton.setEnabled(imageDataArray.length > 1); animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0); imageDataIndex = 0; displayImage(imageDataArray[imageDataIndex]); resetScrollBars(); } } catch (Exception e) { showErrorDialog("Loading", urlName, e); } finally { shell.setCursor(null); imageCanvas.setCursor(crossCursor); waitCursor.dispose(); } }
11
Code Sample 1: public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } 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: public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); } Code Sample 2: public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } }
11
Code Sample 1: public static void copy(File from, File to) { if (from.getAbsolutePath().equals(to.getAbsolutePath())) { return; } FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(from); os = new FileOutputStream(to); int read = -1; byte[] buffer = new byte[10000]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } catch (Exception e) { throw new RuntimeException(); } finally { try { is.close(); } catch (Exception e) { } try { os.close(); } catch (Exception e) { } } } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: private void SaveLoginInfo() { int iSize; try { if (m_bSavePwd) { byte[] MD5PWD = new byte[80]; java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal"; java.io.File file = new java.io.File(szPath); if (!file.exists()) file.mkdirs(); file = new java.io.File(file, "user.dat"); if (!file.exists()) file.createNewFile(); java.io.FileOutputStream pw = new java.io.FileOutputStream(file); iSize = m_PwdList.size(); for (int iIndex = 0; iIndex < iSize; iIndex++) { md.reset(); md.update(((String) m_UsrList.get(iIndex)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i = 0; i < DESUSR.length; i++) alpha += DESUSR[i]; String pwd = (String) m_PwdList.get(iIndex); if (pwd.length() > 0) { java.util.Arrays.fill(MD5PWD, (byte) 0); int iLen = pwd.length(); pw.write(iLen); for (int i = 0; i < iLen; i++) { int iDiff = (int) pwd.charAt(i) + (int) alpha; int c = iDiff % 256; MD5PWD[i] = (byte) c; pw.write((byte) c); } } else pw.write(0); } pw.flush(); } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } } Code Sample 2: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); data = Data.valueOf(md.digest()); try { response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); setID(response.getWord()); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
00
Code Sample 1: @Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: public static boolean loadTestProperties(Properties props, Class<?> callingClazz, Class<?> hierarchyRootClazz, String resourceBaseName) { if (!hierarchyRootClazz.isAssignableFrom(callingClazz)) { throw new IllegalArgumentException("Class " + callingClazz + " is not derived from " + hierarchyRootClazz); } if (null == resourceBaseName) { throw new NullPointerException("resourceBaseName is null"); } String fqcn = callingClazz.getName(); String uqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1); String callingClassResource = uqcn + ".properties"; String globalCallingClassResource = "/" + callingClassResource; String baseClassResource = resourceBaseName + "-" + uqcn + ".properties"; String globalBaseClassResource = "/" + baseClassResource; String pkgResource = resourceBaseName + ".properties"; String globalResource = "/" + pkgResource; boolean loaded = false; final String[] resources = { baseClassResource, globalBaseClassResource, callingClassResource, globalCallingClassResource, pkgResource, globalResource }; List<URL> urls = new ArrayList<URL>(); Class<?> clazz = callingClazz; do { for (String res : resources) { URL url = clazz.getResource(res); if (null != url && !urls.contains(url)) { urls.add(url); } } if (hierarchyRootClazz.equals(clazz)) { clazz = null; } else { clazz = clazz.getSuperclass(); } } while (null != clazz); ListIterator<URL> it = urls.listIterator(urls.size()); while (it.hasPrevious()) { URL url = it.previous(); InputStream in = null; try { LOG.info("Loading test properties from resource: " + url); in = url.openStream(); props.load(in); loaded = true; } catch (IOException ex) { LOG.warn("Failed to load properties from resource: " + url, ex); } IOUtil.closeSilently(in); } return loaded; } Code Sample 2: public MapInfo getMap(double latitude, double longitude, double wanted_mapblast_scale, int image_width, int image_height, String file_path_wo_extension, ProgressListener progress_listener) throws IOException { try { if (web_request_ == null) { web_request_ = new HttpRequester(HOST_NAME); } int zoom_index = getZoomLevelIndex(wanted_mapblast_scale); int google_zoom_level = GOOGLE_ZOOM_LEVELS[zoom_index]; double mapblast_scale = POSSIBLE_GOOGLE_SCALES[zoom_index]; Tile tile = new Tile(latitude, longitude, google_zoom_level); SimplePoint coords = tile.getTileLatLong(); SimplePoint google_xy = tile.getTileCoord(); MapInfo map_info = new MapInfo(); map_info.setLatitude(coords.getX()); map_info.setLongitude(coords.getY()); map_info.setScale((float) mapblast_scale); map_info.setWidth(256); map_info.setHeight(256); map_info.setFilename(file_path_wo_extension + "png"); Object[] params = new Object[] { new Integer(google_xy.getX()), new Integer(google_xy.getY()), new Integer(google_zoom_level) }; MessageFormat message_format = new MessageFormat(GOOGLE_MAPS_URL, Locale.US); String url_string = message_format.format(params); URL url = new URL(url_string); if (Debug.DEBUG) Debug.println("map_download", "loading map from url: " + url); URLConnection connection = url.openConnection(); if (resources_.getBoolean(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USE)) { String proxy_userid = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_USERNAME); String proxy_password = resources_.getString(GpsylonKeyConstants.KEY_HTTP_PROXY_AUTHENTICATION_PASSWORD); String auth_string = proxy_userid + ":" + proxy_password; auth_string = "Basic " + new sun.misc.BASE64Encoder().encode(auth_string.getBytes()); connection.setRequestProperty("Proxy-Authorization", auth_string); } connection.connect(); String mime_type = connection.getContentType().toLowerCase(); if (!mime_type.startsWith("image")) { if (mime_type.startsWith("text")) { HTMLViewerFrame viewer = new HTMLViewerFrame(url); viewer.setSize(640, 480); viewer.setTitle("ERROR on loading url: " + url); viewer.setVisible(true); throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type + "\nPage is displayed in HTML frame."); } throw new IOException("Invalid mime type (expected 'image/*'): received " + mime_type); } int content_length = connection.getContentLength(); if (content_length < 0) progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, Integer.MIN_VALUE); else progress_listener.actionStart(PROGRESS_LISTENER_ID, 0, content_length); String extension = mime_type.substring(mime_type.indexOf('/') + 1); String filename = file_path_wo_extension + extension; FileOutputStream out = new FileOutputStream(filename); byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE); int sum_bytes = 0; int num_bytes = 0; while ((num_bytes = in.read(buffer)) != -1) { out.write(buffer, 0, num_bytes); sum_bytes += num_bytes; progress_listener.actionProgress(PROGRESS_LISTENER_ID, sum_bytes); } progress_listener.actionEnd(PROGRESS_LISTENER_ID); in.close(); out.close(); return (map_info); } catch (NoRouteToHostException nrhe) { nrhe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = nrhe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_NO_ROUTE_TO_HOST_MESSAGE); throw new IOException(message); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); progress_listener.actionEnd(PROGRESS_LISTENER_ID); String message = fnfe.getMessage() + ":\n" + resources_.getString(DownloadMouseModeLayer.KEY_LOCALIZE_MESSAGE_DOWNLOAD_ERROR_FILE_NOT_FOUND_MESSAGE); throw new IOException(message); } catch (Exception e) { progress_listener.actionEnd(PROGRESS_LISTENER_ID); e.printStackTrace(); String message = e.getMessage(); if (message == null) { Throwable cause = e.getCause(); if (cause != null) message = cause.getMessage(); } throw new IOException(message); } }
00
Code Sample 1: protected URLConnection openConnection(URL url) throws IOException { if (url == null) return null; if (!url.getProtocol().equals("nntp")) return null; if (m_connection != null) { if (m_connection.getURL().getHost().equals(url.getHost()) && (m_connection.getURL().getPort() == url.getPort()) && (m_connection.getURL().getUserInfo().equals(url.getUserInfo()))) { return m_connection; } } m_connection = new NNTPConnection(url); return m_connection; } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
11
Code Sample 1: public static String encodeMD5(String value) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); BASE64Encoder encoder = new BASE64Encoder(); md.update(value.getBytes()); byte[] raw = md.digest(); result = encoder.encode(raw); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } Code Sample 2: public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:plindenbaum@yahoo.fr\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&amp;cmd=Search&amp;itool=pubmed_Abstract&amp;term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=pubmed&amp;dopt=Abstract&amp;list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); }
11
Code Sample 1: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public String Hash(String plain) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes(), 0, plain.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (Exception ex) { Log.serverlogger.warn("No such Hash algorithm", ex); return ""; } } Code Sample 2: @Override public InputStream getInputStream() { String url = resourceURL_; try { return new URL(url).openStream(); } catch (Exception e) { } try { return new FileInputStream("/" + url); } catch (Exception e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } 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 boolean doPost(String urlString, Map<String, String> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setDoOutput(true); PrintWriter out = new PrintWriter(conn.getOutputStream()); boolean first = true; for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey(); String value = pair.getValue(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, "UTF-8")); } out.close(); Scanner in; StringBuilder response = new StringBuilder(); try { in = new Scanner(conn.getInputStream()); } catch (IOException ex) { if (!(conn instanceof HttpURLConnection)) throw ex; InputStream err = ((HttpURLConnection) conn).getErrorStream(); in = new Scanner(err); } while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } in.close(); return true; }
11
Code Sample 1: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private void process(String zipFileName, String directory, String db) throws SQLException { InputStream in = null; try { if (!FileUtils.exists(zipFileName)) { throw new IOException("File not found: " + zipFileName); } String originalDbName = null; int originalDbLen = 0; if (db != null) { originalDbName = getOriginalDbName(zipFileName, db); if (originalDbName == null) { throw new IOException("No database named " + db + " found"); } if (originalDbName.startsWith(File.separator)) { originalDbName = originalDbName.substring(1); } originalDbLen = originalDbName.length(); } in = FileUtils.openFileInputStream(zipFileName); ZipInputStream zipIn = new ZipInputStream(in); while (true) { ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { break; } String fileName = entry.getName(); fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); if (fileName.startsWith(File.separator)) { fileName = fileName.substring(1); } boolean copy = false; if (db == null) { copy = true; } else if (fileName.startsWith(originalDbName + ".")) { fileName = db + fileName.substring(originalDbLen); copy = true; } if (copy) { OutputStream out = null; try { out = FileUtils.openFileOutputStream(directory + File.separator + fileName, false); IOUtils.copy(zipIn, out); out.close(); } finally { IOUtils.closeSilently(out); } } zipIn.closeEntry(); } zipIn.closeEntry(); zipIn.close(); } catch (IOException e) { throw Message.convertIOException(e, zipFileName); } finally { IOUtils.closeSilently(in); } }
11
Code Sample 1: public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } } Code Sample 2: private static boolean prepareProbeFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "probe.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
00
Code Sample 1: public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { if (baseName == null || locale == null || format == null || loader == null) throw new NullPointerException(); ResourceBundle bundle = null; if (format.equals("user")) { String bundleName = toBundleName(baseName, locale); String resourceName = "file://" + config.getString(HOME) + "/" + bundleName + ".properties"; InputStream stream = null; try { URL url = new URL(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { if (reload) { connection.setUseCaches(false); } stream = connection.getInputStream(); } } } catch (Throwable t) { } if (stream != null) { BufferedInputStream bis = new BufferedInputStream(stream); bundle = new UserResourceBundle(UTF8ClassLoader.readUTFStreamToEscapedASCII(bis), super.newBundle(baseName, locale, "java.properties", loader, reload)); bis.close(); } else { return super.newBundle(baseName, locale, "java.properties", loader, reload); } } return bundle; } Code Sample 2: public InputStream retrieveStream(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; }
11
Code Sample 1: private static final void addFile(ZipArchiveOutputStream os, File file, String prefix) throws IOException { ArchiveEntry entry = os.createArchiveEntry(file, file.getAbsolutePath().substring(prefix.length() + 1)); os.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, os); fis.close(); os.closeArchiveEntry(); } Code Sample 2: public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
00
Code Sample 1: public GEItem lookup(final String itemName) { try { URL url = new URL(GrandExchange.HOST + "/m=itemdb_rs/results.ws?query=" + itemName + "&price=all&members="); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; while ((input = br.readLine()) != null) { if (input.contains("<div id=\"search_results_text\">")) { input = br.readLine(); if (input.contains("Your search for")) { return null; } } else if (input.startsWith("<td><img src=")) { Matcher matcher = GrandExchange.PATTERN.matcher(input); if (matcher.find()) { if (matcher.group(2).contains(itemName)) { return lookup(Integer.parseInt(matcher.group(1))); } } } } } catch (IOException ignored) { } return null; } Code Sample 2: private Source getStylesheetSource(String stylesheetResource) throws ApplicationContextException { if (LOG.isDebugEnabled()) { LOG.debug("Loading XSLT stylesheet from " + stylesheetResource); } try { URL url = this.getClass().getClassLoader().getResource(stylesheetResource); String urlPath = url.toString(); String systemId = urlPath.substring(0, urlPath.lastIndexOf('/') + 1); return new StreamSource(url.openStream(), systemId); } catch (IOException e) { throw new RuntimeException("Can't load XSLT stylesheet from " + stylesheetResource, e); } }
00
Code Sample 1: protected boolean checkResource(final String resourceName) { boolean isValid = true; HttpURLConnection.setFollowRedirects(false); try { final URL url = new URL(buildUrl(new Resource(resourceName).getName())); logger.debug("check url: " + url.toString()); final HttpURLConnection headConnection = (HttpURLConnection) url.openConnection(); addHeaders(headConnection); headConnection.setRequestMethod("HEAD"); headConnection.setDoOutput(true); int statusCode = headConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_PERM) { isValid = false; logger.debug("responseCode: " + statusCode); } else { logger.debug("responseCode: " + statusCode); } } catch (MalformedURLException e) { logger.error(e.toString()); isValid = false; } catch (ProtocolException e) { logger.error(e.toString()); isValid = false; } catch (IOException e) { logger.error(e.toString()); isValid = false; } HttpURLConnection.setFollowRedirects(true); return isValid; } Code Sample 2: public static void track(String strUserName, String strShortDescription, String strLongDescription, String strPriority, String strComponent) { String strFromToken = ""; try { URL url = new URL(getTracUrl() + "newticket"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String buffer = reader.readLine(); while (buffer != null) { if (buffer.contains("__FORM_TOKEN")) { Pattern pattern = Pattern.compile("value=\"[^\"]*\""); Matcher matcher = pattern.matcher(buffer); int start = 0; matcher.find(start); int von = matcher.start() + 7; int bis = matcher.end() - 1; strFromToken = buffer.substring(von, bis); } buffer = reader.readLine(); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(getTracUrl() + "newticket"); method.setRequestHeader("Cookie", "trac_form_token=" + strFromToken); method.addParameter("__FORM_TOKEN", strFromToken); method.addParameter("reporter", strUserName); method.addParameter("summary", strShortDescription); method.addParameter("type", "Fehler"); method.addParameter("description", strLongDescription); method.addParameter("action", "create"); method.addParameter("status", "new"); method.addParameter("priority", strPriority); method.addParameter("milestone", ""); method.addParameter("component", strComponent); method.addParameter("keywords", "BugReporter"); method.addParameter("cc", ""); method.addParameter("version", ""); client.executeMethod(method); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } }
11
Code Sample 1: public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); } Code Sample 2: public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
11
Code Sample 1: private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); } Code Sample 2: @SuppressWarnings("unchecked") private void doService(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String url = request.getRequestURL().toString(); if (url.endsWith("/favicon.ico")) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (url.contains("/delay")) { final String delay = StringUtils.substringBetween(url, "/delay", "/"); final int ms = Integer.parseInt(delay); if (LOG.isDebugEnabled()) { LOG.debug("Sleeping for " + ms + " before to deliver " + url); } Thread.sleep(ms); } final URL requestedUrl = new URL(url); final WebRequest webRequest = new WebRequest(requestedUrl); webRequest.setHttpMethod(HttpMethod.valueOf(request.getMethod())); for (final Enumeration<String> en = request.getHeaderNames(); en.hasMoreElements(); ) { final String headerName = en.nextElement(); final String headerValue = request.getHeader(headerName); webRequest.setAdditionalHeader(headerName, headerValue); } final List<NameValuePair> requestParameters = new ArrayList<NameValuePair>(); for (final Enumeration<String> paramNames = request.getParameterNames(); paramNames.hasMoreElements(); ) { final String name = paramNames.nextElement(); final String[] values = request.getParameterValues(name); for (final String value : values) { requestParameters.add(new NameValuePair(name, value)); } } if ("PUT".equals(request.getMethod()) && request.getContentLength() > 0) { final byte[] buffer = new byte[request.getContentLength()]; request.getInputStream().readLine(buffer, 0, buffer.length); webRequest.setRequestBody(new String(buffer)); } else { webRequest.setRequestParameters(requestParameters); } final WebResponse resp = MockConnection_.getResponse(webRequest); response.setStatus(resp.getStatusCode()); for (final NameValuePair responseHeader : resp.getResponseHeaders()) { response.addHeader(responseHeader.getName(), responseHeader.getValue()); } if (WriteContentAsBytes_) { IOUtils.copy(resp.getContentAsStream(), response.getOutputStream()); } else { final String newContent = getModifiedContent(resp.getContentAsString()); final String contentCharset = resp.getContentCharset(); response.setCharacterEncoding(contentCharset); response.getWriter().print(newContent); } response.flushBuffer(); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
00
Code Sample 1: public HashSet<String> queryResource(String resourceName, String propertyName) { if (resourceName.startsWith("http://dbpedia.org/resource/")) { resourceName = resourceName.substring(28); } try { resourceName = resourceName.trim().replace(' ', '_'); resourceName = URLEncoder.encode(resourceName, "UTF-8"); } catch (UnsupportedEncodingException exc) { } String select = prefix + " SELECT ?hasValue WHERE { { " + "<http://dbpedia.org/resource/" + resourceName + "> " + propertyName + " ?hasValue } FILTER (lang(?hasValue) = \"" + lang + "\" || !isLiteral(?hasValue))}"; System.out.println(select); HashSet<String> values = new HashSet<String>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); Document doc = docBuild.parse(inStream); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 0) { Element valElem = (Element) cols.item(0); String value = ((Text) valElem.getFirstChild()).getData(); if (value.startsWith("http://dbpedia.org/resource/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/ontology/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/class/yago/")) { value = value.substring(30); value = value.split("[\\d]+")[0]; } values.add(value); } } } catch (UnsupportedEncodingException exc) { exc.printStackTrace(); } catch (IOException exc) { System.err.println("Cannot retrieve record for " + resourceName); } catch (SAXException exc) { System.err.println("Cannot parse record for " + resourceName); } return values; } Code Sample 2: public String FTPupload(String filepath) { String fileUrl = null; Long clicks = System.currentTimeMillis(); String currentDateTimeString = clicks.toString(); String[] tmpSplite = filepath.split("/"); String filename = currentDateTimeString + tmpSplite[tmpSplite.length - 1]; String host = "140.112.31.165:8080/sound/"; Log.d("test", "get in"); FTPClient ftp = new FTPClient(); Log.d("test", "initial ftp"); try { ftp.connect("140.112.31.165"); ftp.enterLocalPassiveMode(); Log.d("test", "we connected"); if (!ftp.login("tacowu", "4565686")) { ftp.logout(); return fileUrl; } int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { Log.d("test", "get in trouble"); ftp.disconnect(); return fileUrl; } Log.d("test", "we logged in"); ftp.setFileType(ftp.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); File file = new File(filepath); if (file == null) Log.d("test", "file open faild"); else Log.d("test", "file open sucess"); FileInputStream aInputStream = new FileInputStream(file); boolean aRtn = ftp.storeFile(filename, aInputStream); aInputStream.close(); ftp.disconnect(); } catch (Exception ex) { } fileUrl = host + filename; return fileUrl; }
00
Code Sample 1: private static String deviceIdFromCombined_Device_ID(Context context) { StringBuilder builder = new StringBuilder(); builder.append(deviceIdFromIMEI(context)); builder.append(deviceIdFromPseudo_Unique_Id()); builder.append(deviceIdFromAndroidId(context)); builder.append(deviceIdFromWLAN_MAC_Address(context)); builder.append(deviceIdFromBT_MAC_Address(context)); String m_szLongID = builder.toString(); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(m_szLongID.getBytes(), 0, m_szLongID.length()); byte p_md5Data[] = m.digest(); String m_szUniqueID = new String(); for (int i = 0; i < p_md5Data.length; i++) { int b = (0xFF & p_md5Data[i]); if (b <= 0xF) m_szUniqueID += "0"; m_szUniqueID += Integer.toHexString(b); } return m_szUniqueID; } Code Sample 2: public void unlock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setLong(1, System.currentTimeMillis()); ps.setString(2, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
00
Code Sample 1: @Override public void run() { try { jButton1.setEnabled(false); jButton2.setEnabled(false); URL url = new URL(updatePath + "currentVersion.txt"); URLConnection con = url.openConnection(); con.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; for (int i = 0; (line = in.readLine()) != null; i++) { URL fileUrl = new URL(updatePath + line); URLConnection filecon = fileUrl.openConnection(); InputStream stream = fileUrl.openStream(); int oneChar, count = 0; int size = filecon.getContentLength(); jProgressBar1.setMaximum(size); jProgressBar1.setValue(0); File testFile = new File(line); String build = ""; for (String dirtest : line.split("/")) { build += dirtest; if (!build.contains(".")) { File dirfile = new File(build); if (!dirfile.exists()) { dirfile.mkdir(); } } build += "/"; } if (testFile.length() == size) { } else { transferFile(line, fileUrl, size); if (line.endsWith("documents.zip")) { ZipInputStream in2 = new ZipInputStream(new FileInputStream(line)); ZipEntry entry; String pathDoc = line.split("documents.zip")[0]; File docDir = new File(pathDoc + "documents"); if (!docDir.exists()) { docDir.mkdir(); } while ((entry = in2.getNextEntry()) != null) { String outFilename = pathDoc + "documents/" + entry.getName(); OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } in2.close(); } if (line.endsWith("mysql.zip")) { ZipFile zipfile = new ZipFile(line); Enumeration entries = zipfile.entries(); String pathDoc = line.split("mysql.zip")[0]; File docDir = new File(pathDoc + "mysql"); if (!docDir.exists()) { docDir.mkdir(); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { System.err.println("Extracting directory: " + entry.getName()); (new File(pathDoc + "mysql/" + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); InputStream in2 = zipfile.getInputStream(entry); OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName())); byte[] buf = new byte[1024]; int len; while ((len = in2.read(buf)) > 0) { out.write(buf, 0, len); } in2.close(); out.close(); } } } jProgressBar2.setValue(i + 1); labelFileProgress.setText((i + 1) + "/" + numberFiles); } labelStatus.setText("Update Finished"); jButton1.setVisible(false); jButton2.setText("Finished"); jButton1.setEnabled(true); jButton2.setEnabled(true); } catch (IOException ex) { Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
00
Code Sample 1: private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } } Code Sample 2: public int[] bubbleSort(int[] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length - i - 1; j++) { if (data[j] > data[j + 1]) { int temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; } } } return data; }
11
Code Sample 1: public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } } Code Sample 2: public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } return convertToHex(md5hash); }
11
Code Sample 1: private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } } Code Sample 2: public static Board readStream(InputStream is) throws IOException { StringWriter stringWriter = new StringWriter(); IOUtils.copy(is, stringWriter); String s = stringWriter.getBuffer().toString(); Board board = read(s); return board; }
11
Code Sample 1: public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); } Code Sample 2: public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
00
Code Sample 1: public alto.io.Output openOutput() throws java.io.IOException { URL url = this.url; if (null != url) { URLConnection connection = url.openConnection(); connection.setDoOutput(true); if (connection instanceof alto.net.Connection) { ((alto.net.Connection) connection).setReference(this); } return new ReferenceOutputStream(this, connection); } HttpMessage container = this.write(); return new ReferenceOutputStream(this, container); } Code Sample 2: @Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); }
00
Code Sample 1: private void salvarArtista(Artista artista) throws Exception { System.out.println("GerenteMySQL.salvarArtista()" + artista.toString2()); Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); for (Obra obra : artista.getListaObras()) { salvarObra(conn, ps, obra, artista.getNumeroInscricao()); } conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: @Test public void testClient() throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpHost proxy = new HttpHost("127.0.0.1", 1280, "http"); HttpGet httpget = new HttpGet("http://a.b.c.d/pdn/"); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = response.getEntity().getContent(); readInputStream(is); System.out.println("----------------------------------------"); httpget.abort(); httpclient.getConnectionManager().shutdown(); } Code Sample 2: public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public void fetch(URL url, HTTPMethod method, String payload, WithResponse wr) throws IOException { System.out.println("fetchin' " + url.toString() + " with GAE fetch service"); HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setReadTimeout(10000); connection.setRequestMethod(method.name()); System.out.println(method.name().toString()); connection.setRequestProperty("Connection", "close"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (wr != null) { connection.setDoOutput(true); } connection.connect(); System.out.println(connection.toString()); if (payload != null) { OutputStream out = null; OutputStreamWriter outWriter = null; try { out = connection.getOutputStream(); outWriter = new OutputStreamWriter(out, "UTF-8"); outWriter.write(payload); System.out.println(out.toString()); } finally { close(outWriter); close(out); } } if (wr != null) { InputStream in = null; InputStreamReader reader = null; StringBuilder sb = new StringBuilder(); try { in = connection.getInputStream(); reader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(reader); String line; while ((line = bufReader.readLine()) != null) { sb.append(line).append('\n'); } System.out.println(line); } finally { close(reader); close(in); } } } finally { if (connection != null) { connection.disconnect(); } } } Code Sample 2: @Override public void execute() throws BuildException { if (this.toFile == null && this.toDir == null) throw new BuildException("Missing Destination File/Dir"); if (this.toFile != null && this.toDir != null) throw new BuildException("Both Defined Destination File/Dir"); if (this.urlStr == null) throw new BuildException("Missing URL"); URL base = null; try { if (baseStr != null) base = new URL(this.baseStr + (baseStr.endsWith("/") ? "" : "/")); } catch (MalformedURLException e) { throw new BuildException(e); } String tokens[] = this.urlStr.split("[ \t\n]+"); try { for (String nextURL : tokens) { nextURL = nextURL.trim(); if (nextURL.length() == 0) continue; URL url = null; try { url = new URL(base, nextURL); } catch (MalformedURLException e) { throw new BuildException(e); } File dest = null; if (this.toDir != null) { String file = url.getFile(); int i = file.lastIndexOf('/'); if (i != -1 && i + 1 != file.length()) file = file.substring(i + 1); dest = new File(this.toDir, file); } else { dest = this.toFile; } if (dest.exists()) continue; byte buff[] = new byte[2048]; FileOutputStream out = new FileOutputStream(dest); InputStream in = url.openStream(); int n = 0; while ((n = in.read(buff)) != -1) { out.write(buff, 0, n); } in.close(); out.flush(); out.close(); System.out.println("Downloaded " + url + " to " + dest); } } catch (IOException e) { throw new BuildException(e); } }
00
Code Sample 1: public void moveRowDown(int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number not between 1 and " + (max - 1)); stmt.executeUpdate("update WordClassifications set Rank = -1 where Rank = " + row); stmt.executeUpdate("update WordClassifications set Rank = " + row + " where Rank = " + (row + 1)); stmt.executeUpdate("update WordClassifications set Rank = " + (row + 1) + " where Rank = -1"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
00
Code Sample 1: public void deleteInstance(int instanceId) throws FidoDatabaseException, ObjectNotFoundException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, instanceId) == false) throw new ObjectNotFoundException(instanceId); ObjectLinkTable objectLinkList = new ObjectLinkTable(); ObjectAttributeTable objectAttributeList = new ObjectAttributeTable(); objectLinkList.deleteObject(stmt, instanceId); objectAttributeList.deleteObject(stmt, instanceId); stmt.executeUpdate("delete from Objects where ObjectId = " + instanceId); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException { System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath()); try { if (destination.exists() && !appendToFile) { destination.delete(); } if (!destination.exists()) destination.createNewFile(); GetMethod get = new GetMethod(url.toString()); HttpClient httpClient = new HttpClient(); Header rangeHeader = new Header(); rangeHeader.setName("Range"); rangeHeader.setValue("bytes=" + beginRange + "-" + endRange); get.setRequestHeader(rangeHeader); httpClient.executeMethod(get); int statusCode = get.getStatusCode(); if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server -> " + statusCode + " " + get.getStatusText()); InputStream input = get.getResponseBodyAsStream(); OutputStream output = new FileOutputStream(destination, appendToFile); try { int length = IOUtils.copy(input, output); System.out.println(" Length : " + length); } finally { input.close(); output.flush(); output.close(); } } catch (Exception e) { e.printStackTrace(); logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage()); throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage()); } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
00
Code Sample 1: public static byte[] generatePasswordHash(String s) { byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); password = md5.digest(); return password; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return password; } Code Sample 2: public Document getDocument(String urlString) { Document doc = null; URLConnection conn = null; InputStream in = null; try { SAXBuilder sxbuild = new SAXBuilder(); if (Osmolt.debug) { outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); in = new FileInputStream(new File(System.getProperty("user.home") + "/data.osm")); outputInterface.processSetStatus("getting data from " + System.getProperty("user.home") + "/data.osm"); } else { URL url = new URL(urlString); outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); outputInterface.processSetStatus("connecting Server"); conn = url.openConnection(); outputInterface.processSetStatus("loading Data"); in = conn.getInputStream(); } doc = sxbuild.build(in); } catch (java.net.UnknownHostException e) { outputInterface.printError("Unknown Host: " + urlString); } catch (java.net.SocketTimeoutException e) { outputInterface.printError("Timeout: Server does not response"); } catch (java.net.ConnectException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (java.net.SocketException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (JDOMException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (IOException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (Exception e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ioe) { } } return doc; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void 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); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } 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) { ; } } }
11
Code Sample 1: static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); } Code Sample 2: private String generateFilename() { byte[] hash = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); try { digest.update(InetAddress.getLocalHost().toString().getBytes()); } catch (UnknownHostException e) { } digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes()); byte[] foo = new byte[128]; new SecureRandom().nextBytes(foo); digest.update(foo); hash = digest.digest(); } catch (NoSuchAlgorithmException e) { Debug.assrt(false); } return hexEncode(hash); }
11
Code Sample 1: public static void main(String[] args) { File container = new File(ArchiveFeature.class.getProtectionDomain().getCodeSource().getLocation().toURI()); if (container == null) { throw new RuntimeException("this use-case isn't being invoked from the executable jar"); } JarFile jarFile = new JarFile(container); String artifactName = PROJECT_DIST_ARCHIVE + ".tar.gz"; File artifactFile = new File(".", artifactName); ZipEntry artifactEntry = jarFile.getEntry(artifactName); InputStream source = jarFile.getInputStream(artifactEntry); try { FileOutputStream dest = new FileOutputStream(artifactFile); try { IOUtils.copy(source, dest); } finally { IOUtils.closeQuietly(dest); } } finally { IOUtils.closeQuietly(source); } Project project = new Project(); project.setName("project"); project.init(); Target target = new Target(); target.setName("target"); project.addTarget(target); project.addBuildListener(new Log4jListener()); Untar untar = new Untar(); untar.setTaskName("untar"); untar.setSrc(artifactFile); untar.setDest(new File(".")); Untar.UntarCompressionMethod method = new Untar.UntarCompressionMethod(); method.setValue("gzip"); untar.setCompression(method); untar.setProject(project); untar.setOwningTarget(target); target.addTask(untar); untar.execute(); } Code Sample 2: public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
00
Code Sample 1: public LinkedList<NameValuePair> getScoreboard() { InputStream is = null; String result = ""; LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>(); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return null; } } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json = new JSONObject(result); JSONArray data = json.getJSONArray("data"); JSONArray me = json.getJSONArray("me"); for (int i = 0; i < data.length(); i++) { JSONObject single = data.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } for (int i = 0; i < me.length(); i++) { JSONObject single = me.getJSONObject(i); String uid = single.getString("uid"); String score = single.getString("score"); scores.add(new BasicNameValuePair(uid, score)); } System.out.println(json); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return scores; } Code Sample 2: public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:plindenbaum@yahoo.fr\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&amp;cmd=Search&amp;itool=pubmed_Abstract&amp;term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=pubmed&amp;dopt=Abstract&amp;list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); }
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: private static byte[] gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(frase.getBytes()); return md.digest(); } catch (Exception e) { return null; } }
11
Code Sample 1: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = super.getDatastreams(pDeposit); FileInputStream tInput = null; String tFileName = ((LocalDatastream) tDatastreams.get(0)).getPath(); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".thum")); tInput.close(); Datastream tThum = new LocalDatastream("THUMBRES_IMG", this.getContentType(), tTempFileName + ".thum"); tDatastreams.add(tThum); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".mid")); tInput.close(); Datastream tMid = new LocalDatastream("MEDRES_IMG", this.getContentType(), tTempFileName + ".mid"); tDatastreams.add(tMid); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".high")); tInput.close(); Datastream tLarge = new LocalDatastream("HIGHRES_IMG", this.getContentType(), tTempFileName + ".high"); tDatastreams.add(tLarge); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".vhigh")); tInput.close(); Datastream tVLarge = new LocalDatastream("VERYHIGHRES_IMG", this.getContentType(), tTempFileName + ".vhigh"); tDatastreams.add(tVLarge); return tDatastreams; } Code Sample 2: public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
00
Code Sample 1: public Set<Plugin<?>> loadPluginMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginMetaInfPath); pluginsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "interfaces", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { if (!StringHelper.isEmpty(line)) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "interface", line)); pluginsSet.add(inspectPlugin(Class.forName(line.trim()))); } line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginMetaInfPath, line); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile() + "\n" + url.toString(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginMetaInfPath, ioe.getMessage()); } } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
00
Code Sample 1: public static boolean insereLicao(final Connection con, Licao lic, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodLicao(con, lic); String titulo = lic.getTitulo().replaceAll("['\"]", ""); String coment = lic.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO licao VALUES(" + lic.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO lic_aut VALUES(" + lic.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "LICAO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/record/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Record Deleted!"); } else { response.setDone(false); response.setMessage("Delete Record Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: public ValidationReport validate(OriginalDeployUnitDescription unit) throws UnitValidationException { ValidationReport vr = new DefaultValidationReport(); errorHandler = new SimpleErrorHandler(vr); vr.setFileUri(unit.getAbsolutePath()); SAXParser parser; SAXReader reader = null; try { parser = factory.newSAXParser(); reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(this.errorHandler); } catch (ParserConfigurationException e) { throw new UnitValidationException("The configuration of parser is illegal.", e); } catch (SAXException e) { String m = "Something is wrong when register schema"; logger.error(m, e); throw new UnitValidationException(m, e); } ZipInputStream zipInputStream; InputStream tempInput = null; try { tempInput = new FileInputStream(unit.getAbsolutePath()); } catch (FileNotFoundException e1) { String m = String.format("The file [%s] don't exist.", unit.getAbsolutePath()); logger.error(m, e1); throw new UnitValidationException(m, e1); } zipInputStream = new ZipInputStream(tempInput); ZipEntry zipEntry = null; try { zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { String m = String.format("Error when get zipEntry. Maybe the [%s] is not zip file!", unit.getAbsolutePath()); logger.error(m); throw new UnitValidationException(m); } while (zipEntry != null) { if (configFiles.contains(zipEntry.getName())) { byte[] extra = new byte[(int) zipEntry.getSize()]; zipInputStream.read(extra); File file = File.createTempFile("temp", "extra"); file.deleteOnExit(); logger.info("[TempFile:]" + file.getAbsoluteFile()); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(extra); FileOutputStream tempFileOutputStream = new FileOutputStream(file); IOUtils.copy(byteInputStream, tempFileOutputStream); tempFileOutputStream.flush(); IOUtils.closeQuietly(tempFileOutputStream); InputStream inputStream = new FileInputStream(file); reader.read(inputStream, unit.getAbsolutePath() + ":" + zipEntry.getName()); IOUtils.closeQuietly(inputStream); } zipEntry = zipInputStream.getNextEntry(); } } catch (IOException e) { ValidationMessage vm = new XMLValidationMessage("IOError", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } catch (DocumentException e) { ValidationMessage vm = new XMLValidationMessage("Document Error.", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } finally { IOUtils.closeQuietly(tempInput); IOUtils.closeQuietly(zipInputStream); } return vr; }
00
Code Sample 1: public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static String digestString(String data) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; }
00
Code Sample 1: public void bindDownload(Download download) throws BindingException { List<ChunkDownload> chunks = download.getChunks(); File destination = download.getFile(); FileOutputStream fos = null; try { fos = FileUtils.openOutputStream(destination); for (ChunkDownload chunk : chunks) { String filePath = chunk.getChunkFilePath(); InputStream ins = null; try { File chunkFile = new File(filePath); ins = FileUtils.openInputStream(chunkFile); IOUtils.copy(ins, fos); chunkFile.delete(); } catch (IOException e) { e.printStackTrace(); } finally { ins.close(); } } download.getWorkDir().delete(); download.complete(); } catch (IOException e) { logger.error("IO Exception while copying the chunk " + e.getMessage(), e); e.printStackTrace(); throw new BindingException("IO Exception while copying the chunk " + e.getMessage(), e); } finally { try { fos.close(); } catch (IOException e) { logger.error("IO Exception while copying closing stream of the target file " + e.getMessage(), e); e.printStackTrace(); throw new BindingException("IO Exception while copying closing stream of the target file " + e.getMessage(), e); } } } Code Sample 2: public void run() { btnReintentar.setEnabled(false); try { lblEstado.setText("Conectando con servidor..."); escribir("\nConectando con servidor..."); URL url = new URL("http://apeiron.sourceforge.net/version.php"); lblEstado.setText("Obteniendo informaci�n de versi�n..."); escribir("Ok\n"); escribir("Obteniendo informaci�n sobre �ltima versi�n..."); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String linea = br.readLine(); escribir("Ok\n"); if (linea != null) { escribir("Versi�n mas reciente: " + linea + "\n"); if (Principal.version < Double.parseDouble(linea)) { lblEstado.setText("Hay una nueva versi�n: Apeiron " + linea); escribir("Puede obtener la actualizaci�n de: http://apeiron.sourceforge.net\n"); btnActualizar.setEnabled(true); setVisible(true); } else { lblEstado.setText("Usted tiene la �ltima versi�n"); } } br.close(); } catch (MalformedURLException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } catch (IOException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } btnReintentar.setEnabled(true); }
00
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: public void buildDocument(Files page) { String uri = constructFileUrlString(page, true); URL url; try { url = new URL(uri); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); Reader reader = new InputStreamReader(in, "UTF8"); xsltInputSource = new InputSourceImpl(reader, uri); xsltInputSource.setEncoding("utf-8"); UserAgentContext ucontext = new CobraConfig.LocalUserAgentContext(); HtmlRendererContext rendererContext = new CobraConfig.LocalHtmlRendererContext(htmlPanel, ucontext); DocumentBuilderImpl builder = new DocumentBuilderImpl(rendererContext.getUserAgentContext(), rendererContext); xsltDocument = builder.parse(xsltInputSource); htmlPanel.setDocument(xsltDocument, rendererContext); documentHolder = xsltDocument.toString(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
11
Code Sample 1: public boolean updatenum(int num, String pid) { boolean flag = false; Connection conn = null; PreparedStatement pm = null; try { conn = Pool.getConnection(); conn.setAutoCommit(false); pm = conn.prepareStatement("update addwuliao set innum=? where pid=?"); pm.setInt(1, num); pm.setString(2, pid); int a = pm.executeUpdate(); if (a == 0) { flag = false; } else { flag = true; } conn.commit(); Pool.close(pm); Pool.close(conn); } catch (Exception e) { e.printStackTrace(); flag = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } Pool.close(pm); Pool.close(conn); } finally { Pool.close(pm); Pool.close(conn); } return flag; } Code Sample 2: private void saveCampaign() throws HeadlessException { try { dbConnection.setAutoCommit(false); dbConnection.setSavepoint(); String sql = "UPDATE campaigns SET " + "queue = ? ," + "adjustRatioPeriod = ?, " + "asterisk = ?, " + "context = ?," + "extension = ?, " + "dialContext = ?, " + "dialPrefix = ?," + "dialTimeout = ?, " + "dialingMethod = ?," + "dialsPerFreeResourceRatio = ?, " + "maxIVRChannels = ?, " + "maxDialingThreads = ?," + "maxDialsPerFreeResourceRatio = ?," + "minDialsPerFreeResourceRatio = ?, " + "maxTries = ?, " + "firstRetryAfterMinutes = ?," + "secondRetryAfterMinutes = ?, " + "furtherRetryAfterMinutes = ?, " + "startDate = ?, " + "endDate = ?," + "popUpURL = ?, " + "contactBatchSize = ?, " + "retriesBatchPct = ?, " + "reschedulesBatchPct = ?, " + "allowReschedule = ?, " + "rescheduleToOnself = ?, " + "script = ?," + "agentsCanUpdateContacts = ?, " + "hideContactFields = ?, " + "afterCallWork = ?, " + "reserveAvailableAgents = ?, " + "useDNCList = ?, " + "enableAgentDNC = ?, " + "contactsFilter = ?, " + "DNCTo = ?," + "callRecordingPolicy = ?, " + "callRecordingPercent = ?, " + "callRecordingMaxAge = ?, " + "WHERE name = ?"; PreparedStatement statement = dbConnection.prepareStatement(sql); int i = 1; statement.setString(i++, txtQueue.getText()); statement.setInt(i++, Integer.valueOf(txtAdjustRatio.getText())); statement.setString(i++, ""); statement.setString(i++, txtContext.getText()); statement.setString(i++, txtExtension.getText()); statement.setString(i++, txtDialContext.getText()); statement.setString(i++, txtDialPrefix.getText()); statement.setInt(i++, 30000); statement.setInt(i++, cboDialingMethod.getSelectedIndex()); statement.setFloat(i++, Float.valueOf(txtInitialDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxIVRChannels.getText())); statement.setInt(i++, Integer.valueOf(txtDialLimit.getText())); statement.setFloat(i++, Float.valueOf(txtMaxDialingRatio.getText())); statement.setFloat(i++, Float.valueOf(txtMinDialingRatio.getText())); statement.setInt(i++, Integer.valueOf(txtMaxRetries.getText())); statement.setInt(i++, Integer.valueOf(txtFirstRetry.getText())); statement.setInt(i++, Integer.valueOf(txtSecondRetry.getText())); statement.setInt(i++, Integer.valueOf(txtFurtherRetries.getText())); statement.setDate(i++, Date.valueOf(txtStartDate.getText())); statement.setDate(i++, Date.valueOf(txtEndDate.getText())); statement.setString(i++, txtURL.getText()); statement.setInt(i++, Integer.valueOf(txtContactBatchSize.getText())); statement.setInt(i++, Integer.valueOf(txtRetryBatchPct.getText())); statement.setInt(i++, Integer.valueOf(txtRescheduleBatchPct.getText())); statement.setInt(i++, chkAgentCanReschedule.isSelected() ? 1 : 0); statement.setInt(i++, chkAgentCanRescheduleSelf.isSelected() ? 1 : 0); statement.setString(i++, txtScript.getText()); statement.setInt(i++, chkAgentCanUpdateContacts.isSelected() ? 1 : 0); statement.setString(i++, ""); statement.setInt(i++, Integer.valueOf(txtACW.getText())); statement.setInt(i++, Integer.valueOf(txtReserveAgents.getText())); statement.setInt(i++, cboDNCListPreference.getSelectedIndex()); statement.setInt(i++, 1); statement.setString(i++, ""); statement.setInt(i++, 0); statement.setInt(i++, cboRecordingPolicy.getSelectedIndex()); statement.setInt(i++, Integer.valueOf(txtRecordingPct.getText())); statement.setInt(i++, Integer.valueOf(txtRecordingMaxAge.getText())); statement.setString(i++, campaign); statement.executeUpdate(); dbConnection.commit(); } catch (SQLException ex) { try { dbConnection.rollback(); } catch (SQLException ex1) { Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1); } JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE); Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex); } }
00
Code Sample 1: public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } } Code Sample 2: public String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
11
Code Sample 1: public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } } Code Sample 2: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).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(); } } }
11
Code Sample 1: private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; } Code Sample 2: public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
11
Code Sample 1: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } } Code Sample 2: public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
11
Code Sample 1: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } } Code Sample 2: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
11
Code Sample 1: public static String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } Code Sample 2: private String read(URL url) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer text = new StringBuffer(); String line; while ((line = in.readLine()) != null) { text.append(line); } return text.toString(); } finally { in.close(); } }
00
Code Sample 1: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); } Code Sample 2: public Document getSdlDomResource(String aResourceName) throws SdlException { InputStream in = null; try { URL url = getDeploymentContext().getResourceURL(aResourceName); if (url == null) { return null; } else { in = url.openStream(); return getSdlParser().loadSdlDocument(in, null); } } catch (Throwable t) { logger.error("Error: unable to load: " + aResourceName + " from " + getDeploymentContext().getDeploymentLocation()); throw new SdlDeploymentException(MessageFormat.format("unable to load: {0} from {1}", new Object[] { aResourceName, getDeploymentContext().getDeploymentLocation() }), t); } finally { SdlCloser.close(in); } }
00
Code Sample 1: public Vector<String> getVoiceServersNames() { Vector<String> result = new Vector<String>(); boolean serverline = false; String line; String[] splitline; try { URL url = new URL(voiceaddress); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { if (serverline) { splitline = line.split(":"); result.add(splitline[0]); } if (line.startsWith("!VOICE SERVERS")) { serverline = true; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } Code Sample 2: public static void gunzip(File gzippedFile, File destinationFile) throws IOException { int buffer = 2048; FileInputStream in = new FileInputStream(gzippedFile); GZIPInputStream zipin = new GZIPInputStream(in); byte[] data = new byte[buffer]; FileOutputStream out = new FileOutputStream(destinationFile); int length; while ((length = zipin.read(data, 0, buffer)) != -1) out.write(data, 0, length); out.close(); zipin.close(); }
11
Code Sample 1: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; } Code Sample 2: public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }