label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public String uploadReport(Collection c) { try { String id = generateRandomId(); Iterator iter = c.iterator(); URL url = new URL(ZorobotSystem.props.getProperty("zoro.url") + "auplo2.jsp"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("id=" + id + "&"); StringBuffer sb = new StringBuffer(); int gg = 0; while (iter.hasNext()) { if (gg++ >= 500) break; Question tq = (Question) iter.next(); sb.append("a="); sb.append(URLEncoder.encode(tq.question, "UTF-8")); sb.append("*"); StringBuffer ss = new StringBuffer(); String[] ans; if (tq.ansDisplay != null) { ans = tq.ansDisplay; } else { ans = tq.answer; } for (int j = 0; j < ans.length; j++) { if (j > 0) ss.append("*"); ss.append(ans[j]); } sb.append(URLEncoder.encode(ss.toString(), "UTF-8")); if (iter.hasNext() && gg < 500) sb.append("&"); } out.println(sb.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; if ((inputLine = in.readLine()) != null) { if (!inputLine.equals("OK!") && inputLine.length() > 3) { System.out.println("Not OK: " + inputLine); return "xxxxxxxxxx"; } } in.close(); return id; } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static final boolean zipExtract(String zipfile, String name, String dest) { boolean f = false; try { InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().equals(name)) { FileOutputStream out = new FileOutputStream(dest); byte b[] = new byte[TEMP_FILE_BUFFER_SIZE]; int len = 0; while ((len = zin.read(b)) != -1) out.write(b, 0, len); out.close(); f = true; break; } } zin.close(); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } return (f); }
|
11
|
Code Sample 1:
private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } }
Code Sample 2:
public void uploadFile(File inputFile, String targetFile) throws IOException { System.out.println("Uploading " + inputFile.getName() + " to " + targetFile); File outputFile = new File(targetFile); if (targetFile.endsWith("/")) { outputFile = new File(outputFile, inputFile.getName()); } else if (outputFile.getParentFile().exists() == false) { outputFile.getParentFile().mkdirs(); } if (inputFile.renameTo(outputFile) == false) { InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } }
|
11
|
Code Sample 1:
public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
Code Sample 2:
void IconmenuItem6_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setDefaultPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getDefaultPath().lastIndexOf(separator); String imgName = getDefaultPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getDefaultPath()); File outputFile = new File(newPath); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setDefaultPath(newPath); createDefaultImage(); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFromHDFSMerge(String hdfsDir, String local) throws IOException { rmr(local); File f = new File(local); f.getAbsoluteFile().getParentFile().mkdirs(); HDFSDirInputStream inp = new HDFSDirInputStream(hdfsDir); FileOutputStream oup = new FileOutputStream(local); IOUtils.copyBytes(inp, oup, 65 * 1024 * 1024, true); }
|
11
|
Code Sample 1:
public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); }
Code Sample 2:
public String get(String s) { s = s.replaceAll("[^a-z0-9_]", ""); StringBuilder sb = new StringBuilder(); try { String result = null; URL url = new URL("http://docs.google.com/Doc?id=" + URLEncoder.encode(s, "UTF-8")); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(false); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String inputLine; int state = 0; while ((inputLine = in.readLine()) != null) { if (state == 0) { int textPos = inputLine.indexOf("id=\"doc-contents"); if (textPos >= 0) { state = 1; } } else if (state == 1) { int textPos = inputLine.indexOf("</div>"); if (textPos >= 0) break; inputLine = inputLine.replaceAll("[\\u0000-\\u001F]", ""); sb.append(inputLine); } } in.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
|
11
|
Code Sample 1:
public void launchJob(final String workingDir, final AppConfigType appConfig) throws FaultType { logger.info("called for job: " + jobID); MessageContext mc = MessageContext.getCurrentContext(); HttpServletRequest req = (HttpServletRequest) mc.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); String clientDN = (String) req.getAttribute(GSIConstants.GSI_USER_DN); if (clientDN != null) { logger.info("Client's DN: " + clientDN); } else { clientDN = "Unknown client"; } String remoteIP = req.getRemoteAddr(); SOAPService service = mc.getService(); String serviceName = service.getName(); if (serviceName == null) { serviceName = "Unknown service"; } if (appConfig.isParallel()) { if (AppServiceImpl.drmaaInUse) { if (AppServiceImpl.drmaaPE == null) { logger.error("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("drmaa.pe property must be specified in opal.properties " + "for parallel execution using DRMAA"); } if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution using DRMAA"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "using DRMAA"); } } else if (!AppServiceImpl.globusInUse) { if (AppServiceImpl.mpiRun == null) { logger.error("mpi.run property must be specified in opal.properties " + "for parallel execution without using Globus"); throw new FaultType("mpi.run property must be specified in " + "opal.properties for parallel execution " + "without using Globus"); } } if (jobIn.getNumProcs() == null) { logger.error("Number of processes unspecified for parallel job"); throw new FaultType("Number of processes unspecified for parallel job"); } else if (jobIn.getNumProcs().intValue() > AppServiceImpl.numProcs) { logger.error("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); throw new FaultType("Processors required - " + jobIn.getNumProcs() + ", available - " + AppServiceImpl.numProcs); } } try { status.setCode(GramJob.STATUS_PENDING); status.setMessage("Launching executable"); status.setBaseURL(new URI(AppServiceImpl.tomcatURL + jobID)); } catch (MalformedURIException mue) { logger.error("Cannot convert base_url string to URI - " + mue.getMessage()); throw new FaultType("Cannot convert base_url string to URI - " + mue.getMessage()); } if (!AppServiceImpl.dbInUse) { AppServiceImpl.statusTable.put(jobID, status); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { logger.error("Cannot connect to database - " + e.getMessage()); throw new FaultType("Cannot connect to database - " + e.getMessage()); } String time = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.US).format(new Date()); String sqlStmt = "insert into job_status(job_id, code, message, base_url, " + "client_dn, client_ip, service_name, start_time, last_update) " + "values ('" + jobID + "', " + status.getCode() + ", " + "'" + status.getMessage() + "', " + "'" + status.getBaseURL() + "', " + "'" + clientDN + "', " + "'" + remoteIP + "', " + "'" + serviceName + "', " + "'" + time + "', " + "'" + time + "');"; try { Statement stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); conn.close(); } catch (SQLException e) { logger.error("Cannot insert job status into database - " + e.getMessage()); throw new FaultType("Cannot insert job status into database - " + e.getMessage()); } } String args = appConfig.getDefaultArgs(); if (args == null) { args = jobIn.getArgList(); } else { String userArgs = jobIn.getArgList(); if (userArgs != null) args += " " + userArgs; } if (args != null) { args = args.trim(); } logger.debug("Argument list: " + args); if (AppServiceImpl.drmaaInUse) { String cmd = null; String[] argsArray = null; if (appConfig.isParallel()) { cmd = "/bin/sh"; String newArgs = AppServiceImpl.mpiRun + " -machinefile $TMPDIR/machines" + " -np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation(); if (args != null) { args = newArgs + " " + args; } else { args = newArgs; } logger.debug("CMD: " + args); argsArray = new String[] { "-c", args }; } else { cmd = appConfig.getBinaryLocation(); if (args == null) args = ""; logger.debug("CMD: " + cmd + " " + args); argsArray = args.split(" "); } try { logger.debug("Working directory: " + workingDir); JobTemplate jt = session.createJobTemplate(); if (appConfig.isParallel()) jt.setNativeSpecification("-pe " + AppServiceImpl.drmaaPE + " " + jobIn.getNumProcs()); jt.setRemoteCommand(cmd); jt.setArgs(argsArray); jt.setJobName(jobID); jt.setWorkingDirectory(workingDir); jt.setErrorPath(":" + workingDir + "/stderr.txt"); jt.setOutputPath(":" + workingDir + "/stdout.txt"); drmaaJobID = session.runJob(jt); logger.info("DRMAA job has been submitted with id " + drmaaJobID); session.deleteJobTemplate(jt); } catch (Exception ex) { logger.error(ex); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via DRMAA - " + ex.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } else if (AppServiceImpl.globusInUse) { String rsl = null; if (appConfig.isParallel()) { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(count=" + jobIn.getNumProcs() + ")" + "(jobtype=mpi)" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } else { rsl = "&(directory=" + workingDir + ")" + "(executable=" + appConfig.getBinaryLocation() + ")" + "(stdout=stdout.txt)" + "(stderr=stderr.txt)"; } if (args != null) { args = "\"" + args + "\""; args = args.replaceAll("[\\s]+", "\" \""); rsl += "(arguments=" + args + ")"; } logger.debug("RSL: " + rsl); try { job = new GramJob(rsl); GlobusCredential globusCred = new GlobusCredential(AppServiceImpl.serviceCertPath, AppServiceImpl.serviceKeyPath); GSSCredential gssCred = new GlobusGSSCredentialImpl(globusCred, GSSCredential.INITIATE_AND_ACCEPT); job.setCredentials(gssCred); job.addListener(this); job.request(AppServiceImpl.gatekeeperContact); } catch (Exception ge) { logger.error(ge); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via Globus - " + ge.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } } else { String cmd = null; if (appConfig.isParallel()) { cmd = new String(AppServiceImpl.mpiRun + " " + "-np " + jobIn.getNumProcs() + " " + appConfig.getBinaryLocation()); } else { cmd = new String(appConfig.getBinaryLocation()); } if (args != null) { cmd += " " + args; } logger.debug("CMD: " + cmd); try { logger.debug("Working directory: " + workingDir); proc = Runtime.getRuntime().exec(cmd, null, new File(workingDir)); stdoutThread = writeStdOut(proc, workingDir); stderrThread = writeStdErr(proc, workingDir); } catch (IOException ioe) { logger.error(ioe); status.setCode(GramJob.STATUS_FAILED); status.setMessage("Error while running executable via fork - " + ioe.getMessage()); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } return; } status.setCode(GramJob.STATUS_ACTIVE); status.setMessage("Execution in progress"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { logger.error(e); throw new FaultType("Cannot update status into database - " + e.getMessage()); } } } new Thread() { public void run() { try { waitForCompletion(); } catch (FaultType f) { logger.error(f); synchronized (status) { status.notifyAll(); } return; } if (AppServiceImpl.drmaaInUse || !AppServiceImpl.globusInUse) { done = true; status.setCode(GramJob.STATUS_STAGE_OUT); status.setMessage("Writing output metadata"); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } } try { if (!AppServiceImpl.drmaaInUse && !AppServiceImpl.globusInUse) { try { logger.debug("Waiting for all outputs to be written out"); stdoutThread.join(); stderrThread.join(); logger.debug("All outputs successfully written out"); } catch (InterruptedException ignore) { } } File stdOutFile = new File(workingDir + File.separator + "stdout.txt"); if (!stdOutFile.exists()) { throw new IOException("Standard output missing for execution"); } File stdErrFile = new File(workingDir + File.separator + "stderr.txt"); if (!stdErrFile.exists()) { throw new IOException("Standard error missing for execution"); } if (AppServiceImpl.archiveData) { logger.debug("Archiving output files"); File f = new File(workingDir); File[] outputFiles = f.listFiles(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(workingDir + File.separator + jobID + ".zip")); byte[] buf = new byte[1024]; try { for (int i = 0; i < outputFiles.length; i++) { FileInputStream in = new FileInputStream(outputFiles[i]); out.putNextEntry(new ZipEntry(outputFiles[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { logger.error(e); logger.error("Error not fatal - moving on"); } } File f = new File(workingDir); File[] outputFiles = f.listFiles(); OutputFileType[] outputFileObj = new OutputFileType[outputFiles.length - 2]; int j = 0; for (int i = 0; i < outputFiles.length; i++) { if (outputFiles[i].getName().equals("stdout.txt")) { outputs.setStdOut(new URI(AppServiceImpl.tomcatURL + jobID + "/stdout.txt")); } else if (outputFiles[i].getName().equals("stderr.txt")) { outputs.setStdErr(new URI(AppServiceImpl.tomcatURL + jobID + "/stderr.txt")); } else { OutputFileType next = new OutputFileType(); next.setName(outputFiles[i].getName()); next.setUrl(new URI(AppServiceImpl.tomcatURL + jobID + "/" + outputFiles[i].getName())); outputFileObj[j++] = next; } } outputs.setOutputFile(outputFileObj); } catch (IOException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot retrieve outputs after finish - " + e.getMessage()); logger.error(e); if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } } synchronized (status) { status.notifyAll(); } return; } if (!AppServiceImpl.dbInUse) { AppServiceImpl.outputTable.put(jobID, outputs); } else { Connection conn = null; try { conn = DriverManager.getConnection(AppServiceImpl.dbUrl, AppServiceImpl.dbUser, AppServiceImpl.dbPasswd); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot connect to database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } String sqlStmt = "insert into job_output(job_id, std_out, std_err) " + "values ('" + jobID + "', " + "'" + outputs.getStdOut().toString() + "', " + "'" + outputs.getStdErr().toString() + "');"; Statement stmt = null; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update job output database after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } OutputFileType[] outputFile = outputs.getOutputFile(); for (int i = 0; i < outputFile.length; i++) { sqlStmt = "insert into output_file(job_id, name, url) " + "values ('" + jobID + "', " + "'" + outputFile[i].getName() + "', " + "'" + outputFile[i].getUrl().toString() + "');"; try { stmt = conn.createStatement(); stmt.executeUpdate(sqlStmt); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update output_file DB after finish - " + e.getMessage()); logger.error(e); try { updateStatusInDatabase(jobID, status); } catch (SQLException se) { logger.error(se); } synchronized (status) { status.notifyAll(); } return; } } } if (terminatedOK()) { status.setCode(GramJob.STATUS_DONE); status.setMessage("Execution complete - " + "check outputs to verify successful execution"); } else { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Execution failed"); } if (AppServiceImpl.dbInUse) { try { updateStatusInDatabase(jobID, status); } catch (SQLException e) { status.setCode(GramJob.STATUS_FAILED); status.setMessage("Cannot update status database after finish - " + e.getMessage()); logger.error(e); synchronized (status) { status.notifyAll(); } return; } } AppServiceImpl.jobTable.remove(jobID); synchronized (status) { status.notifyAll(); } logger.info("Execution complete for job: " + jobID); } }.start(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } }
Code Sample 2:
public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); }
|
11
|
Code Sample 1:
public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); }
Code Sample 2:
public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); }
|
00
|
Code Sample 1:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
Code Sample 2:
public void testGetResource_FileOutsideOfClasspath() throws Exception { File temp = File.createTempFile("dozerfiletest", ".txt"); temp.deleteOnExit(); String resourceName = "file:" + temp.getAbsolutePath(); URL url = loader.getResource(resourceName); assertNotNull("URL should not be null", url); InputStream is = url.openStream(); assertNotNull("input stream should not be null", is); }
|
11
|
Code Sample 1:
public static String downloadWebpage1(String address) throws MalformedURLException, IOException { URL url = new URL(address); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
Code Sample 2:
public int doCheck(URL url) throws IOException { long start = (System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { } in.close(); long end = (System.currentTimeMillis()); return (int) (end - start); }
|
00
|
Code Sample 1:
public static void saveChangeLink(URL url, OutputStream os) { try { BufferedInputStream is = new BufferedInputStream(url.openStream()); int i; while ((i = is.read()) != -1) if ((char) i == '<') { String s = readTag(is); String s1 = convertTag(url, s); os.write(s1.getBytes()); } else { os.write((byte) i); } } catch (Exception _ex) { } }
Code Sample 2:
@Override public synchronized void deleteCallStatistics(Integer elementId, String contextName, String category, String project, String name, Date dateFrom, Date dateTo, Boolean extractException, String principal) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getCallInvocationsSchemaAndTableName() + " FROM " + this.getCallInvocationsSchemaAndTableName() + " INNER JOIN " + this.getCallElementsSchemaAndTableName() + " ON " + this.getCallElementsSchemaAndTableName() + ".element_id = " + this.getCallInvocationsSchemaAndTableName() + ".element_id "; if (principal != null) { queryString = queryString + "LEFT JOIN " + this.getCallPrincipalsSchemaAndTableName() + " ON " + this.getCallInvocationsSchemaAndTableName() + ".principal_id = " + this.getCallPrincipalsSchemaAndTableName() + ".principal_id "; } queryString = queryString + "WHERE "; if (elementId != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".elementId = ? AND "; } if (contextName != null) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".context_name LIKE ? AND "; } if ((category != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".category LIKE ? AND "; } if ((project != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".project LIKE ? AND "; } if ((name != null)) { queryString = queryString + this.getCallElementsSchemaAndTableName() + ".name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".start_timestamp <= ? AND "; } if (principal != null) { queryString = queryString + this.getCallPrincipalsSchemaAndTableName() + ".principal_name LIKE ? AND "; } if (extractException != null) { if (extractException.booleanValue()) { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NOT NULL AND "; } else { queryString = queryString + this.getCallInvocationsSchemaAndTableName() + ".exception_id IS NULL AND "; } } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((category != null)) { preparedStatement.setString(indexCounter, category); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } if (principal != null) { preparedStatement.setString(indexCounter, principal); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting call statistics.", e); } finally { this.releaseConnection(connection); } }
|
00
|
Code Sample 1:
public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
public void copyURLToFile(TmpFile p_TmpFile) { byte[] l_Buffer; URLConnection l_Connection = null; DataInputStream l_IN = null; DataOutputStream l_Out = null; FileOutputStream l_FileOutStream = null; try { System.gc(); if (error.compareTo(noError) == 0) { l_Connection = urlHome.openConnection(); l_FileOutStream = new FileOutputStream(p_TmpFile.getAbsolutePath()); l_Out = new DataOutputStream(l_FileOutStream); l_IN = new DataInputStream(l_Connection.getInputStream()); l_Buffer = new byte[8192]; int bytes = 0; while ((bytes = l_IN.read(l_Buffer)) > 0) { l_Out.write(l_Buffer, 0, bytes); } } } catch (MalformedURLException mue) { error = "MalformedURLException in connecting url was " + mue.getMessage(); } catch (IOException io) { error = "IOException in connecting url was " + io.getMessage(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } finally { try { l_IN.close(); l_Out.flush(); l_FileOutStream.flush(); l_FileOutStream.close(); l_Out.close(); } catch (Exception e) { error = "Exception in connecting url was " + e.getMessage(); } } }
|
00
|
Code Sample 1:
public MytemMaster getMytemMaster(String janCode) throws GaeException { HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setSoTimeout(httpParams, 10000); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); BufferedReader reader = null; StringBuffer request = new StringBuffer(address); request.append("api/mytems/show?jan="); request.append(janCode); try { HttpGet httpGet = new HttpGet(request.toString()); HttpResponse httpResponse = client.execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == NOT_FOUND) { return null; } if (statusCode >= 400) { throw new GaeException("Status Error = " + Integer.toString(statusCode)); } reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } return createMytemMaster(builder.toString()); } catch (ClientProtocolException e) { throw new GaeException(e); } catch (SocketTimeoutException e) { throw new GaeException(e); } catch (IOException exception) { throw new GaeException(exception); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); }
|
00
|
Code Sample 1:
public LinkedList<NameValuePair> getQuestion() { InputStream is = null; String result = ""; LinkedList<NameValuePair> question = 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"); JSONObject quest = data.getJSONObject(0); question.add(new BasicNameValuePair("q", quest.getString("q"))); question.add(new BasicNameValuePair("a", quest.getString("a"))); question.add(new BasicNameValuePair("b", quest.getString("b"))); question.add(new BasicNameValuePair("c", quest.getString("c"))); question.add(new BasicNameValuePair("d", quest.getString("d"))); question.add(new BasicNameValuePair("correct", quest.getString("correct"))); return question; } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return null; }
Code Sample 2:
public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); }
Code Sample 2:
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception { String attachmentName = request.getParameter("attachment"); String virtualWiki = getVirtualWiki(request); File uploadPath = getEnvironment().uploadPath(virtualWiki, attachmentName); response.reset(); response.setHeader("Content-Disposition", getEnvironment().getStringSetting(Environment.PROPERTY_ATTACHMENT_TYPE) + ";filename=" + attachmentName + ";"); int dotIndex = attachmentName.indexOf('.'); if (dotIndex >= 0 && dotIndex < attachmentName.length() - 1) { String extension = attachmentName.substring(attachmentName.lastIndexOf('.') + 1); logger.fine("Extension: " + extension); String mimetype = (String) getMimeByExtension().get(extension.toLowerCase()); logger.fine("MIME: " + mimetype); if (mimetype != null) { logger.fine("Setting content type to: " + mimetype); response.setContentType(mimetype); } } FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(uploadPath); out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
|
11
|
Code Sample 1:
public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); }
Code Sample 2:
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
|
11
|
Code Sample 1:
public void copyFile(File a_fileSrc, File a_fileDest, boolean a_append) throws IOException { a_fileDest.getParentFile().mkdirs(); FileInputStream in = null; FileOutputStream out = null; FileChannel fcin = null; FileChannel fcout = null; try { in = new FileInputStream(a_fileSrc); out = new FileOutputStream(a_fileDest, a_append); fcin = in.getChannel(); fcout = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } } catch (IOException ex) { throw ex; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } } }
Code Sample 2:
public static void copyFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
|
00
|
Code Sample 1:
public static NSData sendSynchronousRequest(NSMutableURLRequest req, NSHTTPURLResponseHolder resp, NSErrorHolder error) { NSData data = null; URL url = req.URL().xmlvmGetURL(); URLConnection conn; try { conn = url.openConnection(); data = new NSData(conn.getInputStream()); } catch (IOException e) { } return data; }
Code Sample 2:
public boolean connect() { try { int reply; ftp.connect(server, port); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(username, password)) { ftp.enterLocalPassiveMode(); return true; } } else { ftp.disconnect(); System.out.println("FTP server refused connection."); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } System.out.println("Could not connect to server."); } return false; }
|
00
|
Code Sample 1:
public void load(URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("URL cannot be null."); } isFileBased = false; this.url = url; InputStream in = null; try { in = url.openStream(); load(in); } finally { if (in != null) { in.close(); } } }
Code Sample 2:
public static XMLConfigurator loadFromDefaultSystemProperty() throws IOException { String urlStr = System.getProperty(DEFAULT_SYS_PROP_NAME); if (urlStr == null || urlStr.length() == 0) { return null; } InputStream in = null; DOMRetriever xmlDoc = null; try { URL url = new URL(urlStr); xmlDoc = new DOMRetriever(in = url.openStream()); } catch (MalformedURLException e) { throw new RuntimeException(e); } finally { if (in != null) in.close(); } return newInstance(xmlDoc); }
|
11
|
Code Sample 1:
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
Code Sample 2:
public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
|
11
|
Code Sample 1:
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()); } }
Code Sample 2:
public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
Code Sample 2:
public void setPassword(UserType user, String clearPassword) { try { Random r = new Random(); String newSalt = Long.toString(Math.abs(r.nextLong())); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.reset(); md.update(newSalt.getBytes("UTF-8")); md.update(clearPassword.getBytes("UTF-8")); String encodedString = new String(Base64.encode(md.digest())); user.setPassword(encodedString); user.setSalt(newSalt); this.markModified(user); } catch (UnsupportedEncodingException ex) { logger.fatal("Your computer does not have UTF-8 support for Java installed.", ex); GlobalUITools.displayFatalExceptionMessage(null, "UTF-8 for Java not installed", ex, true); } catch (NoSuchAlgorithmException ex) { String errorMessage = "Could not use algorithm " + HASH_ALGORITHM; logger.fatal(errorMessage, ex); GlobalUITools.displayFatalExceptionMessage(null, errorMessage, ex, true); } }
|
11
|
Code Sample 1:
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()); } }
Code Sample 2:
@SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
|
11
|
Code Sample 1:
public void importCertFile(File file) throws IOException { File kd; File cd; synchronized (this) { kd = keysDir; cd = certsDir; } if (!cd.isDirectory()) { kd.mkdirs(); cd.mkdirs(); } String newName = file.getName(); File dest = new File(cd, newName); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(file).getChannel(); destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); }
|
11
|
Code Sample 1:
@Override public void render(IContentNode contentNode, Request req, Response resp, Application app, ServerInfo serverInfo) { Node fileNode = contentNode.getNode(); try { Node res = fileNode.getNode("jcr:content"); if (checkLastModified(res, req.getServletRequset(), resp.getServletResponse())) { return; } Property data = res.getProperty("jcr:data"); InputStream is = data.getBinary().getStream(); int contentLength = (int) data.getBinary().getSize(); String mime; if (res.hasProperty("jcr:mimeType")) { mime = res.getProperty("jcr:mimeType").getString(); } else { mime = serverInfo.getSerlvetContext().getMimeType(fileNode.getName()); } if (mime != null && mime.startsWith("image")) { int w = req.getInt("w", 0); int h = req.getInt("h", 0); String fmt = req.get("fmt"); if (w != 0 || h != 0 || fmt != null) { Resource imgRes = ImageResource.create(is, mime.substring(6), w, h, req.getInt("cut", 0), fmt); imgRes.process(serverInfo); return; } } resp.getServletResponse().setContentType(mime); resp.getServletResponse().setContentLength(contentLength); OutputStream os = resp.getServletResponse().getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } catch (PathNotFoundException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
Code Sample 2:
public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek (stepan@geek.cz)"); return; } } }
|
00
|
Code Sample 1:
public static String doPostEntity(String URL, List<NameValuePair> params) { try { OauthUtil util = new OauthUtil(); URI uri = new URI(URL); HttpClient httpclient = util.getNewHttpClient(); HttpPost postMethod = new HttpPost(uri); postMethod.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpclient.execute(postMethod); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); Log.i("DEBUG", "result: " + strResult); String token; try { JSONObject obj = new JSONObject(strResult); token = obj.getString("access_token"); } catch (Exception e) { token = strResult.substring(strResult.indexOf("access_token=") + 13); } return token; } } catch (Exception e) { Log.i("DEBUG", e.toString()); } return null; }
Code Sample 2:
public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
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 InputStream getResourceStream(String resource) { try { URL url = getClass().getResource(resource); System.out.println("URL: " + url); System.out.println("Read ROM " + resource); if (url == null) url = new URL(codebase + resource); return url.openConnection().getInputStream(); } catch (Exception e) { e.printStackTrace(); } return null; }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public 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(); }
Code Sample 2:
public static Map putFile(DispatchContext dctx, Map context) { Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try { localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil.returnError("ERROR: Could not open local file"); } List errorList = new ArrayList(); FTPClient ftp = new FTPClient(); try { Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add("connection refused"); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module); if (!ftp.login(username, password)) { Debug.logInfo("[putFile] login failed", module); errorList.add("Login failed (" + username + ", " + password + ")"); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add("File not sent succesfully: " + ftp.getReplyString()); } else { Debug.logInfo("[putFile] store was successful", module); List siteCommands = (List) context.get("siteCommands"); if (siteCommands != null) { Iterator ci = siteCommands.iterator(); while (ci.hasNext()) { String command = (String) ci.next(); Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add("SITE command (" + command + ") failed: " + ftp.getReplyString()); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.log(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add("Problem with FTP transfer: " + ioe.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException dce) { Debug.logWarning(dce, "[putFile] Problem with FTP disconnect", module); } } } try { localFile.close(); } catch (IOException ce) { Debug.logWarning(ce, "[putFile] Problem closing local file", module); } if (errorList.size() > 0) { Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { File inputFile = new File("D:/farrago.txt"); File outputFile = new File("D:/outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
|
11
|
Code Sample 1:
public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } }
Code Sample 2:
protected void copy(File source, File destination) throws IOException { final FileChannel inChannel = new FileInputStream(source).getChannel(); final FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
00
|
Code Sample 1:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
|
00
|
Code Sample 1:
public InputStream getEntry(String entryPath) throws IOException { if (!entries.contains(entryPath)) { return null; } JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (ze.getName().equals(entryPath)) { return jis; } } while (true); assert (false); return null; }
Code Sample 2:
private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
|
00
|
Code Sample 1:
public RawCandidate getRawCandidate(long candId) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/" + Long.toHexString(candId)); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof RawCandidate) { RawCandidate p = (RawCandidate) xmlable; return p; } else { throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for candId"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } }
Code Sample 2:
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); } if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && headers == null || !headers.containsKey("Accept-Encoding")) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = client.execute(hr, context); byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; if (code < 200 || code >= 300) { try { HttpEntity entity = response.getEntity(); byte[] s = AQUtility.toBytes(entity.getContent()); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } catch (Exception e) { AQUtility.debug(e); } } else { HttpEntity entity = response.getEntity(); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); PredefinedBAOS baos = new PredefinedBAOS(size); Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { InputStream is = new GZIPInputStream(entity.getContent()); AQUtility.copy(is, baos); } else { entity.writeTo(baos); } data = baos.toByteArray(); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).client(client).context(context).headers(response.getAllHeaders()); }
|
00
|
Code Sample 1:
protected void downloadFile(String filename, java.io.File targetFile, File partFile, ProgressMonitor monitor) throws java.io.IOException { FileOutputStream out = null; InputStream is = null; try { filename = toCanonicalFilename(filename); URL url = new URL(root + filename.substring(1)); URLConnection urlc = url.openConnection(); int i = urlc.getContentLength(); monitor.setTaskSize(i); out = new FileOutputStream(partFile); is = urlc.getInputStream(); monitor.started(); copyStream(is, out, monitor); monitor.finished(); out.close(); is.close(); if (!partFile.renameTo(targetFile)) { throw new IllegalArgumentException("unable to rename " + partFile + " to " + targetFile); } } catch (IOException e) { if (out != null) out.close(); if (is != null) is.close(); if (partFile.exists() && !partFile.delete()) { throw new IllegalArgumentException("unable to delete " + partFile); } throw e; } }
Code Sample 2:
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
00
|
Code Sample 1:
public static void run(File targetFolder, URL url) throws UpdateException { try { run(targetFolder, new ZipInputStream(url.openStream())); } catch (Exception e) { if (e instanceof UpdateException) throw (UpdateException) e; else throw new UpdateException(e); } }
Code Sample 2:
@Override public String getFeedFeed(String sUrl) { try { URL url = new URL(sUrl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String result = ""; String line; for (; (line = reader.readLine()) != null; result += line) { } reader.close(); return result; } catch (MalformedURLException e) { } catch (IOException e) { } return null; }
|
00
|
Code Sample 1:
public static String getTextFromUrl(final String url) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(HtmlUtil.quoteHtml(line)).append("\r"); } return result.toString(); } catch (final IOException exception) { return exception.getMessage(); } finally { InputOutputUtil.close(bufferedReader); InputOutputUtil.close(inputStreamReader); } }
Code Sample 2:
private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
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(); }
Code Sample 2:
private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } }
|
11
|
Code Sample 1:
private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
Code Sample 2:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
public void xtestFile1() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
Code Sample 2:
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
|
11
|
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:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); }
Code Sample 2:
public Web(String urlString, String charset) throws java.net.MalformedURLException, java.io.IOException { this.charset = charset; final java.net.URL url = new java.net.URL(urlString); final java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP."); final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(600000); conn.setReadTimeout(600000); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "spider"); conn.connect(); responseHeader = conn.getHeaderFields(); responseCode = conn.getResponseCode(); responseURL = conn.getURL(); length = conn.getContentLength(); final java.io.InputStream stream = conn.getErrorStream(); if (stream != null) { content = readStream(length, stream); } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) { content = readStream(length, (java.io.InputStream) inputStream); } conn.disconnect(); }
|
11
|
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:
private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } }
|
11
|
Code Sample 1:
protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
Code Sample 2:
@Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); }
|
11
|
Code Sample 1:
public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; }
Code Sample 2:
public void invoke(MessageContext msgContext) throws AxisFault { log.debug("Enter: MD5AttachHandler::invoke"); try { Message msg = msgContext.getRequestMessage(); SOAPConstants soapConstants = msgContext.getSOAPConstants(); org.apache.axis.message.SOAPEnvelope env = (org.apache.axis.message.SOAPEnvelope) msg.getSOAPEnvelope(); org.apache.axis.message.SOAPBodyElement sbe = env.getFirstBody(); org.w3c.dom.Element sbElement = sbe.getAsDOM(); org.w3c.dom.Node n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; org.w3c.dom.Element paramElement = (org.w3c.dom.Element) n; String href = paramElement.getAttribute(soapConstants.getAttrHref()); org.apache.axis.Part ap = msg.getAttachmentsImpl().getAttachmentByReference(href); javax.activation.DataHandler dh = org.apache.axis.attachments.AttachmentUtils.getActivationDataHandler(ap); org.w3c.dom.Node timeNode = paramElement.getFirstChild(); long startTime = -1; if (timeNode != null && timeNode instanceof org.w3c.dom.Text) { String startTimeStr = ((org.w3c.dom.Text) timeNode).getData(); startTime = Long.parseLong(startTimeStr); } long receivedTime = System.currentTimeMillis(); long elapsedTime = -1; if (startTime > 0) elapsedTime = receivedTime - startTime; String elapsedTimeStr = elapsedTime + ""; java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); java.io.InputStream attachmentStream = dh.getInputStream(); int bread = 0; byte[] buf = new byte[64 * 1024]; do { bread = attachmentStream.read(buf); if (bread > 0) { md.update(buf, 0, bread); } } while (bread > -1); attachmentStream.close(); buf = null; String contentType = dh.getContentType(); if (contentType != null && contentType.length() != 0) { md.update(contentType.getBytes("US-ASCII")); } sbe = env.getFirstBody(); sbElement = sbe.getAsDOM(); n = sbElement.getFirstChild(); for (; n != null && !(n instanceof org.w3c.dom.Element); n = n.getNextSibling()) ; paramElement = (org.w3c.dom.Element) n; String MD5String = org.apache.axis.encoding.Base64.encode(md.digest()); String senddata = " elapsedTime=" + elapsedTimeStr + " MD5=" + MD5String; paramElement.appendChild(paramElement.getOwnerDocument().createTextNode(senddata)); sbe = new org.apache.axis.message.SOAPBodyElement(sbElement); env.clearBody(); env.addBodyElement(sbe); msg = new Message(env); msgContext.setResponseMessage(msg); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); throw AxisFault.makeFault(e); } log.debug("Exit: MD5AttachHandler::invoke"); }
|
00
|
Code Sample 1:
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); }
Code Sample 2:
private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
|
00
|
Code Sample 1:
public void readData(RowSetInternal caller) throws SQLException { Connection con = null; try { CachedRowSet crs = (CachedRowSet) caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls = 0; userCon = false; con = this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch (Exception ex) { ; } PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs = pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt = con.prepareStatement(crs.getCommand(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } rs = pstmt.executeQuery(); crs.populate(rs, startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch (SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch (SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch (Exception dummy) { } con.close(); con = null; } } catch (SQLException e) { } } }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
|
00
|
Code Sample 1:
public static TerminatedInputStream find(URL url, String entryName) throws IOException { if (url.getProtocol().equals("file")) { return find(new File(url.getFile()), entryName); } else { return find(url.openStream(), entryName); } }
Code Sample 2:
public byte[] getHash(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(salt.getBytes("UTF-8")); return digest.digest(plaintext.getBytes("UTF-8")); }
|
00
|
Code Sample 1:
public String getTags(String content) { StringBuffer xml = new StringBuffer(); OutputStreamWriter osw = null; BufferedReader br = null; try { String reqData = URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(content, "UTF-8"); URL service = new URL(cmdUrl); URLConnection urlConn = service.openConnection(); urlConn.setDoOutput(true); urlConn.connect(); osw = new OutputStreamWriter(urlConn.getOutputStream()); osw.write(reqData); osw.flush(); br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = null; while ((line = br.readLine()) != null) { xml.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (osw != null) { osw.close(); } if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } return xml.toString(); }
Code Sample 2:
public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException { InputStream input = null; BufferedOutputStream bos = null; File tempUnit = null; try { URL url = null; int total = 0; try { url = new URL(urlStr); input = url.openStream(); URLConnection urlConnection; urlConnection = url.openConnection(); total = urlConnection.getContentLength(); } catch (IOException e) { throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e); } String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1); tempUnit = null; try { if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit"); File parent = tempUnit.getParentFile(); FileUtils.forceMkdir(parent); if (!tempUnit.exists()) FileUtils.touch(tempUnit); bos = new BufferedOutputStream(new FileOutputStream(tempUnit)); } catch (FileNotFoundException e) { throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (IOException e) { throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e); } catch (DeployToolException e) { throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e); } logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr)); int size = -1; try { size = IOUtils.copy(input, bos); bos.flush(); } catch (IOException e) { logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit)); } if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr)); } finally { if (input != null) IOUtils.closeQuietly(input); if (bos != null) IOUtils.closeQuietly(bos); } logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath())); return tempUnit.getAbsolutePath(); }
|
11
|
Code Sample 1:
public static ResultSet execute(String commands) { ResultSet rs = null; BufferedReader reader = new BufferedReader(new StringReader(commands)); String sqlCommand = null; Connection conn = ConnPool.getConnection(); try { Statement stmt = conn.createStatement(); while ((sqlCommand = reader.readLine()) != null) { sqlCommand = sqlCommand.toLowerCase().trim(); if (sqlCommand.equals("") || sqlCommand.startsWith("#")) { continue; } if (dmaLogger.isInfoEnabled(SqlExecutor.class)) { dmaLogger.logInfo("Executing SQL: " + sqlCommand, SqlExecutor.class); } long currentTimeMillis = System.currentTimeMillis(); if (sqlCommand.startsWith("select")) { rs = stmt.executeQuery(sqlCommand); } else { stmt.executeUpdate(sqlCommand); } dmaLogger.logInfo(DateUtil.getElapsedTime("SQL execution of " + sqlCommand + " took: ", (System.currentTimeMillis() - currentTimeMillis)), SqlExecutor.class); } if (rs == null) { stmt.close(); } return rs; } catch (SQLException e) { try { conn.rollback(); } catch (SQLException se) { } throw new RuntimeException("Execution of " + sqlCommand + " failed:" + e.getMessage(), e); } catch (IOException e) { try { conn.rollback(); } catch (SQLException se) { } throw new RuntimeException("Execution of " + sqlCommand + " failed:", e); } finally { ConnPool.releaseConnection(conn); } }
Code Sample 2:
@Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
|
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:
private void copy(File src, File dest, String name) { File srcFile = new File(src, name); File destFile = new File(dest, name); if (destFile.exists()) { if (destFile.lastModified() == srcFile.lastModified()) return; destFile.delete(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(srcFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } destFile.setLastModified(srcFile.lastModified()); }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
Code Sample 2:
private void loadConfig(ServletContext ctx, String configFileName) { Digester digester = new Digester(); digester.push(this); digester.addFactoryCreate("pagespy/server", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetProperty("pagespy/server/param", "name", "value"); digester.addSetNext("pagespy/server", "setServer", PageSpyServer.class.getName()); digester.addCallMethod("pagespy/ignored-patterns", "setIgnorePattern", 1); digester.addCallParam("pagespy/ignored-patterns", 0); digester.addFactoryCreate("pagespy/property-setters/setter", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/property-setters/setter", "addPropertySetter", PagePropertySetter.class.getName()); digester.addFactoryCreate("pagespy/page-replacers/replacer", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/page-replacers/replacer", "addPageReplacer", PageReplacer.class.getName()); digester.addFactoryCreate("pagespy/properties-panel", new AbstractObjectCreationFactory() { public Object createObject(Attributes attrs) { String className = attrs.getValue("className"); try { return Class.forName(className).newInstance(); } catch (Exception e) { throw new ClassCastException("Error al instanciar " + className); } } }); digester.addSetNext("pagespy/properties-panel", "setPropertiesPanel", PagePanel.class.getName()); try { this.getLogger().info("Initializing " + configFileName); URL url = ctx.getResource(configFileName); if (url == null) { url = this.getClass().getResource(configFileName); } digester.parse(url.openStream()); } catch (Exception e) { this.getLogger().error("Error parsing configuration file.", e); throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public void method31() { boolean flag = true; while (flag) { flag = false; for (int i = 0; i < anInt772 - 1; i++) if (anIntArray774[i] < anIntArray774[i + 1]) { int j = anIntArray774[i]; anIntArray774[i] = anIntArray774[i + 1]; anIntArray774[i + 1] = j; long l = aLongArray773[i]; aLongArray773[i] = aLongArray773[i + 1]; aLongArray773[i + 1] = l; flag = true; } } }
Code Sample 2:
private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
|
00
|
Code Sample 1:
public HttpEntity execute(final HttpRequestBase request) throws IOException, ClientProtocolException { final HttpResponse response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK | statusCode == HttpStatus.SC_CREATED) { return response.getEntity(); } return null; }
Code Sample 2:
protected void handleUrl(URL url) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; boolean moreResults = false; while ((s = in.readLine()) != null) { if (s.indexOf("<h1>Search Results</h1>") > -1) { System.err.println("found severals result"); moreResults = true; } else if (s.indexOf("Download <a href=") > -1) { if (s.indexOf("in JCAMP-DX format.") > -1) { System.err.println("download masspec"); super.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } moreResults = false; } if (moreResults == true) { if (s.indexOf("<li><a href=\"/cgi/cbook.cgi?ID") > -1) { System.err.println("\tdownloading new url " + new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); this.handleUrl(new URL((url.getProtocol() + "://" + url.getHost() + s.substring(s.indexOf("\"") + 1, s.lastIndexOf("\""))).replaceAll("amp;", ""))); } } } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) throws IOException { if (!source.isFile()) { throw new IOException(source + " is not a file."); } if (destination.exists()) { throw new IOException("Destination file " + destination + " is already exist."); } FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { inChannel.close(); outChannel.close(); } }
Code Sample 2:
public static void translateTableAttributes(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table_att", nsDefinition); String filename = baseDir + "table_att.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + "_att.xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + "_att.json", baseDir + tableName + "_att.xsl"); }
|
11
|
Code Sample 1:
public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
Code Sample 2:
private void update() { if (VERSION.contains("dev")) return; System.out.println(updateURL_s); try { URL updateURL = new URL(updateURL_s); InputStream uis = updateURL.openStream(); InputStreamReader uisr = new InputStreamReader(uis); BufferedReader ubr = new BufferedReader(uisr); String header = ubr.readLine(); if (header.equals("GENREMANUPDATEPAGE")) { String cver = ubr.readLine(); String cdl = ubr.readLine(); if (!cver.equals(VERSION)) { System.out.println("Update available!"); int i = JOptionPane.showConfirmDialog(this, Language.get("UPDATE_AVAILABLE_MSG").replaceAll("%o", VERSION).replaceAll("%c", cver), Language.get("UPDATE_AVAILABLE_TITLE"), JOptionPane.YES_NO_OPTION); if (i == 0) { URL url = new URL(cdl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() / 100 != 2) { throw new Exception("Server error! Response code: " + connection.getResponseCode()); } int contentLength = connection.getContentLength(); if (contentLength < 1) { throw new Exception("Invalid content length!"); } int size = contentLength; File tempfile = File.createTempFile("genreman_update", ".zip"); tempfile.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(tempfile, "rw"); InputStream stream = connection.getInputStream(); int downloaded = 0; ProgressWindow pwin = new ProgressWindow(this, "Downloading"); pwin.setVisible(true); pwin.setProgress(0); pwin.setText("Connecting..."); while (downloaded < size) { byte buffer[]; if (size - downloaded > 1024) { buffer = new byte[1024]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; pwin.setProgress(downloaded / size); } file.close(); System.out.println("Downloaded file to " + tempfile.getAbsolutePath()); pwin.setVisible(false); pwin.dispose(); pwin = null; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempfile)); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { File outf = new File(entry.getName()); System.out.println(outf.getAbsoluteFile()); if (outf.exists()) outf.delete(); OutputStream out = new FileOutputStream(outf); byte[] buf = new byte[1024]; int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } JOptionPane.showMessageDialog(this, Language.get("UPDATE_SUCCESS_MSG"), Language.get("UPDATE_SUCCESS_TITLE"), JOptionPane.INFORMATION_MESSAGE); setVisible(false); if (System.getProperty("os.name").indexOf("Windows") != -1) { Runtime.getRuntime().exec("iTunesGenreArtManager.exe"); } else { Runtime.getRuntime().exec("java -jar \"iTunes Genre Art Manager.app/Contents/Resources/Java/iTunes_Genre_Art_Manager.jar\""); } System.exit(0); } else { } } ubr.close(); uisr.close(); uis.close(); } else { while (ubr.ready()) { System.out.println(ubr.readLine()); } ubr.close(); uisr.close(); uis.close(); throw new Exception("Update page had invalid header: " + header); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, Language.get("UPDATE_ERROR_MSG"), Language.get("UPDATE_ERROR_TITLE"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } }
|
00
|
Code Sample 1:
public boolean delMail(MailObject mail) throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_MAIL_DEL + mail.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
Code Sample 2:
public static String download(String urlStr, String folder, String title) { String result = ""; try { long startTime = System.currentTimeMillis(); URL url = new URL(urlStr); url.openConnection(); InputStream reader = url.openStream(); FileOutputStream writer = new FileOutputStream(folder + File.separator + title); byte[] buffer = new byte[1024 * 1024]; int totalBytesRead = 0; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) > 0) { writer.write(buffer, 0, bytesRead); buffer = new byte[153600]; totalBytesRead += bytesRead; } long endTime = System.currentTimeMillis(); result = "Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n"; writer.close(); reader.close(); } catch (Exception e) { result = "Can not download. " + folder + File.separator + title + ":\n" + e.getMessage(); } return result; }
|
11
|
Code Sample 1:
public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static void copy(File src, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); }
|
11
|
Code Sample 1:
private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public static void copyFile(File src, String srcEncoding, File dest, String destEncoding) throws IOException { InputStreamReader in = new InputStreamReader(new FileInputStream(src), srcEncoding); OutputStreamWriter out = new OutputStreamWriter(new RobustFileOutputStream(dest), destEncoding); int c; while ((c = in.read()) != -1) out.write(c); out.flush(); in.close(); out.close(); }
|
11
|
Code Sample 1:
private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; }
Code Sample 2:
public static void setFinishedFlag(String ip, String port, String user, String dbname, String password, int flag) throws Exception { String sql = "update flag set flag = " + flag; Connection conn = CubridDBCenter.getConnection(ip, port, dbname, user, password); System.out.println("====:::===" + ip); Statement stmt = null; try { conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate(sql); conn.commit(); } catch (Exception ex) { ex.printStackTrace(); conn.rollback(); throw ex; } finally { stmt.close(); conn.close(); } }
|
11
|
Code Sample 1:
public GEItem lookup(final int itemID) { try { URL url = new URL(GrandExchange.HOST + GrandExchange.GET + itemID); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String input; boolean exists = false; int i = 0; double[] values = new double[4]; String name = "", examine = ""; while ((input = br.readLine()) != null) { if (input.contains("<div class=\"brown_box main_ge_page") && !exists) { if (!input.contains("vertically_spaced")) { return null; } exists = true; br.readLine(); br.readLine(); name = br.readLine(); } else if (input.contains("<img id=\"item_image\" src=\"")) { examine = br.readLine(); } else if (input.matches("(?i).+ (price|days):</b> .+")) { values[i] = parse(input); i++; } else if (input.matches("<div id=\"legend\">")) break; } return new GEItem(name, examine, itemID, values); } catch (IOException ignore) { } return null; }
Code Sample 2:
private void readParameterTable() { if (this.parameters != null) return; parameters = new GribPDSParameter[NPARAMETERS]; int center; int subcenter; int number; try { BufferedReader br; if (filename != null && filename.length() > 0) { GribPDSParamTable tab = (GribPDSParamTable) fileTabMap.get(filename); if (tab != null) { this.parameters = tab.parameters; return; } } if (url != null) { InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); } else { br = new BufferedReader(new FileReader("tables\\" + filename)); } String line = br.readLine(); String[] tableDefArr = SmartStringArray.split(":", line); center = Integer.parseInt(tableDefArr[1].trim()); subcenter = Integer.parseInt(tableDefArr[2].trim()); number = Integer.parseInt(tableDefArr[3].trim()); while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() == 0 || line.startsWith("//")) continue; GribPDSParameter parameter = new GribPDSParameter(); tableDefArr = SmartStringArray.split(":", line); parameter.number = Integer.parseInt(tableDefArr[0].trim()); parameter.name = tableDefArr[1].trim(); if (tableDefArr[2].indexOf('[') == -1) { parameter.description = parameter.unit = tableDefArr[2].trim(); } else { String[] arr2 = SmartStringArray.split("[", tableDefArr[2]); parameter.description = arr2[0].trim(); parameter.unit = arr2[1].substring(0, arr2[1].lastIndexOf(']')).trim(); } if (!this.setParameter(parameter)) { System.err.println("Warning, bad parameter ignored (" + filename + "): " + parameter.toString()); } } if (filename != null && filename.length() > 0) { GribPDSParamTable loadedTable = new GribPDSParamTable(filename, center, subcenter, number, this.parameters); fileTabMap.put(filename, loadedTable); } } catch (IOException ioError) { System.err.println("An error occurred in GribPDSParamTable while " + "trying to open the parameter table " + filename + " : " + ioError); } }
|
00
|
Code Sample 1:
public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } }
Code Sample 2:
public void testDigest() { try { String myinfo = "我的测试信息"; MessageDigest alga = MessageDigest.getInstance("SHA-1"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); System.out.println("本信息摘要是:" + byte2hex(digesta)); MessageDigest algb = MessageDigest.getInstance("SHA-1"); algb.update(myinfo.getBytes()); if (MessageDigest.isEqual(digesta, algb.digest())) { System.out.println("信息检查正常"); } else { System.out.println("摘要不相同"); } } catch (NoSuchAlgorithmException ex) { System.out.println("非法摘要算法"); } }
|
00
|
Code Sample 1:
protected void init() { if (this.strUrl != null) { InputStream in = null; try { URL url = ClassLoader.getSystemClassLoader().getResource(strUrl); if (url != null) { in = url.openStream(); if (in != null) { props.load(in); } } } catch (IOException e) { Logger.defaultLogger().error("Error during framework properties loading", e); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } }
Code Sample 2:
public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); }
|
11
|
Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
@Override public void dispatchContent(InputStream is) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Sending content message over JMS"); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); this.send(new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { BytesMessage message = session.createBytesMessage(); message.writeBytes(bos.toByteArray()); return message; } }); }
|
00
|
Code Sample 1:
private void downloadFtp(File file, URL jurl) throws SocketException, IOException { System.out.println("downloadFtp(" + file + ", " + jurl + ")"); FTPClient client = new FTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } }); try { client.connect(jurl.getHost(), -1 == jurl.getPort() ? FTP.DEFAULT_PORT : jurl.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new IOException("FTP server refused connection."); } if (!client.login("anonymous", "anonymous")) { client.logout(); throw new IOException("Authentication failure."); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); FileOutputStream out = new FileOutputStream(file); boolean ok = client.retrieveFile(jurl.getPath(), out); out.close(); client.logout(); if (!ok) { throw new IOException("File transfer failure."); } } catch (IOException e) { throw e; } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } }
Code Sample 2:
private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public void compareResult(String path, String expected) throws IOException { if (path.length() == 0 || path.charAt(0) != '/') path = "/" + path; URL url = new URL(getBase() + path); String actual = IOUtils.toString(url.openStream()); Assert.assertEquals(url.toString(), expected, actual); }
Code Sample 2:
@Override public boolean register(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); try { if (this.getDbServ().queryFeelerUser(username) != null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); this.getDbServ().addFeelerUser(username, passwordMd5); return this.identification(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; }
Code Sample 2:
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(); }
|
00
|
Code Sample 1:
public String crypt(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
Code Sample 2:
private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public List tree(String cat, int branch) { Pattern p = Pattern.compile("<a href=\"javascript:checkBranch\\(([0-9]+), 'true'\\)\">([^<]*)</a>"); Matcher m; List res = new ArrayList(); URL url; HttpURLConnection conn; System.out.println(); try { url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?category=trainee&expand=false&forceLoad=false&reload=false&scroll=0"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Cookie", sessionId); BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = i.readLine()) != null) { m = p.matcher(line); if (m.find()) { trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2))); System.out.println(m.group(1) + " - " + m.group(2)); } } } catch (Exception e2) { e2.printStackTrace(); } return res; }
Code Sample 2:
public static void loadFile(final URL url, final StringBuffer buffer) throws IOException { InputStream in = null; BufferedReader dis = null; try { in = url.openStream(); dis = new BufferedReader(new InputStreamReader(in)); int i; while ((i = dis.read()) != -1) { buffer.append((char) i); } } finally { closeStream(in); closeReader(dis); } }
|
00
|
Code Sample 1:
public static void copyFile6(File srcFile, File destFile) throws FileNotFoundException { Scanner s = new Scanner(srcFile); PrintWriter pw = new PrintWriter(destFile); while(s.hasNextLine()) { pw.println(s.nextLine()); } pw.close(); s.close(); }
Code Sample 2:
private void storeFieldMap(WorkingContent c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); try { if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } finally { if (ps != null) ps.close(); } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } }
|
00
|
Code Sample 1:
private static void init() { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> enumeration = cl.getResources("extension-services.properties"); do { if (!enumeration.hasMoreElements()) break; URL url = (URL) enumeration.nextElement(); System.out.println(" - " + url); try { props = new Properties(); props.load(url.openStream()); } catch (Exception e) { e.printStackTrace(); } } while (true); } 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 SetRoles(Connection conn, User user, String[] roles) throws NpsException { if (!IsSysAdmin() && !IsLocalAdmin()) throw new NpsException(ErrorHelper.ACCESS_NOPRIVILEGE); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "delete from userrole where userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); pstmt.executeUpdate(); if (roles != null && roles.length > 0) { try { pstmt.close(); } catch (Exception e1) { } sql = "insert into userrole(userid,roleid) values(?,?)"; pstmt = conn.prepareStatement(sql); for (int i = 0; i < roles.length; i++) { if (roles[i] != null && roles[i].length() > 0) { pstmt.setString(1, user.GetId()); pstmt.setString(2, roles[i]); pstmt.executeUpdate(); } } } try { pstmt.close(); } catch (Exception e1) { } if (user.roles_by_name != null) user.roles_by_name.clear(); if (user.roles_by_id != null) user.roles_by_id.clear(); if (roles != null && roles.length > 0) { sql = "select b.* from UserRole a,Role b where a.roleid = b.id and a.userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); rs = pstmt.executeQuery(); while (rs.next()) { if (user.roles_by_name == null) user.roles_by_name = new Hashtable(); if (user.roles_by_id == null) user.roles_by_id = new Hashtable(); user.roles_by_name.put(rs.getString("name"), rs.getString("id")); user.roles_by_id.put(rs.getString("id"), rs.getString("name")); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { } nps.util.DefaultLog.error(e); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (pstmt != null) try { pstmt.close(); } catch (Exception e1) { } } }
Code Sample 2:
public static void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException { log.debug("Start MemberPortletActionMethod.processAction()"); MemberProcessingActionRequest mp = null; try { ModuleManager moduleManager = ModuleManager.getInstance(PropertiesProvider.getConfigPath()); mp = new MemberProcessingActionRequest(actionRequest, moduleManager); String moduleName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_MODULE_PARAM); String actionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_ACTION_PARAM); String subActionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_SUBACTION_PARAM).trim(); if (log.isDebugEnabled()) { Map parameterMap = actionRequest.getParameterMap(); if (!parameterMap.entrySet().isEmpty()) { log.debug("Action request parameter"); for (Object o : parameterMap.entrySet()) { Map.Entry entry = (Map.Entry) o; log.debug(" key: " + entry.getKey() + ", value: " + entry.getValue()); } } else { log.debug("Action request map is empty"); } log.debug(" Point #4.1 module '" + moduleName + "'"); log.debug(" Point #4.2 action '" + actionName + "'"); log.debug(" Point #4.3 subAction '" + subActionName + "'"); } if (mp.mod == null) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.2. Module '" + moduleName + "' not found"); return; } if (mp.mod.getType() != null && mp.mod.getType().getType() == ModuleTypeTypeType.LOOKUP_TYPE && (mp.getFromParam() == null || mp.getFromParam().length() == 0)) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.4. Module " + moduleName + " is lookup module"); return; } int actionType = ContentTypeActionType.valueOf(actionName).getType(); if (log.isDebugEnabled()) { log.debug("action name " + actionName); log.debug("ContentTypeActionType " + ContentTypeActionType.valueOf(actionName).toString()); log.debug("action type " + actionType); } mp.content = MemberServiceClass.getContent(mp.mod, actionType); if (mp.content == null) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Module: '" + moduleName + "', action '" + actionName + "', not found"); return; } if (log.isDebugEnabled()) { log.debug("Debug. Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-0.xml", "windows-1251"); } } if (!MemberServiceClass.checkRole(actionRequest, mp.content)) { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Access denied"); return; } if (log.isDebugEnabled()) { log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-2.xml", "windows-1251"); } } initRenderParameters(actionRequest.getParameterMap(), actionResponse); if ("commit".equalsIgnoreCase(subActionName)) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = mp.getDatabaseAdapter(); int i1; switch(actionType) { case ContentTypeActionType.INSERT_TYPE: if (log.isDebugEnabled()) log.debug("Start prepare data for inserting."); String validateStatus = mp.validateFields(dbDyn); if (log.isDebugEnabled()) log.debug("Validating status - " + validateStatus); if (validateStatus != null) { WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); return; } if (log.isDebugEnabled()) { log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-before-yesno.xml", "windows-1251"); } } if (log.isDebugEnabled()) log.debug("Start looking for field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString()); if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) { if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString()); mp.process_Yes_1_No_N_Fields(dbDyn); } else { if (log.isDebugEnabled()) log.debug("Field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString() + " not found"); } String sql_ = MemberServiceClass.buildInsertSQL(mp.content, mp.getFromParam(), mp.mod, dbDyn, actionRequest.getServerName(), mp.getModuleManager(), mp.authSession); if (log.isDebugEnabled()) { log.debug("insert SQL:\n" + sql_ + "\n"); log.debug("Unmarshal sqlCache object"); synchronized (syncFile) { XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content.xml", "windows-1251"); } } boolean checkStatus = false; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: checkStatus = mp.checkRestrict(); if (!checkStatus) throw new ServletException("check status of restrict failed"); break; } if (log.isDebugEnabled()) log.debug("check status - " + checkStatus); ps = dbDyn.prepareStatement(sql_); Object idNewRec = mp.bindInsert(dbDyn, ps); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of inserter record - " + i1); DatabaseManager.close(ps); ps = null; if (log.isDebugEnabled()) { outputDebugOfInsertStatus(mp, dbDyn, idNewRec); } mp.prepareBigtextData(dbDyn, idNewRec, false); for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.003 terminate class " + rc.getClassName()); CacheFactory.terminate(rc.getClassName(), null, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } break; case ContentTypeActionType.CHANGE_TYPE: if (log.isDebugEnabled()) log.debug("Commit change page"); validateStatus = mp.validateFields(dbDyn); if (validateStatus != null) { WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); return; } if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) { if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N); mp.process_Yes_1_No_N_Fields(dbDyn); } Object idCurrRec; if (log.isDebugEnabled()) log.debug("PrimaryKeyType " + mp.content.getQueryArea().getPrimaryKeyType()); switch(mp.content.getQueryArea().getPrimaryKeyType().getType()) { case PrimaryKeyTypeType.NUMBER_TYPE: log.debug("PrimaryKeyType - 'number'"); idCurrRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); break; case PrimaryKeyTypeType.STRING_TYPE: log.debug("PrimaryKeyType - 'string'"); idCurrRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); break; default: throw new Exception("Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); } if (log.isDebugEnabled()) log.debug("mp.isSimpleField(): " + mp.isSimpleField()); if (mp.isSimpleField()) { log.debug("start build SQL"); sql_ = MemberServiceClass.buildUpdateSQL(dbDyn, mp.content, mp.getFromParam(), mp.mod, true, actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), mp.getModuleManager(), mp.authSession); if (log.isDebugEnabled()) log.debug("update SQL:" + sql_); ps = dbDyn.prepareStatement(sql_); mp.bindUpdate(dbDyn, ps, idCurrRec, true); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of updated record - " + i1); } log.debug("prepare big text"); mp.prepareBigtextData(dbDyn, idCurrRec, true); if (mp.content.getQueryArea().getPrimaryKeyType().getType() != PrimaryKeyTypeType.NUMBER_TYPE) throw new Exception("PK of 'Bigtext' table must be a 'number' type"); log.debug("start sync cache data"); for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.002 terminate class " + rc.getClassName() + ", id_rec " + idCurrRec); if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) { CacheFactory.terminate(rc.getClassName(), (Long) idCurrRec, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } else { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); return; } } break; case ContentTypeActionType.DELETE_TYPE: log.debug("Commit delete page<br>"); Object idRec; if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) { idRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); } else if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.STRING_TYPE) { idRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey()); } else { actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Delete. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType()); return; } if (dbDyn.getFamaly() == DatabaseManager.MYSQL_FAMALY) mp.deleteBigtextData(dbDyn, idRec); sql_ = MemberServiceClass.buildDeleteSQL(dbDyn, mp.mod, mp.content, mp.getFromParam(), actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), moduleManager, mp.authSession); if (log.isDebugEnabled()) log.debug("delete SQL: " + sql_ + "<br>\n"); ps = dbDyn.prepareStatement(sql_); mp.bindDelete(ps); i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of deleted record - " + i1); if (idRec != null && (idRec instanceof Long)) { for (int i = 0; i < mp.mod.getRelateClassCount(); i++) { RelateClassType rc = mp.mod.getRelateClass(i); if (log.isDebugEnabled()) log.debug("#7.003.001 terminate class " + rc.getClassName() + ", id_rec " + idRec.toString()); CacheFactory.terminate(rc.getClassName(), (Long) idRec, Boolean.TRUE.equals(rc.getIsFullReinitCache())); } } break; default: actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Unknown type of action - " + actionName); return; } log.debug("do commit"); dbDyn.commit(); } catch (Exception e1) { try { dbDyn.rollback(); } catch (Exception e001) { log.info("error in rolback()"); } log.error("Error while processing this page", e1); if (dbDyn.testExceptionIndexUniqueKey(e1)) { WebmillErrorPage.setErrorInfo(actionResponse, "You input value already exists in DB. Try again with other value", MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME); } else { WebmillErrorPage.setErrorInfo(actionResponse, "Error while processing request", MemberConstants.ERROR_TEXT, e1, "Continue", MemberConstants.ERROR_URL_NAME); } } finally { DatabaseManager.close(dbDyn, ps); } } } catch (Exception e) { final String es = "General processing error "; log.error(es, e); throw new PortletException(es, e); } finally { if (mp != null) { mp.destroy(); } } }
|
00
|
Code Sample 1:
private void fetchAvailable(ProgressObserver po) { if (po == null) throw new IllegalArgumentException("the progress observer can't be null"); if (availables == null) availables = new ArrayList<Dictionary>(); else availables.clear(); if (installed == null) initInstalled(); File home = SpellCheckPlugin.getHomeDir(jEdit.getActiveView()); File target = new File(home, "available.lst"); try { boolean skipDownload = false; if (target.exists()) { long modifiedDate = target.lastModified(); Calendar c = Calendar.getInstance(); c.setTimeInMillis(modifiedDate); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.HOUR, -1); skipDownload = yesterday.before(c); } String enc = null; if (!skipDownload) { URL available_url = new URL(jEdit.getProperty(OOO_DICTS_PROP) + "available.lst"); URLConnection connect = available_url.openConnection(); connect.connect(); InputStream is = connect.getInputStream(); po.setMaximum(connect.getContentLength()); OutputStream os = new FileOutputStream(target); boolean copied = IOUtilities.copyStream(po, is, os, true); if (!copied) { Log.log(Log.ERROR, HunspellDictsManager.class, "Unable to download " + available_url.toString()); GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { "Unable to download file " + available_url.toString() }); availables = null; if (target.exists()) target.delete(); return; } IOUtilities.closeQuietly(os); enc = connect.getContentEncoding(); } FileInputStream fis = new FileInputStream(target); Reader r; if (enc != null) { try { r = new InputStreamReader(fis, enc); } catch (UnsupportedEncodingException uee) { r = new InputStreamReader(fis, "UTF-8"); } } else { r = new InputStreamReader(fis, "UTF-8"); } BufferedReader br = new BufferedReader(r); for (String line = br.readLine(); line != null; line = br.readLine()) { Dictionary d = parseLine(line); if (d != null) { int ind = installed.indexOf(d); if (ind == -1) { d.installed = false; availables.add(d); } else { Dictionary id = installed.get(ind); if (!skipDownload) { Date lmd = fetchLastModifiedDate(id.archiveName); if (lmd != null) { id.lastModified = lmd; } } } } } IOUtilities.closeQuietly(fis); } catch (IOException ioe) { if (ioe instanceof UnknownHostException) { GUIUtilities.error(null, "spell-check-hunspell-error-unknownhost", new String[] { ioe.getMessage() }); } else { GUIUtilities.error(null, "spell-check-hunspell-error-fetch", new String[] { ioe.getMessage() }); } ioe.printStackTrace(); if (target.exists()) target.delete(); } }
Code Sample 2:
public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
|
00
|
Code Sample 1:
@Override public void remove(int disciplinaId) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "delete from Disciplina where id = ?"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setInt(1, disciplinaId); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
Code Sample 2:
public Document createDocument(String uri) throws IOException { ParsedURL purl = new ParsedURL(uri); InputStream is = purl.openStream(MimeTypeConstants.MIME_TYPES_SVG); InputSource isrc = new InputSource(is); String contentType = purl.getContentType(); int cindex = -1; if (contentType != null) { contentType = contentType.toLowerCase(); cindex = contentType.indexOf(HTTP_CHARSET); } if (cindex != -1) { int i = cindex + HTTP_CHARSET.length(); int eqIdx = contentType.indexOf('=', i); if (eqIdx != -1) { eqIdx++; String charset; int idx = contentType.indexOf(',', eqIdx); int semiIdx = contentType.indexOf(';', eqIdx); if ((semiIdx != -1) && ((semiIdx < idx) || (idx == -1))) idx = semiIdx; if (idx != -1) charset = contentType.substring(eqIdx, idx); else charset = contentType.substring(eqIdx); isrc.setEncoding(charset.trim()); } } isrc.setSystemId(uri); Document doc = super.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", uri, isrc); try { ((SVGOMDocument) doc).setURLObject(new URL(purl.toString())); } catch (MalformedURLException mue) { throw new IOException("Malformed URL: " + uri); } return doc; }
|
00
|
Code Sample 1:
private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } }
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 void postProcess() throws StopWriterVisitorException { dxfWriter.postProcess(); try { FileChannel fcinDxf = new FileInputStream(fTemp).getChannel(); FileChannel fcoutDxf = new FileOutputStream(m_Fich).getChannel(); DriverUtilities.copy(fcinDxf, fcoutDxf); fTemp.delete(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } }
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.setVisible(true); 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.setVisible(true); 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.setVisible(true); } { 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.setVisible(true); 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.setVisible(true); } { 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 void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static String md5hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { LOG.error(e); } return null; }
Code Sample 2:
public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static List importSymbol(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws IOException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); QuoteFilter filter = new YahooQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { Quote quote = filter.toQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (ConnectException e) { DesktopManager.showErrorMessage(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); throw new IOException(); } catch (UnknownHostException e) { DesktopManager.showErrorMessage(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); throw new IOException(); } catch (NoRouteToHostException e) { DesktopManager.showErrorMessage(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); throw new IOException(); } catch (MalformedURLException e) { DesktopManager.showErrorMessage(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); throw new IOException(); } catch (FileNotFoundException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + Locale.getString("NO_QUOTES_FOUND")); } catch (IOException e) { DesktopManager.showErrorMessage(Locale.getString("ERROR_DOWNLOADING_QUOTES")); throw new IOException(); } return quotes; }
|
00
|
Code Sample 1:
public ICCColorSpaceExt createICCColorSpaceExt(BridgeContext ctx, Element paintedElement, String iccProfileName) { ICCColorSpaceExt cs = cache.request(iccProfileName.toLowerCase()); if (cs != null) { return cs; } Document doc = paintedElement.getOwnerDocument(); NodeList list = doc.getElementsByTagNameNS(SVG_NAMESPACE_URI, SVG_COLOR_PROFILE_TAG); int n = list.getLength(); Element profile = null; for (int i = 0; i < n; i++) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element profileNode = (Element) node; String nameAttr = profileNode.getAttributeNS(null, SVG_NAME_ATTRIBUTE); if (iccProfileName.equalsIgnoreCase(nameAttr)) { profile = profileNode; } } } if (profile == null) return null; String href = XLinkSupport.getXLinkHref(profile); ICC_Profile p = null; if (href != null) { String baseURI = ((SVGOMDocument) doc).getURL(); ParsedURL purl = new ParsedURL(baseURI, href); if (!purl.complete()) throw new BridgeException(paintedElement, ERR_URI_MALFORMED, new Object[] { href }); try { ParsedURL pDocURL = null; if (baseURI != null) { pDocURL = new ParsedURL(baseURI); } ctx.getUserAgent().checkLoadExternalResource(purl, pDocURL); p = ICC_Profile.getInstance(purl.openStream()); } catch (IOException e) { throw new BridgeException(paintedElement, ERR_URI_IO, new Object[] { href }); } catch (SecurityException e) { throw new BridgeException(paintedElement, ERR_URI_UNSECURE, new Object[] { href }); } } if (p == null) { return null; } int intent = convertIntent(profile); cs = new ICCColorSpaceExt(p, intent); cache.put(iccProfileName.toLowerCase(), cs); return cs; }
Code Sample 2:
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); }
|
00
|
Code Sample 1:
private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); }
Code Sample 2:
private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } }
|
11
|
Code Sample 1:
private void fileCopier(String filenameFrom, String filenameTo) { FileInputStream fromStream = null; FileOutputStream toStream = null; try { fromStream = new FileInputStream(new File(filenameFrom)); if (new File(filenameTo).exists()) { new File(filenameTo).delete(); } File dirr = new File(getContactPicPath()); if (!dirr.exists()) { dirr.mkdir(); } toStream = new FileOutputStream(new File(filenameTo)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fromStream.read(buffer)) != -1) toStream.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { Errmsg.errmsg(e); } catch (IOException e) { Errmsg.errmsg(e); } finally { try { if (fromStream != null) { fromStream.close(); } if (toStream != null) { toStream.close(); } } catch (IOException e) { Errmsg.errmsg(e); } } }
Code Sample 2:
private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
|
00
|
Code Sample 1:
public static boolean isAnimated(Icon icon) { if (icon instanceof ImageIcon) { Image image = ((ImageIcon) icon).getImage(); if (image != null) { Object comment = image.getProperty("comment", null); if (String.valueOf(comment).startsWith("GifBuilder")) return true; if (decoded.containsKey(image)) { return Boolean.TRUE.equals(decoded.get(image)); } InputStream is = null; try { URL url = new URL(icon.toString()); is = url.openConnection().getInputStream(); } catch (Exception e) { e.printStackTrace(); } if (is == null) { try { ImageProducer p = image.getSource(); if (p instanceof InputStreamImageSource) { Method m = InputStreamImageSource.class.getDeclaredMethod("getDecoder", null); m.setAccessible(true); ImageDecoder d = (ImageDecoder) m.invoke(p, null); if (d instanceof GifImageDecoder) { GifImageDecoder gd = (GifImageDecoder) d; Field input = ImageDecoder.class.getDeclaredField("input"); input.setAccessible(true); is = (InputStream) input.get(gd); } } } catch (Exception e) { e.printStackTrace(); } } if (is != null) { GifDecoder decoder = new GifDecoder(); decoder.read(is); boolean animated = decoder.getFrameCount() > 1; decoded.put(image, Boolean.valueOf(animated)); return animated; } } return false; } return icon instanceof AnimatedIcon; }
Code Sample 2:
public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int totalBytes = 0; int dlBytes = 0; try { if (!Main.Updates.current.hasFile(rawClass)) { Main.Updates.current.addFile(newVer, newStage, rawClass); } Main.Updates.current.getFile(rawClass).downloading = true; Main.Updates.setImage(rawClass, "refresh.png"); java.io.File folder = new java.io.File(localFileName); folder.createNewFile(); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); totalBytes = conn.getContentLength(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; double incr = java.lang.Math.floor(totalBytes / 1000); Main.Interface.Update.prgStatus.setMaximum(1000); Main.Interface.Update.prgStatus.setString("0.0%"); while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; dlBytes += numRead; int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000); Main.Interface.Update.prgStatus.setValue(newVal); Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%"); } Main.Updates.current.getFile(rawClass).downloading = false; Main.Updates.current.getFile(rawClass).version = newVer; Main.Updates.current.getFile(rawClass).stage = newStage; Main.Updates.setImage(rawClass, "updater.png"); Main.Updates.updateTable(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ioe) { } } }
|
00
|
Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); }
Code Sample 2:
public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); }
|
00
|
Code Sample 1:
@Override public void execute(IAlert alert, IReport report, Rule rule, Row row) { try { URL url = new URL(getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(getTimeout()); con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write(formatOutput(report, alert, rule, row).getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder input = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { input.append(line); input.append('\n'); } in.close(); this.lastResult = input.toString(); } catch (Throwable e) { logError("Error sending alert", e); if (!isHeadless()) { alert.setEnabled(false); JOptionPane.showMessageDialog(null, "Can't send alert " + e + "\n" + alert.getName() + " alert disabled.", "Action Error", JOptionPane.ERROR_MESSAGE); } } }
Code Sample 2:
public boolean exists(String filename) { String localFileName = (java.io.File.separatorChar != '/') ? filename.replace('/', java.io.File.separatorChar) : filename; for (int i = 0; i < dirs.length; i++) { if (zipEntries[i] != null) { if (zipEntries[i].get(filename) != null) return true; String dir = ""; String name = filename; int index = filename.lastIndexOf('/'); if (index >= 0) { dir = filename.substring(0, index); name = filename.substring(index + 1); } Vector directory = (Vector) zipEntries[i].get(dir); if (directory != null && directory.contains(name)) return true; continue; } if (bases[i] != null) { try { URL url = new URL(bases[i], filename); URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; } catch (IOException ex) { } continue; } if (dirs[i] == null) continue; if (zips[i] != null) { String fullname = zipDirs[i] != null ? zipDirs[i] + filename : filename; ZipEntry ze = zips[i].getEntry(fullname); if (ze != null) return true; } else { try { File f = new File(dirs[i], localFileName); if (f.exists()) return true; } catch (SecurityException ex) { } } } return false; }
|
11
|
Code Sample 1:
private static void unzipEntry(final ZipFile zipfile, final ZipEntry entry, final File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
Code Sample 2:
public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
|
00
|
Code Sample 1:
public ReqJsonContent(String useragent, String urlstr, String domain, String pathinfo, String alarmMessage) throws IOException { URL url = new URL(urlstr); URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", useragent); conn.setRequestProperty("pathinfo", pathinfo); conn.setRequestProperty("domain", domain); try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8")); response = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); jsonContectResult = response.toString(); } catch (SocketTimeoutException e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } catch (Exception e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } }
Code Sample 2:
private static void init() { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> enumeration = cl.getResources("extension-services.properties"); do { if (!enumeration.hasMoreElements()) break; URL url = (URL) enumeration.nextElement(); System.out.println(" - " + url); try { props = new Properties(); props.load(url.openStream()); } catch (Exception e) { e.printStackTrace(); } } while (true); } catch (IOException e) { } }
|
11
|
Code Sample 1:
public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } }
Code Sample 2:
public static String hashMD5(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
|
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(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
|
00
|
Code Sample 1:
private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); }
Code Sample 2:
private void createSaveServiceProps() throws MojoExecutionException { saveServiceProps = new File(workDir, "saveservice.properties"); try { FileWriter out = new FileWriter(saveServiceProps); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("saveservice.properties"), out); out.flush(); out.close(); System.setProperty("saveservice_properties", File.separator + "target" + File.separator + "jmeter" + File.separator + "saveservice.properties"); } catch (IOException e) { throw new MojoExecutionException("Could not create temporary saveservice.properties", e); } }
|
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 void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
11
|
Code Sample 1:
public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); }
Code Sample 2:
private String getMAC(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
00
|
Code Sample 1:
public static String encrypt(String plainText) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static Image readImage(URL url, ImageMimeType type, int page) throws IOException { if (type.javaNativeSupport()) { return ImageIO.read(url.openStream()); } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) { com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url); doc.setAsync(false); DjVuPage[] p = new DjVuPage[1]; int size = doc.size(); if ((page != 0) && (page >= size)) { page = 0; } p[0] = doc.getPage(page, 1, true); p[0].setAsync(false); DjVuImage djvuImage = new DjVuImage(p, true); Rectangle pageBounds = djvuImage.getPageBounds(0); Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height)); if (images.length == 1) { Image img = images[0]; return img; } else return null; } else if (type.equals(ImageMimeType.PDF)) { PDDocument document = null; try { document = PDDocument.load(url.openStream()); int resolution = 96; List<?> pages = document.getDocumentCatalog().getAllPages(); PDPage pdPage = (PDPage) pages.get(page); BufferedImage image = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, resolution); return image; } finally { if (document != null) { document.close(); } } } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'"); }
|
00
|
Code Sample 1:
private void harvest() throws IOException, XMLStreamException { String api_url = "http://search.twitter.com/search.atom?q=+%23" + hashtag + "+to%3A" + account; System.err.println(api_url); URL url = new URL(api_url); URLConnection con = url.openConnection(); String basic = this.login + ":" + new String(this.password); con.setRequestProperty("Authorization", "Basic " + Base64.encode(basic)); XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); factory.setProperty(XMLInputFactory.IS_VALIDATING, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); XMLEventReader reader = factory.createXMLEventReader(con.getInputStream()); boolean inEntry = false; boolean inAuthor = false; String published = null; String title = null; String foafName = null; String foafURI = null; String link = null; while (reader.hasNext()) { XMLEvent evt = reader.nextEvent(); if (evt.isStartElement()) { StartElement e = evt.asStartElement(); QName qName = e.getName(); if (!inEntry && Atom.NS.equals(qName.getNamespaceURI()) && qName.getLocalPart().equals("entry")) { inEntry = true; } else if (inEntry) { String local = qName.getLocalPart(); if (local.equals("published")) { published = reader.getElementText(); } else if (local.equals("title")) { title = reader.getElementText(); } else if (link == null && local.equals("link")) { Attribute att = e.getAttributeByName(new QName("type")); if (att != null && att.getValue().equals("text/html")) { att = e.getAttributeByName(new QName("href")); if (att != null) { link = att.getValue(); } } } else if (local.equals("author")) { inAuthor = true; } else if (inAuthor && local.equals("name")) { foafName = reader.getElementText(); } else if (inAuthor && local.equals("uri")) { foafURI = reader.getElementText(); } } } else if (evt.isEndElement()) { EndElement e = evt.asEndElement(); QName qName = e.getName(); if (inEntry && Atom.NS.equals(qName.getNamespaceURI())) { String local = qName.getLocalPart(); if (local.equals("entry")) { Protein p1 = null; Protein p2 = null; PubmedEntry pubmed = null; boolean valid = title != null && published != null; String tokens[] = title == null ? new String[0] : title.trim().split("[ \t\n\r]+"); if (valid && tokens.length != 5) { System.err.println("Ignoring " + title); valid = false; } if (valid && !tokens[0].equals("@" + account)) { System.err.println("Ignoring " + title + " doesn't start with @" + account); valid = false; } if (valid && !(tokens[1].startsWith("gi:") && Cast.Integer.isA(tokens[1].substring(3)))) { System.err.println("Ignoring " + title + " not a gi:###"); valid = false; } if (valid && (p1 = fetchProtein(Integer.parseInt(tokens[1].substring(3)))) == null) { valid = false; } if (valid && !(tokens[2].startsWith("gi:") && Cast.Integer.isA(tokens[2].substring(3)))) { System.err.println("Ignoring " + title + " not a gi:###"); valid = false; } if (valid && (p2 = fetchProtein(Integer.parseInt(tokens[2].substring(3)))) == null) { valid = false; } if (valid && !(tokens[3].startsWith("pmid:") && Cast.Integer.isA(tokens[3].substring(5)))) { System.err.println("Ignoring " + title + " not a pmid:###"); valid = false; } if (valid && (pubmed = fetchPubmedEntry(Integer.parseInt(tokens[3].substring(5)))) == null) { valid = false; } if (valid && !tokens[4].equals("#" + hashtag)) { System.err.println("Ignoring " + title + " doesn't end with #" + hashtag); valid = false; } if (valid && p1 != null && p2 != null && pubmed != null && foafName != null && foafURI != null) { exportFoaf(foafName, foafURI); exportGi(p1); exportGi(p2); exportPubmed(pubmed); System.out.println("<Interaction rdf:about=\"" + link + "\">"); System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p1.gi + "\"/>"); System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p2.gi + "\"/>"); System.out.println(" <reference rdf:resource=\"http://www.ncbi.nlm.nih.gov/pubmed/" + pubmed.pmid + "\"/>"); System.out.println(" <dc:creator rdf:resource=\"" + foafURI + "\"/>"); System.out.println(" <dc:date>" + escape(published) + "</dc:date>"); System.out.println("</Interaction>"); } inEntry = false; title = null; foafName = null; foafURI = null; inAuthor = false; published = null; link = null; } else if (inAuthor && local.equals("author")) { inAuthor = false; } } } } reader.close(); }
Code Sample 2:
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
|
11
|
Code Sample 1:
public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
private int getRootNodeId(DataSource dataSource) throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; String query = null; try { conn = dataSource.getConnection(); st = conn.createStatement(); query = "select " + col.id + " from " + DB.Tbl.tree + " where " + col.parentId + " is null"; rs = st.executeQuery(query); while (rs.next()) { return rs.getInt(col.id); } query = "insert into " + DB.Tbl.tree + "(" + col.lKey + ", " + col.rKey + ", " + col.level + ") values(1,2,0)"; st.executeUpdate(query, new String[] { col.id }); rs = st.getGeneratedKeys(); while (rs.next()) { int genId = rs.getInt(1); rs.close(); conn.commit(); return genId; } throw new SQLException("Не удается создать корневой элемент для дерева."); } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } try { conn.rollback(); } catch (Exception e) { } try { conn.close(); } catch (Exception e) { } } }
Code Sample 2:
public static Document getXHTMLDocument(URL _url) throws IOException { final Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setShowWarnings(false); tidy.setXmlOut(true); final BufferedInputStream input_stream = new BufferedInputStream(_url.openStream()); return tidy.parseDOM(input_stream, null); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.