label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public static synchronized void loadConfig(String configFile) { if (properties != null) { return; } URL url = null; InputStream is = null; try { String configProperty = null; try { configProperty = System.getProperty("dspace.configuration"); } catch (SecurityException se) { log.warn("Unable to access system properties, ignoring.", se); } if (loadedFile != null) { log.info("Reloading current config file: " + loadedFile.getAbsolutePath()); url = loadedFile.toURI().toURL(); } else if (configFile != null) { log.info("Loading provided config file: " + configFile); loadedFile = new File(configFile); url = loadedFile.toURI().toURL(); } else if (configProperty != null) { log.info("Loading system provided config property (-Ddspace.configuration): " + configProperty); loadedFile = new File(configProperty); url = loadedFile.toURI().toURL(); } else { url = ConfigurationManager.class.getResource("/dspace.cfg"); if (url != null) { log.info("Loading from classloader: " + url); loadedFile = new File(url.getPath()); } } if (url == null) { log.fatal("Cannot find dspace.cfg"); throw new IllegalStateException("Cannot find dspace.cfg"); } else { properties = new Properties(); moduleProps = new HashMap<String, Properties>(); is = url.openStream(); properties.load(is); for (Enumeration<?> pe = properties.propertyNames(); pe.hasMoreElements(); ) { String key = (String) pe.nextElement(); String value = interpolate(key, properties.getProperty(key), 1); if (value != null) { properties.setProperty(key, value); } } } } catch (IOException e) { log.fatal("Can't load configuration: " + url, e); throw new IllegalStateException("Cannot load configuration: " + url, e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } } File licenseFile = new File(getProperty("dspace.dir") + File.separator + "config" + File.separator + "default.license"); FileInputStream fir = null; InputStreamReader ir = null; BufferedReader br = null; try { fir = new FileInputStream(licenseFile); ir = new InputStreamReader(fir, "UTF-8"); br = new BufferedReader(ir); String lineIn; license = ""; while ((lineIn = br.readLine()) != null) { license = license + lineIn + '\n'; } br.close(); } catch (IOException e) { log.fatal("Can't load license: " + licenseFile.toString(), e); throw new IllegalStateException("Cannot load license: " + licenseFile.toString(), e); } finally { if (br != null) { try { br.close(); } catch (IOException ioe) { } } if (ir != null) { try { ir.close(); } catch (IOException ioe) { } } if (fir != null) { try { fir.close(); } catch (IOException ioe) { } } } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
@Override public void run() { if (mMode == 0) { long currentVersion = Version.extractVersion(App.getVersion()); if (currentVersion == 0) { mMode = 2; RESULT = MSG_UP_TO_DATE; return; } long versionAvailable = currentVersion; mMode = 2; try { StringBuilder buffer = new StringBuilder(mCheckURL); try { NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); if (!ni.isLoopback()) { if (ni.isUp()) { if (!ni.isVirtual()) { buffer.append('?'); byte[] macAddress = ni.getHardwareAddress(); for (byte one : macAddress) { buffer.append(Integer.toHexString(one >>> 4 & 0xF)); buffer.append(Integer.toHexString(one & 0xF)); } } } } } catch (Exception exception) { } URL url = new URL(buffer.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, "\t"); if (tokenizer.hasMoreTokens()) { try { if (tokenizer.nextToken().equalsIgnoreCase(mProductKey)) { String token = tokenizer.nextToken(); long version = Version.extractVersion(token); if (version > versionAvailable) { versionAvailable = version; } } } catch (Exception exception) { } } line = in.readLine(); } } catch (Exception exception) { } if (versionAvailable > currentVersion) { Preferences prefs = Preferences.getInstance(); String humanReadableVersion = Version.getHumanReadableVersion(versionAvailable); NEW_VERSION_AVAILABLE = true; RESULT = MessageFormat.format(MSG_OUT_OF_DATE, humanReadableVersion); if (versionAvailable > Version.extractVersion(prefs.getStringValue(MODULE, LAST_VERSION_KEY, App.getVersion()))) { prefs.setValue(MODULE, LAST_VERSION_KEY, humanReadableVersion); prefs.save(); mMode = 1; EventQueue.invokeLater(this); return; } } else { RESULT = MSG_UP_TO_DATE; } } else if (mMode == 1) { if (App.isNotificationAllowed()) { String result = getResult(); mMode = 2; if (WindowUtils.showConfirmDialog(null, result, MSG_UPDATE_TITLE, JOptionPane.OK_CANCEL_OPTION, new String[] { MSG_UPDATE_TITLE, MSG_IGNORE_TITLE }, MSG_UPDATE_TITLE) == JOptionPane.OK_OPTION) { goToUpdate(); } } else { DelayedTask.schedule(this, 250); } } }
Code Sample 2:
protected void registerClasses() throws PrintException { if (!init) { try { Enumeration<URL> somethingToRegister = this.getClass().getClassLoader().getResources("META-INF/" + getClass().getSimpleName() + ".properties"); while (somethingToRegister.hasMoreElements()) { URL url = (URL) somethingToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); try { Class cls = Class.forName(line); cls.newInstance(); log.debug("class " + line + " registered " + url); } catch (ClassNotFoundException e) { log.error("class " + line + " not found " + url, e); } catch (InstantiationException e) { log.error("class " + line + " not found " + url, e); } catch (IllegalAccessException e) { log.error("class " + line + " not found " + url, e); } line = buff.readLine(); } buff.close(); in.close(); } } catch (IOException e) { throw new PrintException(e.getMessage(), e); } init = true; } }
|
00
|
Code Sample 1:
public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String sql = "delete from Instructions where InstructionId = " + id; stmt.executeUpdate(sql); sql = "delete from InstructionGroups where InstructionId = " + id; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
Code Sample 2:
private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) { boolean result = true; try { notifyCopyStart(destinationFile); destinationFile.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destinationFile); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { result = false; handleException("\n Error in method: copy!\n", e, errorLog); } finally { notifyCopyEnd(destinationFile); } return result; }
|
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 { closeQuietly(in); closeQuietly(out); } return success; }
Code Sample 2:
@Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("summarysort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("summarysort :: INPATH not given."); return 3; } final String outS = (String) parser.getOptionValue(outputDirOpt); final Path wrkDir = new Path(args.get(0)), in = new Path(args.get(1)), out = outS == null ? null : new Path(outS); final boolean verbose = parser.getBoolean(verboseOpt); final Configuration conf = getConf(); final Timer t = new Timer(); try { @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = sortOne(conf, in, wrkDir, "summarysort", ""); System.out.printf("summarysort :: Waiting for job completion...\n"); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("summarysort :: Job failed."); return 4; } System.out.printf("summarysort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("summarysort :: Merging output..."); t.start(); final FileSystem srcFS = wrkDir.getFileSystem(conf); final FileSystem dstFS = out.getFileSystem(conf); final OutputStream outs = dstFS.create(out); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, in.getName() + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("summarysort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarysort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Output merging failed: %s\n", e); return 5; } return 0; }
|
00
|
Code Sample 1:
public void getDownloadInfo(String _url) throws Exception { cl = new FTPClient(); Authentication auth = new FTPAuthentication(); cl.connect(getHostName()); while (!cl.login(auth.getUser(), auth.getPassword())) { log.debug("getDownloadInfo() - login error state: " + Arrays.asList(cl.getReplyStrings())); ap.setSite(getSite()); auth = ap.promptAuthentication(); if (auth == null) throw new Exception("User Cancelled Auth Operation"); } AuthManager.putAuth(getSite(), auth); cl.enterLocalPassiveMode(); FTPFile file = cl.listFiles(new URL(_url).getFile())[0]; setURL(_url); setLastModified(file.getTimestamp().getTimeInMillis()); setSize(file.getSize()); setResumable(cl.rest("0") == 350); setRangeEnd(getSize() - 1); }
Code Sample 2:
public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { URL url = new URL("https://imo.im/"); URLConnection con = url.openConnection(); InputStream is = con.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while (((len = is.read(buffer)) >= 0)) { out.write(buffer, 0, len); } out.flush(); System.out.println(out.toString()); }
Code Sample 2:
private SpequlosResponse executeGet(String targetURL, String urlParameters) { URL url; HttpURLConnection connection = null; boolean succ = false; try { url = new URL(targetURL + "?" + urlParameters); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer log = new StringBuffer(); ArrayList<String> response = new ArrayList<String>(); while ((line = rd.readLine()) != null) { if (line.startsWith("<div class=\"qos\">")) { System.out.println("here is the line : " + line); String resp = line.split(">")[1].split("<")[0]; System.out.println("here is the splitted line : " + resp); if (!resp.startsWith("None")) { succ = true; String[] values = resp.split(" "); ArrayList<String> realvalues = new ArrayList<String>(); for (String s : values) { realvalues.add(s); } if (realvalues.size() == 5) { realvalues.add(2, realvalues.get(2) + " " + realvalues.get(3)); realvalues.remove(3); realvalues.remove(3); } for (String n : realvalues) { response.add(n); } } } else { log.append(line); log.append('\r'); } } rd.close(); SpequlosResponse speqresp = new SpequlosResponse(response, log.toString(), succ); return speqresp; } catch (Exception e) { e.printStackTrace(); String log = "Please check the availability of Spequlos server!<br />" + "URL:" + targetURL + "<br />" + "PARAMETERS:" + urlParameters + "<br />"; return new SpequlosResponse(null, log, succ); } finally { if (connection != null) connection.disconnect(); } }
|
11
|
Code Sample 1:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
|
00
|
Code Sample 1:
public boolean refresh() { try { URLConnection conn = url.openConnection(); conn.setUseCaches(false); if (credential != null) conn.setRequestProperty("Authorization", credential); conn.connect(); int status = ((HttpURLConnection) conn).getResponseCode(); if (status == 401 || status == 403) errorMessage = (credential == null ? PASSWORD_MISSING : PASSWORD_INCORRECT); else if (status == 404) errorMessage = NOT_FOUND; else if (status != 200) errorMessage = COULD_NOT_RETRIEVE; else { InputStream in = conn.getInputStream(); byte[] httpData = TinyWebServer.slurpContents(in, true); synchronized (this) { data = httpData; dataProvider = null; } errorMessage = null; refreshDate = new Date(); String owner = conn.getHeaderField(OWNER_HEADER_FIELD); if (owner != null) setLocalAttr(OWNER_ATTR, owner); store(); return true; } } catch (UnknownHostException uhe) { errorMessage = NO_SUCH_HOST; } catch (ConnectException ce) { errorMessage = COULD_NOT_CONNECT; } catch (IOException ioe) { errorMessage = COULD_NOT_RETRIEVE; } return false; }
Code Sample 2:
public static String generateHashSE(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); byte[] hashSHA256 = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md.digest(hashSHA256, 0, text.length()); return convertToHex(hashSHA256); }
|
11
|
Code Sample 1:
protected boolean store(Context context) throws DataStoreException, ServletException { Connection db = context.getConnection(); Statement st = null; String q = null; Integer subscriber = context.getValueAsInteger("subscriber"); int amount = 0; if (subscriber == null) { throw new DataAuthException("Don't know who moderator is"); } Object response = context.get("Response"); if (response == null) { throw new DataStoreException("Don't know what to moderate"); } else { Context scratch = (Context) context.clone(); TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch); Integer author = scratch.getValueAsInteger("author"); if (subscriber.equals(author)) { throw new SelfModerationException("You may not moderate your own responses"); } } context.put("moderator", subscriber); context.put("moderated", response); if (db != null) { try { st = db.createStatement(); q = "select mods from subscriber where subscriber = " + subscriber.toString(); ResultSet r = st.executeQuery(q); if (r.next()) { if (r.getInt("mods") < 1) { throw new DataAuthException("You have no moderation points left"); } } else { throw new DataAuthException("Don't know who moderator is"); } Object reason = context.get("reason"); q = "select score from modreason where modreason = " + reason; r = st.executeQuery(q); if (r.next()) { amount = r.getInt("score"); context.put("amount", new Integer(amount)); } else { throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate"); } context.put(keyField, null); if (super.store(context, db)) { db.setAutoCommit(false); q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response; st.executeUpdate(q); q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber; st.executeUpdate(q); q = "select author from response " + "where response = " + response; r = st.executeQuery(q); if (r.next()) { int author = r.getInt("author"); if (author != 0) { int points = -1; if (amount > 0) { points = 1; } StringBuffer qb = new StringBuffer("update subscriber "); qb.append("set score = score + ").append(amount); qb.append(", mods = mods + ").append(points); qb.append(" where subscriber = ").append(author); st.executeUpdate(qb.toString()); } } db.commit(); } } catch (Exception e) { try { db.rollback(); } catch (Exception whoops) { throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage()); } throw new DataStoreException("Failed to store moderation: " + e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (Exception noclose) { } context.releaseConnection(db); } } } return true; }
Code Sample 2:
public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
|
00
|
Code Sample 1:
@Test public void test02_ok_200_logo() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(xlsURL); HttpResponse response = client.execute(post); assertEquals("failed code for ", 200, response.getStatusLine().getStatusCode()); } finally { client.getConnectionManager().shutdown(); } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == submitButton) { SubmissionProfile profile = (SubmissionProfile) destinationCombo.getSelectedItem(); String uri = profile.endpoint; String authPoint = profile.authenticationPoint; String user = userIDField.getText(); String passwd = new String(passwordField.getPassword()); try { URL url = new URL(authPoint + "?username=" + user + "&password=" + passwd); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String text = ""; while ((line = reader.readLine()) != null) { text = text + line; } reader.close(); submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); this.dispose(); } catch (Exception ex) { ex.printStackTrace(); if (ex instanceof java.io.IOException) { String msg = ex.getMessage(); if (msg.indexOf("HTTP response code: 401") != -1) JOptionPane.showMessageDialog(null, "Invalid Username/Password", "Invalid Username/Password", JOptionPane.ERROR_MESSAGE); else if (msg.indexOf("HTTP response code: 404") != -1) { try { submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (Exception exc) { exc.printStackTrace(); } } } } } else if (src == cancelButton) { this.setVisible(false); this.dispose(); } }
|
00
|
Code Sample 1:
public static final boolean updateFDT(final String currentVersion, final String updateURL, boolean shouldUpdate, boolean noLock) throws Exception { final String partialURL = updateURL + (updateURL.endsWith("/") ? "" : "/") + "fdt.jar"; logger.log("Checking remote fdt.jar at URL: " + partialURL); String JVMVersion = "NotAvailable"; String JVMRuntimeVersion = "NotAvailable"; String OSVersion = "NotAvailable"; String OSName = "NotAvailable"; String OSArch = "NotAvailable"; try { JVMVersion = System.getProperty("java.vm.version"); } catch (Throwable t) { JVMVersion = "NotAvailable"; } try { JVMRuntimeVersion = System.getProperty("java.runtime.version"); } catch (Throwable t) { JVMRuntimeVersion = "NotAvailable"; } try { OSName = System.getProperty("os.name"); } catch (Throwable t) { OSName = "NotAvailable"; } try { OSArch = System.getProperty("os.arch"); } catch (Throwable t) { OSArch = "NotAvailable"; } try { OSVersion = System.getProperty("os.version"); } catch (Throwable t) { OSVersion = "NotAvailable"; } StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(partialURL); urlBuilder.append("?FDTCurrentVersion=").append(currentVersion); urlBuilder.append("&shouldUpdate=").append(shouldUpdate); urlBuilder.append("&tstamp=").append(System.currentTimeMillis()); urlBuilder.append("&java.vm.version=").append(JVMVersion); urlBuilder.append("&java.runtime.version=").append(JVMRuntimeVersion); urlBuilder.append("&os.name=").append(OSName); urlBuilder.append("&os.version=").append(OSVersion); urlBuilder.append("&os.arch=").append(OSArch); final Properties p = getFDTUpdateProperties(); if (p.getProperty("totalRead") == null) { p.put("totalRead", "0"); } if (p.getProperty("totalWrite") == null) { p.put("totalWrite", "0"); } checkAndSetInstanceID(p); if (p.getProperty("totalRead_rst") != null) { p.remove("totalRead_rst"); } if (p.getProperty("totalWrite_rst") != null) { p.remove("totalWrite_rst"); } if (p != null && p.size() > 0) { for (final Map.Entry<Object, Object> entry : p.entrySet()) { urlBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue()); } } final String finalPath = new URI(FDT.class.getProtectionDomain().getCodeSource().getLocation().toString()).getPath(); if (finalPath == null || finalPath.length() == 0) { throw new IOException("Cannot determine the path to current fdt jar"); } final File currentJar = new File(finalPath); if (!currentJar.exists()) { throw new IOException("Current fdt.jar path seems to be [ " + finalPath + " ] but the JVM cannot access it!"); } if (currentJar.isFile() && currentJar.canWrite()) { logger.log("\nCurrent fdt.jar path is: " + finalPath); } else { throw new IOException("Current fdt.jar path seems to be [ " + finalPath + " ] but it does not have write access!"); } File tmpUpdateFile = null; FileOutputStream fos = null; JarFile jf = null; InputStream connInputStream = null; try { tmpUpdateFile = File.createTempFile("fdt_update_tmp", ".jar"); tmpUpdateFile.deleteOnExit(); fos = new FileOutputStream(tmpUpdateFile); final URLConnection urlConnection = new URL(urlBuilder.toString()).openConnection(); urlConnection.setDefaultUseCaches(false); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(URL_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(URL_CONNECTION_TIMEOUT); logger.log("Connecting ... "); urlConnection.connect(); connInputStream = urlConnection.getInputStream(); logger.log("OK"); byte[] buff = new byte[8192]; int count = 0; while ((count = connInputStream.read(buff)) > 0) { fos.write(buff, 0, count); } fos.flush(); jf = new JarFile(tmpUpdateFile); final Manifest mf = jf.getManifest(); final Attributes attr = mf.getMainAttributes(); final String remoteVersion = attr.getValue("Implementation-Version"); if (remoteVersion == null || remoteVersion.trim().length() == 0) { throw new Exception("Cannot read the version from the downloaded jar...Cannot compare versions!"); } if (currentVersion.equals(remoteVersion.trim())) { return false; } logger.log("Remote FDT version: " + remoteVersion + " Local FDT version: " + currentVersion + ". Update available."); if (shouldUpdate) { try { final String parent = currentJar.getParent(); if (parent == null) { logger.log("Unable to determine parent dir for: " + currentJar); throw new IOException("Unable to determine parent dir for: " + currentJar); } final File parentDir = new File(parent); if (!parentDir.canWrite()) { logger.log(Level.WARNING, "[ WARNING CHECK ] The OS reported that is unable to write in parent dir: " + parentDir + " continue anyway; the call might be broken."); } final File bkpJar = new File(parentDir.getPath() + File.separator + "fdt_" + Config.FDT_FULL_VERSION + ".jar"); boolean bDel = bkpJar.exists(); if (bDel) { bDel = bkpJar.delete(); if (!bDel) { logger.log("[ WARNING ] Unable to delete backup jar with the same version: " + bkpJar + " ... will continue"); } else { logger.log("[ INFO ] Backup jar (same version as the update) " + bkpJar + " delete it."); } } boolean renameSucced = currentJar.renameTo(bkpJar); if (!renameSucced) { logger.log(Level.WARNING, "Unable to create backup: " + bkpJar + " for current FDT before update."); } else { logger.log("Backing up old FDT succeeded: " + bkpJar); } } catch (Throwable t) { logger.log(Level.WARNING, "Unable to create a backup for current FDT before update. Exception: ", t); } copyFile2File(tmpUpdateFile, currentJar, noLock); } return true; } finally { closeIgnoringExceptions(connInputStream); closeIgnoringExceptions(fos); if (tmpUpdateFile != null) { try { tmpUpdateFile.delete(); } catch (Throwable ignore) { } } } }
Code Sample 2:
public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, File targetFile) throws FileCopyingException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileCopyingException(exceptionMessage, ioException); } }
Code Sample 2:
public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
|
00
|
Code Sample 1:
private static List retrieveQuotes(Report report, Symbol symbol, String suffix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, suffix, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); 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 { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public 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(); }
|
00
|
Code Sample 1:
public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; }
Code Sample 2:
public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
Code Sample 2:
public GeocodeResponse getGKCoordinateFromAddress(SearchAddressRequest searchAddressRequest) { GeocodeResponse result = null; String adress = null; if (searchAddressRequest.getAdressTextField() != null) adress = searchAddressRequest.getAdressTextField().getText(); if (adress == null || adress.length() == 0) adress = " "; String postRequest = ""; postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + "http://gdi3d.giub.uni-bonn.de:8080/openls-lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"GeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:GeocodeRequest> \n" + " <xls:Address countryCode=\"DE\"> \n" + " <xls:freeFormAddress>" + adress + "</xls:freeFormAddress> \n" + " </xls:Address> \n" + " </xls:GeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; if (Navigator.isVerbose()) { System.out.println("OpenLSGeocoder postRequest " + postRequest); } String errorMessage = ""; try { System.out.println("contacting " + serviceEndPoint); URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); result = new GeocodeResponse(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); XLSType xlsTypeResponse = xlsResponse.getXLS(); Node node0 = xlsTypeResponse.getDomNode(); NodeList nodes1 = node0.getChildNodes(); for (int i = 0; i < nodes1.getLength(); i++) { Node node1 = nodes1.item(i); NodeList nodes2 = node1.getChildNodes(); for (int j = 0; j < nodes2.getLength(); j++) { Node node2 = nodes2.item(j); NodeList nodes3 = node2.getChildNodes(); for (int k = 0; k < nodes3.getLength(); k++) { Node node3 = nodes3.item(k); String nodeName = node3.getNodeName(); if (nodeName.equalsIgnoreCase("xls:GeocodeResponseList")) { net.opengis.xls.GeocodeResponseListDocument gcrld = net.opengis.xls.GeocodeResponseListDocument.Factory.parse(node3); net.opengis.xls.GeocodeResponseListType geocodeResponseList = gcrld.getGeocodeResponseList(); result.setGeocodeResponseList(geocodeResponseList); } } } } is.close(); } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (SocketTimeoutException ste) { ste.printStackTrace(); errorMessage += "<p>Time Out Exception, Server is not responding</p>"; } catch (IOException ioe) { ioe.printStackTrace(); errorMessage += "<p>IO Exception</p>"; } catch (XmlException xmle) { xmle.printStackTrace(); errorMessage += "<p>Error occured during parsing the XML response</p>"; } if (!errorMessage.equals("")) { System.out.println("\nerrorMessage: " + errorMessage + "\n\n"); JLabel label1 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">Geocoder Error</span></body></html>"); JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + errorMessage + "<br>" + "<p>please check Java console. If problem persits, please report to system manager</p>" + "</span></body></html>"); Object[] objects = { label1, label2 }; JOptionPane.showMessageDialog(null, objects, "Error Message", JOptionPane.ERROR_MESSAGE); return null; } return result; }
|
11
|
Code Sample 1:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); }
Code Sample 2:
public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
|
11
|
Code Sample 1:
private static void copyImage(String srcImg, String destImg) { try { FileChannel srcChannel = new FileInputStream(srcImg).getChannel(); FileChannel dstChannel = new FileOutputStream(destImg).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static boolean unzip_and_merge(String infile, String outfile) { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(infile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); FileOutputStream fos = new FileOutputStream(outfile); dest = new BufferedOutputStream(fos, BUFFER); while (zis.getNextEntry() != null) { int count; byte data[] = new byte[BUFFER]; while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); } dest.close(); zis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
Code Sample 2:
public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
public void open() throws IOException, RecursionException { String encoding = null; if (source != null) { Reader sourceReader = source.getCharacterStream(); if (sourceReader != null) { if (readerReader == null) readerReader = new XMLReaderReader(); readerReader.reset(sourceReader, true); isStandalone = readerReader.isXMLStandalone(); activeReader = readerReader; isOpen = true; return; } InputStream in = source.getByteStream(); if (in != null) { if (streamReader == null) streamReader = new XMLStreamReader(); streamReader.reset(in, source.getEncoding(), true); isOpen = true; isStandalone = streamReader.isXMLStandalone(); activeReader = streamReader; return; } url = new URL(defaultContext, source.getSystemId()); sysID = url.toString(); encoding = source.getEncoding(); } if (streamReader == null) streamReader = new XMLStreamReader(); streamReader.reset(url.openStream(), encoding, true); isStandalone = streamReader.isXMLStandalone(); activeReader = streamReader; isOpen = true; }
Code Sample 2:
public String preProcessHTML(String uri) { final StringBuffer buf = new StringBuffer(); try { HTMLDocument doc = new HTMLDocument() { public HTMLEditorKit.ParserCallback getReader(int pos) { return new HTMLEditorKit.ParserCallback() { public void handleText(char[] data, int pos) { buf.append(data); buf.append('\n'); } }; } }; URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); Reader rd = new InputStreamReader(conn.getInputStream()); new ParserDelegator().parse(rd, doc.getReader(0), Boolean.TRUE); } catch (MalformedURLException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (URISyntaxException e) { System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } return buf.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File file, String destDir) throws IOException { if (!isCanReadFile(file)) throw new RuntimeException("The File can't read:" + file.getPath()); if (!isCanWriteDirectory(destDir)) throw new RuntimeException("The Directory can't write:" + destDir); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(file).getChannel(); dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw e; } finally { if (srcChannel != null) try { srcChannel.close(); } catch (IOException e) { } if (dstChannel != null) try { dstChannel.close(); } catch (IOException e) { } } }
Code Sample 2:
public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
11
|
Code Sample 1:
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
Code Sample 2:
public void migrateTo(String newExt) throws IOException { DigitalObject input = new DigitalObject.Builder(Content.byReference(new File(AllJavaSEServiceTestsuite.TEST_FILE_LOCATION + "PlanetsLogo.png").toURI().toURL())).build(); System.out.println("Input: " + input); FormatRegistry format = FormatRegistryFactory.getFormatRegistry(); MigrateResult mr = dom.migrate(input, format.createExtensionUri("png"), format.createExtensionUri(newExt), null); ServiceReport sr = mr.getReport(); System.out.println("Got Report: " + sr); DigitalObject doOut = mr.getDigitalObject(); assertTrue("Resulting digital object is null.", doOut != null); System.out.println("Output: " + doOut); System.out.println("Output.content: " + doOut.getContent()); File out = new File("services/java-se/test/results/test." + newExt); FileOutputStream fo = new FileOutputStream(out); IOUtils.copyLarge(doOut.getContent().getInputStream(), fo); fo.close(); System.out.println("Recieved service report: " + mr.getReport()); System.out.println("Recieved service properties: "); ServiceProperties.printProperties(System.out, mr.getReport().getProperties()); }
|
00
|
Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { return (URLConnection) openConnectionMethod.invoke(handler, new Object[] { url }); } catch (Exception e) { factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), "openConnection", FrameworkLogEntry.ERROR, e, null)); throw new RuntimeException(e.getMessage()); } } throw new MalformedURLException(); }
Code Sample 2:
public char check(String password) { if (captchaRandom.equals("null")) { return 's'; } if (captchaRandom.equals("used")) { return 'm'; } String encryptionBase = secret + captchaRandom; if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) { encryptionBase += ":" + alphabet + ":" + letters; } MessageDigest md5; byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; try { md5 = MessageDigest.getInstance("MD5"); md5.update(encryptionBase.getBytes()); digest = md5.digest(); } catch (NoSuchAlgorithmException e) { } String correctPassword = ""; int index; for (int i = 0; i < letters; i++) { index = (digest[i] + 256) % 256 % alphabet.length(); correctPassword += alphabet.substring(index, index + 1); } if (!password.equals(correctPassword)) { return 'w'; } else { captchaRandom = "used"; return 't'; } }
|
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 boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
private static void copySmallFile(final File sourceFile, final File targetFile) throws PtException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new PtException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(inChannel, outChannel); } }
Code Sample 2:
private boolean _copyPath(String source, String destination, Object handler) { try { FileInputStream fis = new FileInputStream(_fullPathForPath(source)); FileOutputStream fos = new FileOutputStream(_fullPathForPath(destination)); byte[] buffer = new byte[fis.available()]; int read; for (read = fis.read(buffer); read >= 0; read = fis.read(buffer)) { fos.write(buffer, 0, read); } fis.close(); fos.close(); return true; } catch (IOException ioe) { ioe.printStackTrace(); return false; } }
|
00
|
Code Sample 1:
private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
Code Sample 2:
private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; }
|
00
|
Code Sample 1:
public OAuthResponseMessage access(OAuthMessage request, net.oauth.ParameterStyle style) throws IOException { HttpMessage httpRequest = HttpMessage.newRequest(request, style); HttpResponseMessage httpResponse = http.execute(httpRequest, httpParameters); httpResponse = HttpMessageDecoder.decode(httpResponse); return new OAuthResponseMessage(httpResponse); }
Code Sample 2:
public void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException { String sql = null; try { Connection con = getConnection(); Statement stmt = con.createStatement(); ResultSet rslt = null; con.setAutoCommit(false); for (int i = 0; i < entries.length; i++) { if (!sanityCheck(entries[i])) { } else { sql = getSelectSql(entries[i]); rslt = stmt.executeQuery(sql); if (rslt.next()) { if (rslt.getInt(1) == 0) { sql = getInsertSql(entries[i]); if (stmt.executeUpdate(sql) != 1) { con.rollback(); System.out.println("rolling back sql"); throw new WeatherMonitorException("exception on insert"); } } } } } con.commit(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new WeatherMonitorException(e.getMessage()); } }
|
11
|
Code Sample 1:
public void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
Code Sample 2:
public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
|
11
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
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(); } }
|
00
|
Code Sample 1:
public static synchronized Integer getNextSequence(String seqNum) throws ApplicationException { Connection dbConn = null; java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noTableMatchFlag = false; int currID = 0; int nextID = 0; try { dbConn = getConnection(); } catch (Exception e) { log.error("Error Getting Connection.", e); throw new ApplicationException("errors.framework.db_conn", e); } synchronized (hashPkKeyLock) { if (hashPkKeyLock.get(seqNum) == null) { hashPkKeyLock.put(seqNum, new Object()); } } synchronized (hashPkKeyLock.get(seqNum)) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT TABLE_KEY_MAX FROM SYS_TABLE_KEY WHERE TABLE_NAME=?"); preStat.setString(1, seqNum); rs = preStat.executeQuery(); if (rs.next()) { currID = rs.getInt(1); } else { noTableMatchFlag = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (noTableMatchFlag) { try { currID = 0; preStat = dbConn.prepareStatement("INSERT INTO SYS_TABLE_KEY(TABLE_NAME, TABLE_KEY_MAX) VALUES(?, ?)", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setString(1, seqNum); preStat.setInt(2, currID); preStat.executeUpdate(); } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } } try { int updateCnt = 0; nextID = currID; do { nextID++; preStat = dbConn.prepareStatement("UPDATE SYS_TABLE_KEY SET TABLE_KEY_MAX=? WHERE TABLE_NAME=? AND TABLE_KEY_MAX=?", java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); preStat.setInt(1, nextID); preStat.setString(2, seqNum); preStat.setInt(3, currID); updateCnt = preStat.executeUpdate(); currID++; if (updateCnt == 0 && (currID % 2) == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); return (new Integer(nextID)); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e, seqNum); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } } }
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:
private void reloadData(String dataSourceUrl) { try { URL url = new URL(dataSourceUrl); InputStream is = url.openStream(); if (progressMonitor.isCanceled() == false) { progressMonitor.setNote("Building classifications..."); progressMonitor.setProgress(2); mediator.loadClassificationTree(is); } } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public synchronized void readConfiguration() throws IOException, SecurityException { String path; InputStream inputStream; path = System.getProperty("java.util.logging.config.file"); if ((path == null) || (path.length() == 0)) { String url = (System.getProperty("gnu.classpath.home.url") + "/logging.properties"); inputStream = new URL(url).openStream(); } else inputStream = new java.io.FileInputStream(path); try { readConfiguration(inputStream); } finally { inputStream.close(); } }
|
11
|
Code Sample 1:
public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); 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 void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long count = 0; long size = source.size(); while ((count += destination.transferFrom(source, 0, size - count)) < size) ; } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
public Savable loadResource(String name, PrimitiveLoader loader) { Savable objeto = null; URL url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getCompiledExtension()); if (url == null) { url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getPrimitiveExtension()); if (url != null) { try { objeto = loader.loadResource(name, url.openStream()); File file = ResourceLocator.replaceExtension(url, loader.getCompiledExtension()); BinaryExporter.getInstance().save(objeto, file); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } } else { try { objeto = BinaryImporter.getInstance().load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } } return objeto; }
Code Sample 2:
public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
|
00
|
Code Sample 1:
public boolean download(URL url, File file) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[4096]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { System.out.println(e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { return false; } } return true; }
Code Sample 2:
public static String getWikiPage(String city) throws MalformedURLException, IOException, ParserConfigurationException, SAXException { String url = "http://api.geonames.org/wikipediaSearch?q=" + city + "&maxRows=1&lang=it&username=lorenzo.abram"; URLConnection conn = new URL(url).openConnection(); InputStream response = conn.getInputStream(); GeonamesHandler handler = new GeonamesHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(response, handler); return handler.getUrl(); }
|
11
|
Code Sample 1:
private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
Code Sample 2:
private boolean get(String surl, File dst, Get get) throws IOException { boolean ret = false; InputStream is = null; OutputStream os = null; try { try { if (surl.startsWith("file://")) { is = new FileInputStream(surl.substring(7)); } else { URL url = new URL(surl); is = url.openStream(); } if (is != null) { os = new FileOutputStream(dst); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } } catch (ConnectException ex) { log("Connect exception " + ex.getMessage(), ex, 3); if (dst.exists()) dst.delete(); } catch (UnknownHostException ex) { log("Unknown host " + ex.getMessage(), ex, 3); } catch (FileNotFoundException ex) { log("File not found: " + ex.getMessage(), 3); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } if (ret) { try { is = new FileInputStream(dst); os = new FileOutputStream(getCachedFile(get)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; }
|
11
|
Code Sample 1:
public static void copyFile(final File source, final File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Code Sample 2:
private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } }
|
11
|
Code Sample 1:
public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
Code Sample 2:
public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
Code Sample 1:
public static void storeRemote(String sourceLocation, SourceDetail targetSourceDetail, String targetlocation, boolean isBinary) throws Exception { FTPClient client = new FTPClient(); client.connect(targetSourceDetail.getHost()); client.login(targetSourceDetail.getUser(), targetSourceDetail.getPassword()); if (isBinary) client.setFileType(FTPClient.BINARY_FILE_TYPE); File file = new File(sourceLocation); if (file.isDirectory()) { client.makeDirectory(targetlocation); FileInputStream in = null; for (File myFile : file.listFiles()) { if (myFile.isDirectory()) { storeRemote(myFile.getAbsolutePath(), targetSourceDetail, targetlocation + "/" + myFile.getName(), isBinary); } else { in = new FileInputStream(myFile.getAbsolutePath()); if (!targetlocation.endsWith("/")) client.storeFile(targetlocation + "/" + myFile.getName(), in); else client.storeFile(targetlocation + myFile.getName(), in); in.close(); } } } else { FileInputStream in = new FileInputStream(sourceLocation); client.storeFile(targetlocation, in); in.close(); } client.disconnect(); }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); 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 setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
Code Sample 2:
public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
|
11
|
Code Sample 1:
private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } }
Code Sample 2:
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
|
00
|
Code Sample 1:
private HttpURLConnection setUpHttpConnection(URL url, int length) throws IOException, ProtocolException { URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", "\"http://www.webserviceX.NET/GetQuote\""); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); return httpConn; }
Code Sample 2:
private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
|
00
|
Code Sample 1:
InputStream selectSource(String item) { if (item.endsWith(".pls")) { item = fetch_pls(item); if (item == null) return null; } else if (item.endsWith(".m3u")) { item = fetch_m3u(item); if (item == null) return null; } if (!item.endsWith(".ogg")) { return null; } InputStream is = null; URLConnection urlc = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), item); else url = new URL(item); urlc = url.openConnection(); is = urlc.getInputStream(); current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile(); } catch (Exception ee) { System.err.println(ee); } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item); current_source = null; } catch (Exception ee) { System.err.println(ee); } } if (is == null) return null; System.out.println("Select: " + item); { boolean find = false; for (int i = 0; i < cb.getItemCount(); i++) { String foo = (String) (cb.getItemAt(i)); if (item.equals(foo)) { find = true; break; } } if (!find) { cb.addItem(item); } } int i = 0; String s = null; String t = null; udp_port = -1; udp_baddress = null; while (urlc != null && true) { s = urlc.getHeaderField(i); t = urlc.getHeaderFieldKey(i); if (s == null) break; i++; if (t != null && t.equals("udp-port")) { try { udp_port = Integer.parseInt(s); } catch (Exception ee) { System.err.println(ee); } } else if (t != null && t.equals("udp-broadcast-address")) { udp_baddress = s; } } return is; }
Code Sample 2:
public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
|
00
|
Code Sample 1:
public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; }
Code Sample 2:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } }
|
11
|
Code Sample 1:
private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
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(); } }
|
00
|
Code Sample 1:
@SuppressWarnings("static-access") public void run() { valuesRow = new String[this.getMaxCounter()]; for (int i = 0; i < this.getMaxCounter(); i++) { InputStream is = null; try { String surl = "http://download.finance.yahoo.com/d/quotes.csv?s=^GDAXI&f=sl1d1t1c1ohgv&e=.csv"; URL url = new URL(surl); is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); String s = dis.readLine(); System.out.println(s); valuesRow[i] = s; is.close(); } catch (MalformedURLException mue) { System.out.println("Ouch - a MalformedURLException happened."); mue.printStackTrace(); System.exit(1); } catch (IOException ioe) { System.out.println("Oops- an IOException happened."); ioe.printStackTrace(); System.exit(1); } try { Thread.currentThread().sleep(this.getTsleep()); } catch (InterruptedException e) { } } System.out.println("valuesRow.length=" + valuesRow.length); }
Code Sample 2:
public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void processStylesheetFile() { InputStream in = null; OutputStream out = null; try { String filename; if (line.hasOption("stylesheetfile")) { filename = line.getOptionValue("stylesheetfile"); in = new FileInputStream(filename); filename = filename.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf('/') + 1); } else { ClassLoader cl = this.getClass().getClassLoader(); filename = "stylesheet.css"; in = cl.getResourceAsStream(RESOURCE_PKG + "/stylesheet.css"); } baseProperties.setProperty("stylesheetfilename", filename); File outFile = new File(outputDir, filename); if (LOG.isInfoEnabled()) { LOG.info("Processing generated file " + outFile.getAbsolutePath()); } out = new FileOutputStream(outFile); IOUtils.copy(in, out); } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } }
|
11
|
Code Sample 1:
public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } }
Code Sample 2:
private void addMaintainerScripts(TarOutputStream tar, PackageInfo info) throws IOException, ScriptDataTooLargeException { for (final MaintainerScript script : info.getMaintainerScripts().values()) { if (script.getSize() > Integer.MAX_VALUE) { throw new ScriptDataTooLargeException("The script data is too large for the tar file. script=[" + script.getType().getFilename() + "]."); } final TarEntry entry = standardEntry(script.getType().getFilename(), UnixStandardPermissions.EXECUTABLE_FILE_MODE, (int) script.getSize()); tar.putNextEntry(entry); IOUtils.copy(script.getStream(), tar); tar.closeEntry(); } }
|
00
|
Code Sample 1:
private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; }
Code Sample 2:
public static String getPasswordHash(String password) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException(e); } md.update(password.getBytes()); byte[] digest = md.digest(); BigInteger i = new BigInteger(1, digest); String hash = i.toString(16); while (hash.length() < 32) { hash = "0" + hash; } return hash; }
|
00
|
Code Sample 1:
public static boolean insert(final CelulaFinanceira objCelulaFinanceira) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))"; pst = c.prepareStatement(sql); pst.setString(1, objCelulaFinanceira.getDescricao()); pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo()); pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo()); pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo()); pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo()); pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo()); pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo()); pst.setDouble(8, objCelulaFinanceira.getValorProvisionado()); pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto()); pst.setDouble(10, objCelulaFinanceira.getGastoReal()); pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto()); pst.setDouble(12, objCelulaFinanceira.getSaldoReal()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); }
|
11
|
Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
|
11
|
Code Sample 1:
private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } }
Code Sample 2:
public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } }
|
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 boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
|
00
|
Code Sample 1:
public void update() { Vector invalids = new Vector(); for (int i = 0; i < urls.size(); i++) { URL url = null; try { url = new URL((String) urls.elementAt(i)); InputStream stream = url.openStream(); stream.close(); } catch (MalformedURLException urlE) { Logger.logWarning("Malformed URL: " + urls.elementAt(i)); } catch (IOException ioE) { invalids.addElement(url); } } for (int i = 0; i < invalids.size(); i++) { urls.removeElement(invalids.elementAt(i)); Logger.logInfo("Removed " + invalids.elementAt(i) + " - no longer available"); } }
Code Sample 2:
public MeetingScript getScript(Integer id) { MeetingScript script = null; try { URL url = new URL(SCRIPT_URL + "?script=" + id); ObjectInputStream ois = new ObjectInputStream(url.openStream()); script = (MeetingScript) ois.readObject(); ois.close(); System.out.println("got script"); } catch (Exception e) { e.printStackTrace(); } return script; }
|
00
|
Code Sample 1:
public void openFtpConnection(String workingDirectory) throws RQLException { try { ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(workingDirectory); } catch (IOException ioex) { throw new RQLException("FTP client could not be created. Please check attributes given in constructor.", ioex); } }
Code Sample 2:
public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
|
00
|
Code Sample 1:
public static String hashPassword(String password) { String passwordHash = ""; try { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); sha1.reset(); sha1.update(password.getBytes()); Base64 encoder = new Base64(); passwordHash = new String(encoder.encode(sha1.digest())); } catch (NoSuchAlgorithmException e) { LoggerFactory.getLogger(UmsAuthenticationProcessingFilter.class.getClass()).error("Failed to generate password hash: " + e.getMessage()); } return passwordHash; }
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:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException(className + "Cannot overwrite existing file: " + dest.getAbsolutePath()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
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; }
|
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 PVBrowserSearchDocument(URL url, PVBrowserModel applicationModel) { this(applicationModel); if (url != null) { try { data.loadFromXML(url.openStream()); loadOpenPVsFromData(); setHasChanges(false); setSource(url); } catch (java.io.IOException exception) { System.err.println(exception); displayWarning("Open Failed!", exception.getMessage(), exception); } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public void run() { try { File inf = new File(dest); if (!inf.exists()) { inf.getParentFile().mkdirs(); } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); out.transferFrom(in, 0, in.size()); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); System.err.println("Error copying file \n" + src + "\n" + dest); } }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
|
11
|
Code Sample 1:
boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; }
Code Sample 2:
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; }
|
00
|
Code Sample 1:
public Document searchRelease(String id) throws Exception { Document doc = null; URL url = new URL("http://" + disgogsUrl + "/release/" + id + "?f=xml&api_key=" + apiKey[0]); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.addRequestProperty("Accept-Encoding", "gzip"); BufferedReader ir = null; if (uc.getInputStream() != null) { ir = new BufferedReader(new InputStreamReader(new GZIPInputStream(uc.getInputStream()), "ISO8859_1")); SAXBuilder builder = new SAXBuilder(); doc = builder.build(ir); } return doc; }
Code Sample 2:
public static String encripty(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; }
|
00
|
Code Sample 1:
public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public void download() throws IOException { new File(file.getPath().substring(0, file.getPath().lastIndexOf(File.separator))).mkdirs(); URLConnection urlConnection = url.openConnection(); size = urlConnection.getContentLength(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); InputStream inputStream = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; fetchedSize = 0; date = urlConnection.getLastModified(); while (!failed && (numRead = inputStream.read(buffer)) != -1) { if (failed) { throw new IOException("Download manually stopped"); } bufferedOutputStream.write(buffer, 0, numRead); fetchedSize += numRead; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadProgress(this); } } } inputStream.close(); bufferedOutputStream.close(); if (file.toString().endsWith(".gz") || file.toString().endsWith(".gzip")) { for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingProgress(this); } } try { GZIPInputStream gzipInputStream = new GZIPInputStream(new FileInputStream(file)); String fileName = file.toString().substring(0, file.toString().lastIndexOf(".")); OutputStream outputStream = new FileOutputStream(fileName); byte[] unpackBuffer = new byte[1024]; int length; while ((length = gzipInputStream.read(unpackBuffer)) > 0) { outputStream.write(unpackBuffer, 0, length); } gzipInputStream.close(); outputStream.close(); file.delete(); file = new File(fileName); file.setLastModified(date); failed = false; finished = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).uncompressingFinished(this); } } for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } catch (IOException ioException) { file.delete(); failed = true; for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).exceptionWasThrown(this, ioException); } } } try { Runtime.getRuntime().exec("chmod 777 " + file.getCanonicalPath()); } catch (Exception exception) { } } else { failed = false; finished = true; file.setLastModified(date); for (int n = 0, i = downloadListener.size(); n < i; n++) { synchronized (downloadListener.get(n)) { ((DownloadListener) downloadListener.get(n)).downloadFinished(this); } } } }
|
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 { closeQuietly(in); closeQuietly(out); } return success; }
Code Sample 2:
@Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private void moveFile(File orig, File target) throws IOException { byte buffer[] = new byte[1000]; int bread = 0; FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(target); while (bread != -1) { bread = fis.read(buffer); if (bread != -1) fos.write(buffer, 0, bread); } fis.close(); fos.close(); orig.delete(); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); }
|
00
|
Code Sample 1:
public void run() { if (_plot == null) { _plot = newPlot(); } getContentPane().add(plot(), BorderLayout.NORTH); int width; int height; String widthspec = getParameter("width"); if (widthspec != null) { width = Integer.parseInt(widthspec); } else { width = 400; } String heightspec = getParameter("height"); if (heightspec != null) { height = Integer.parseInt(heightspec); } else { height = 400; } _setPlotSize(width, height); plot().setButtons(true); Color background = Color.white; String colorspec = getParameter("background"); if (colorspec != null) { background = PlotBox.getColorByName(colorspec); } setBackground(background); plot().setBackground(background); getContentPane().setBackground(background); Color foreground = Color.black; colorspec = getParameter("foreground"); if (colorspec != null) { foreground = PlotBox.getColorByName(colorspec); } setForeground(foreground); plot().setForeground(foreground); plot().setVisible(true); String dataurlspec = getParameter("dataurl"); if (dataurlspec != null) { try { showStatus("Reading data"); URL dataurl = new URL(getDocumentBase(), dataurlspec); InputStream in = dataurl.openStream(); _read(in); showStatus("Done"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } } }
Code Sample 2:
public static void exportGestureSet(List<GestureSet> sets, File file) { try { FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(exportGestureSetsAsStream(sets), outputStream); outputStream.close(); } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets. Export File not found.", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e); } }
|
11
|
Code Sample 1:
public static byte[] createAuthenticator(ByteBuffer data, String secret) { assert data.isDirect() == false : "must not a direct ByteBuffer"; int pos = data.position(); if (pos < RadiusPacket.MIN_PACKET_LENGTH) { System.err.println("packet too small"); return null; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] arr = data.array(); md5.reset(); md5.update(arr, 0, pos); md5.update(secret.getBytes()); return md5.digest(); } catch (NoSuchAlgorithmException nsaex) { throw new RuntimeException("Could not access MD5 algorithm, fatal error"); } }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { try { setStatus(DigestSignTask.RESET, ""); if (e.getSource() == sd) if (retriveEncodedDigestFromServer()) setStatus(DigestSignTask.RESET, "Inserire il pin e battere INVIO per firmare."); if (e.getSource() == pwd) { initStatus(0, DigestSignTask.SIGN_MAXIMUM); if (detectCardAndCriptoki()) { dsTask = new DigestSignTask(getCryptokiLib(), getSignerLabel(), log); timer = new Timer(ONE_SECOND, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setStatus(dsTask.getCurrent(), dsTask.getMessage()); if (dsTask.done()) { timer.stop(); progressBar.setValue(progressBar.getMinimum()); if (dsTask.getCurrent() == DigestSignTask.SIGN_DONE) { Toolkit.getDefaultToolkit().beep(); setEncryptedDigest(dsTask.getEncryptedDigest()); returnEncryptedDigestToForm(); setCertificate(dsTask.getCertificate()); returnCertificateToForm(); if (getSubmitAfterSigning()) { submitForm(); } } enableControls(true); } } }); sign(); } } if (e.getSource() == enc) { log.println("\nCalculating digest ...\n"); java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5"); md5.update(dataArea.getText().getBytes("UTF8")); byte[] digest = md5.digest(); log.println("digest:\n" + formatAsHexString(digest)); log.println("Done."); setEncodedDigest(encodeFromBytes(digest)); returnDigestToForm(); } if (e.getSource() == ld) retriveEncodedDigestFromForm(); if (e.getSource() == led) retriveEncryptedDigestFromForm(); if (e.getSource() == v) { verify(); } } catch (Exception ex) { log.println(ex.toString()); } finally { pwd.setText(""); } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static boolean saveMap(LWMap map, boolean saveAs, boolean export) { Log.info("saveMap: " + map); GUI.activateWaitCursor(); if (map == null) return false; File file = map.getFile(); int response = -1; if (map.getSaveFileModelVersion() == 0) { final Object[] defaultOrderButtons = { VueResources.getString("saveaction.saveacopy"), VueResources.getString("saveaction.save") }; Object[] messageObject = { map.getLabel() }; response = VueUtil.option(VUE.getDialogParent(), VueResources.getFormatMessage(messageObject, "dialog.saveaction.message"), VueResources.getFormatMessage(messageObject, "dialog.saveaction.title"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, defaultOrderButtons, VueResources.getString("saveaction.saveacopy")); } if (response == 0) { saveAs = true; } if ((saveAs || file == null) && !export) { file = ActionUtil.selectFile("Save Map", null); } else if (export) { file = ActionUtil.selectFile("Export Map", "export"); } if (file == null) { try { return false; } finally { GUI.clearWaitCursor(); } } try { Log.info("saveMap: target[" + file + "]"); final String name = file.getName().toLowerCase(); if (name.endsWith(".rli.xml")) { new IMSResourceList().convert(map, file); } else if (name.endsWith(".xml") || name.endsWith(".vue")) { ActionUtil.marshallMap(file, map); } else if (name.endsWith(".jpeg") || name.endsWith(".jpg")) ImageConversion.createActiveMapJpeg(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".png")) ImageConversion.createActiveMapPng(file, VueResources.getDouble("imageExportFactor")); else if (name.endsWith(".svg")) SVGConversion.createSVG(file); else if (name.endsWith(".pdf")) { PresentationNotes.createMapAsPDF(file); } else if (name.endsWith(".zip")) { Vector resourceVector = new Vector(); Iterator i = map.getAllDescendents(LWComponent.ChildKind.PROPER).iterator(); while (i.hasNext()) { LWComponent component = (LWComponent) i.next(); System.out.println("Component:" + component + " has resource:" + component.hasResource()); if (component.hasResource() && (component.getResource() instanceof URLResource)) { URLResource resource = (URLResource) component.getResource(); try { if (resource.isLocalFile()) { String spec = resource.getSpec(); System.out.println(resource.getSpec()); Vector row = new Vector(); row.add(new Boolean(true)); row.add(resource); row.add(new Long(file.length())); row.add("Ready"); resourceVector.add(row); } } catch (Exception ex) { System.out.println("Publisher.setLocalResourceVector: Resource " + resource.getSpec() + ex); ex.printStackTrace(); } } } File savedCMap = PublishUtil.createZip(map, resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; try { while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); } catch (Exception e) { e.printStackTrace(); } finally { istream.close(); ostream.close(); } } else if (name.endsWith(".html")) { HtmlOutputDialog hod = new HtmlOutputDialog(); hod.setVisible(true); if (hod.getReturnVal() > 0) new ImageMap().createImageMap(file, hod.getScale(), hod.getFormat()); } else if (name.endsWith(".rdf")) { edu.tufts.vue.rdf.RDFIndex index = new edu.tufts.vue.rdf.RDFIndex(); String selectionType = VueResources.getString("rdf.export.selection"); if (selectionType.equals("ALL")) { Iterator<LWMap> maps = VUE.getLeftTabbedPane().getAllMaps(); while (maps.hasNext()) { index.index(maps.next()); } } else if (selectionType.equals("ACTIVE")) { index.index(VUE.getActiveMap()); } else { index.index(VUE.getActiveMap()); } FileWriter writer = new FileWriter(file); index.write(writer); writer.close(); } else if (name.endsWith(VueUtil.VueArchiveExtension)) { Archive.writeArchive(map, file); } else { Log.warn("Unknown save type for filename extension: " + name); return false; } Log.debug("Save completed for " + file); if (!VUE.isApplet()) { VueFrame frame = (VueFrame) VUE.getMainWindow(); String title = VUE.getName() + ": " + name; frame.setTitle(title); } if (name.endsWith(".vue")) { RecentlyOpenedFilesManager rofm = RecentlyOpenedFilesManager.getInstance(); rofm.updateRecentlyOpenedFiles(file.getAbsolutePath()); } return true; } catch (Throwable t) { Log.error("Exception attempting to save file " + file + ": " + t); Throwable e = t; if (t.getCause() != null) e = t.getCause(); if (e instanceof java.io.FileNotFoundException) { Log.error("Save Failed: " + e); } else { Log.error("Save failed for \"" + file + "\"; ", e); } if (e != t) Log.error("Exception attempting to save file " + file + ": " + e); VueUtil.alert(String.format(Locale.getDefault(), VueResources.getString("saveaction.savemap.error") + "\"%s\";\n" + VueResources.getString("saveaction.targetfiel") + "\n\n" + VueResources.getString("saveaction.problem"), map.getLabel(), file, Util.formatLines(e.toString(), 80)), "Problem Saving Map"); } finally { GUI.invokeAfterAWT(new Runnable() { public void run() { GUI.clearWaitCursor(); } }); } return false; }
|
00
|
Code Sample 1:
public static Vector webService(String siteUrl, String login, String password, String table, String station, String element, String dayFrom, String dayTo, String filePath) throws Exception { Service service = new Service(); Call call = (Call) service.createCall(); if (login != null) { call.setUsername(login); if (password != null) { call.setPassword(password); } System.err.println("Info: authentication user=" + login + " passwd=" + password + " at " + siteUrl); } call.setTargetEndpointAddress(new URL(siteUrl)); call.setOperationName("syncData"); Vector exportList = (Vector) call.invoke(new Object[] { table, station, element, dayFrom, dayTo }); if (exportList != null) { for (int k = 0; k < exportList.size(); k++) { HashMap exportDescr = (HashMap) exportList.get(k); String url = (String) exportDescr.get("fileName"); log.debug("result URL is " + url); String fileName = null; URL dataurl = new URL(url); String filePart = dataurl.getFile(); if (filePart == null) { throw new Exception("Error: file part in the data URL is null"); } else { fileName = filePart.substring(filePart.lastIndexOf("/") < 0 ? 0 : filePart.lastIndexOf("/") + 1); if (filePath != null) { fileName = filePath + fileName; } log.debug("local file name is " + fileName); } FileOutputStream fos = new FileOutputStream(fileName); if (fos == null) { throw new Exception("Error: file output stream is null"); } InputStream strm = dataurl.openStream(); if (strm == null) { throw new Exception("Error: data input stream is null"); } else { int c; while ((c = strm.read()) != -1) { fos.write(c); } } strm.close(); fos.close(); File file = new File(fileName); exportDescr.put("fileName", file.getCanonicalPath()); } } return exportList; }
Code Sample 2:
public void playSIDFromURL(String name) { player.reset(); player.setStatus("Loading song: " + name); URL url; try { if (name.startsWith("http")) { url = new URL(name); } else { url = getResource(name); } if (player.readSID(url.openConnection().getInputStream())) { player.playSID(); } } catch (IOException ioe) { System.out.println("Could not load: "); ioe.printStackTrace(); player.setStatus("Could not load SID: " + ioe.getMessage()); } }
|
11
|
Code Sample 1:
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) { } } } }
Code Sample 2:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
|
11
|
Code Sample 1:
private void processData(InputStream raw) { String fileName = remoteName; if (localName != null) { fileName = localName; } try { FileOutputStream fos = new FileOutputStream(new File(fileName), true); IOUtils.copy(raw, fos); LOG.info("ok"); } catch (IOException e) { LOG.error("error writing file", e); } }
Code Sample 2:
protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } }
|
11
|
Code Sample 1:
public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } }
Code Sample 2:
public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
|
00
|
Code Sample 1:
public String grabId(String itemName) throws Exception { StringBuffer modified = new StringBuffer(itemName); for (int i = 0; i <= modified.length() - 1; i++) { char ichar = modified.charAt(i); if (ichar == ' ') modified = modified.replace(i, i + 1, "+"); } itemName = modified.toString(); try { URL url = new URL(searchURL + itemName); InputStream urlStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); while (reader.ready()) { String htmlLine = reader.readLine(); int indexOfSearchStart = htmlLine.indexOf(searchForItemId); if (indexOfSearchStart != -1) { int idStart = htmlLine.indexOf("=", indexOfSearchStart); idStart++; int idEnd = htmlLine.indexOf("'", idStart); id = htmlLine.substring(idStart, idEnd); } } if (id == "") return null; else return id; } catch (Exception ex) { System.out.println("Exception in lookup: " + ex); throw (ex); } }
Code Sample 2:
@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET) public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception { File file = new File(STORAGE_PATH + fileName + ".jpg"); res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpg"); ServletOutputStream ostream = res.getOutputStream(); IOUtils.copy(new FileInputStream(file), ostream); ostream.flush(); ostream.close(); }
|
11
|
Code Sample 1:
public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public static void main(String[] args) throws Exception { URL url = new URL("http://www.yahoo.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = ""; String page = ""; while ((line = br.readLine()) != null) { page += line; } System.out.println(page); }
|
11
|
Code Sample 1:
public static String getMD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
@SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; }
|
00
|
Code Sample 1:
public void delete(String fileName) throws IOException { log.debug("deleting: " + fileName); URL url = new URL(this.endpointURL + "?operation=delete&filename=" + fileName); URLConnection connection = url.openConnection(); connection.setDoOutput(false); connection.setDoInput(true); connection.setUseCaches(false); connection.getInputStream(); }
Code Sample 2:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
|
11
|
Code Sample 1:
public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); }
Code Sample 2:
public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
|
00
|
Code Sample 1:
public List<DemandeChargement> getArtistToLoadFromWiki() throws Exception { URL fileURL = new URL("http://beastchild.free.fr/wiki/doku.php?id=music"); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; List<DemandeChargement> dem = new ArrayList<DemandeChargement>(); while ((ligne = br.readLine()) != null) { if (ligne.indexOf("<@@@>") != -1) { String maidS = ligne.substring(ligne.indexOf("<@@@>") + 11, ligne.indexOf("</@@@>")).trim(); try { long maid = Long.parseLong(maidS); log.info("MAID to load : " + maid); dem.add(new DemandeChargement(maid)); } catch (Exception e) { log.error("Impossible de recuperer le MAID : " + maidS); } } } br.close(); httpStream.close(); return dem; }
Code Sample 2:
void setURLString(String path, boolean forceLoad) { if (path != null) { if (this.url != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5")); try { URL url = new URL(path); InputStream stream; stream = url.openStream(); stream.close(); } catch (Exception e) { throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0")); } } this.urlString = path; if (forceLoad) dispatchMessage(); }
|
11
|
Code Sample 1:
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
Code Sample 2:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
|
00
|
Code Sample 1:
public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
Code Sample 2:
public String getInternetData() throws Exception { BufferedReader in = null; String data = null; try { HttpClient client = new DefaultHttpClient(); URI website = new URI("http://code.google.com/p/gadi-works"); HttpGet request = new HttpGet(); request.setURI(website); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String l = ""; String nl = System.getProperty("line.separator"); while ((l = in.readLine()) != null) { sb.append(l + nl); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
|
00
|
Code Sample 1:
@Test public void usingStream() throws IOException, NameNotFoundException { URL url = new URL("ftp://ftp.ebi.ac.uk/pub/databases/interpro/entry.list"); InterproNameHandler handler = new InterproNameHandler(url.openStream()); String interproName = handler.getNameById("IPR008255"); assertNotNull(interproName); assertEquals("Pyridine nucleotide-disulphide oxidoreductase, class-II, active site", interproName); assertEquals(null, handler.getNameById("Active_site")); }
Code Sample 2:
public void load() { try { isSourceWorking = true; URLConnection urlConnection = url.openConnection(); ontologyServiceMetaData.setName("Ontology for " + url.getFile()); parseDocument(urlConnection.getInputStream()); buildTree(); isSourceWorking = true; String statusOKMessage = PedroResources.getMessage("ontology.statusOK", url.getFile()); status = new StringBuffer(); status.append(statusOKMessage); } catch (Exception err) { err.printStackTrace(System.out); String statusErrorMessage = PedroResources.getMessage("ontology.statusError", err.toString()); status.append(statusErrorMessage); isSourceWorking = false; } }
|
00
|
Code Sample 1:
@Override public final boolean save() throws RecordException, RecordValidationException, RecordValidationSyntax { if (frozen) { throw new RecordException("The object is frozen."); } boolean toReturn = false; Class<? extends Record> actualClass = this.getClass(); HashMap<String, Integer> columns = getColumns(TableNameResolver.getTableName(actualClass)); Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; try { if (exists()) { doValidations(true); StatementBuilder builder = new StatementBuilder("update " + TableNameResolver.getTableName(actualClass) + " set"); String updates = ""; for (String key : columns.keySet()) { if (!key.equals("id")) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } updates += key + " = :" + key + ", "; builder.set(key, FieldHandler.getValue(f, this)); } } builder.append(updates.substring(0, updates.length() - 2)); builder.append("where id = :id"); builder.set(":id", FieldHandler.getValue(FieldHandler.findField(actualClass, "id"), this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } else { doValidations(false); StatementBuilder builder = new StatementBuilder("insert into " + TableNameResolver.getTableName(actualClass) + " "); String names = ""; String values = ""; for (String key : columns.keySet()) { Field f = null; try { f = FieldHandler.findField(actualClass, key); } catch (FieldOrMethodNotFoundException e) { throw new RecordException("Database column name >" + key + "< not found in class " + actualClass.getCanonicalName()); } if (key.equals("id") && (Integer) FieldHandler.getValue(f, this) == 0) { continue; } names += key + ", "; values += ":" + key + ", "; builder.set(key, f.get(this)); } names = names.substring(0, names.length() - 2); values = values.substring(0, values.length() - 2); builder.append("(" + names + ")"); builder.append("values"); builder.append("(" + values + ")"); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); toReturn = i == 1; } if (childList != null) { if (childObjects == null) { childObjects = new HashMap<Class<? extends Record>, Record>(); } for (Class<? extends Record> c : childList.keySet()) { if (childObjects.get(c) != null) { childObjects.get(c).save(); } } } if (childrenList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : childrenList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } if (relatedList != null) { if (childrenObjects == null) { childrenObjects = new HashMap<Class<? extends Record>, List<? extends Record>>(); } for (Class<? extends Record> c : relatedList.keySet()) { if (childrenObjects.get(c) != null) { for (Record r : childrenObjects.get(c)) { r.save(); } } } } return toReturn; } catch (Exception e) { if (e instanceof RecordValidationException) { throw (RecordValidationException) e; } if (e instanceof RecordValidationSyntax) { throw (RecordValidationSyntax) e; } try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
|
11
|
Code Sample 1:
public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
Code Sample 2:
public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); }
|
00
|
Code Sample 1:
public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; }
Code Sample 2:
@Override List<String> HttpGet(URL url) throws IOException { List<String> responseList = new ArrayList<String>(); Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(20000); con.setAllowUserInteraction(false); responseList.add(con.getResponseCode() + " " + con.getResponseMessage()); InputStream inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) responseList.add(inputLine); in.close(); return responseList; }
|
00
|
Code Sample 1:
public static boolean copyFile(final File fileFrom, final File fileTo) { assert fileFrom != null : "fileFrom is null"; assert fileTo != null : "fileTo is null"; LOGGER.info(buildLogString(COPY_FILE_INFO, new Object[] { fileFrom, fileTo })); boolean error = true; FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(fileFrom); outputStream = new FileOutputStream(fileTo); final FileChannel inChannel = inputStream.getChannel(); final FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); error = false; } catch (final IOException e) { LOGGER.log(SEVERE, buildLogString(COPY_FILE_ERROR, new Object[] { fileFrom, fileTo }), e); } finally { closeCloseable(inputStream, fileFrom); closeCloseable(outputStream, fileTo); } return error; }
Code Sample 2:
public InputStream openFileInputStream(String fileName) throws IOException { if (fileName.indexOf(':') > 1) { URL url = new URL(fileName); InputStream in = url.openStream(); return in; } fileName = translateFileName(fileName); FileInputStream in = new FileInputStream(fileName); trace("openFileInputStream", fileName, in); return in; }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public 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 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 String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
|
00
|
Code Sample 1:
public Bits write(Map data) throws IOException { String pictureurl = (String) data.get("pictureurl"); URL url = new URL(pictureurl); InputStream is = url.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int buf = is.read(); while (buf >= 0) { baos.write(buf); buf = is.read(); } return BitUtils._concat(BitUtils._bitsUI16(TypeUtils.toLong(data.get("shapeId"))), BitUtils._bytesToBits(baos.toByteArray())); }
Code Sample 2:
public FileOutputStream transfer(File from, File to, long mark) throws IOException, InterruptedException { if (out != null) { close(); } FileChannel fch = new FileInputStream(from).getChannel(); FileChannel rollch = new FileOutputStream(to).getChannel(); long size = mark; int count = 0; try { while ((count += rollch.transferFrom(fch, count, size - count)) < size) { } } finally { fch.close(); rollch.close(); } out = create(to); return out; }
|
11
|
Code Sample 1:
public static int gunzipFile(File file_input, File dir_output) { GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } String file_input_name = file_input.getName(); String file_output_name = file_input_name.substring(0, file_input_name.length() - 3); File output_file = new File(dir_output, file_output_name); byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } try { gzip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; }
Code Sample 2:
private static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
11
|
Code Sample 1:
@Test public void testDocumentDownloadExcel() throws IOException { if (uploadedExcelDocumentID == null) { fail("Document Upload Test should run first"); } String downloadLink = GoogleDownloadLinkGenerator.generateXlDownloadLink(uploadedExcelDocumentID); URL url = new URL(downloadLink); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream input = url.openStream(); FileWriter fw = new FileWriter("tmpOutput.kb"); Reader reader = new InputStreamReader(input); BufferedReader bufferedReader = new BufferedReader(reader); String strLine = ""; int count = 0; while (count < 10000) { strLine = bufferedReader.readLine(); if (strLine != null && strLine != "") { fw.write(strLine); } count++; } }
Code Sample 2:
public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load " + name); return classList; } while (services.hasMoreElements()) { URL url = (URL) services.nextElement(); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: " + url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: " + url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String) names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: " + className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: " + className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: " + className); } catch (NoClassDefFoundError e) { System.err.println("Service: " + e + " for " + className); } catch (Exception e) { System.err.println("Service: exception for: " + className + " " + e); } } return classList; }
|
11
|
Code Sample 1:
public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } }
Code Sample 2:
public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
11
|
Code Sample 1:
public void updateComponent(int id, int quantity) throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "UPDATE components SET quantity=quantity+? WHERE comp_id=?"; ps = connection.prepareStatement(query); ps.setInt(1, quantity); ps.setInt(2, id); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
Code Sample 2:
public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); Compressor compressor = null; try { compressor = CodecPool.getCompressor(codec); CompressionOutputStream out = codec.createOutputStream(System.out, compressor); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); } finally { CodecPool.returnCompressor(compressor); } }
|
11
|
Code Sample 1:
private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } }
Code Sample 2:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } }
Code Sample 2:
public void testHttpsConnection() { try { URL url = new URL("https://addons.mozilla.org/zh-CN/firefox/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.getOutputStream().write("hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } }
Code Sample 2:
public EncodedScript(PackageScript source, DpkgData data) throws IOException { _source = source; final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream output = null; try { output = MimeUtility.encode(bytes, BASE64); } catch (final MessagingException e) { throw new IOException("Failed to uuencode script. name=[" + _source.getFriendlyName() + "], reason=[" + e.getMessage() + "]."); } IOUtils.write(HEADER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); IOUtils.copy(_source.getSource(data), output); output.flush(); IOUtils.write(FOOTER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); output.close(); bytes.close(); _encoded = bytes.toString(Dpkg.CHAR_ENCODING); }
|
11
|
Code Sample 1:
public void copy(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s265") + sourcePath, AcideLanguageManager.getInstance().getLabels().getString("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s267") + targetPath, AcideLanguageManager.getInstance().getLabels().getString("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } } }
Code Sample 2:
private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.