label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
11
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } }
00
Code Sample 1: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; } Code Sample 2: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } }
00
Code Sample 1: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; } Code Sample 2: public void moveRuleDown(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, language, tag); if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number (" + row + ") was not between 1 and " + (max - 1)); stmt.executeUpdate("update LanguageMorphologies set Rank = -1 " + "where Rank = " + row + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + row + "where Rank = " + (row + 1) + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + (row + 1) + "where Rank = -1 and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); 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); } }
00
Code Sample 1: public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); } Code Sample 2: private static BufferedReader createReaderConnection(String urlString) throws SiteNotFoundException { BufferedReader reader = null; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-agent", "Mozilla/4.5"); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { Logger.logln("Response code for url [" + urlString + "] was " + conn.getResponseCode() + " [" + conn.getResponseMessage() + "]"); throw new SiteNotFoundException(urlString); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException ex) { Logger.logln("" + ex); } return reader; }
00
Code Sample 1: @Override public List<Type> getArtifactTypes(String organisationName, String artifactName, String version) { if (cache != null) { Date d; try { d = cache.getTypesLastUpdate(organisationName, artifactName, version); if (d.compareTo(cacheExpirationDate) >= 0) { return cache.getTypes(organisationName, artifactName, version); } } catch (CacheAccessException e) { log.warn("cannot access cache", e); } } List<Type> types = new ArrayList<Type>(); String urlString = generateUrlString(organisationName, artifactName, version, Type.JAR); try { new URL(urlString).openStream(); types.add(Type.JAR); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.SRC); try { new URL(urlString).openStream(); types.add(Type.SRC); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.WAR); try { new URL(urlString).openStream(); types.add(Type.WAR); } catch (MalformedURLException e) { } catch (IOException e) { } urlString = generateUrlString(organisationName, artifactName, version, Type.ZIP); try { new URL(urlString).openStream(); types.add(Type.ZIP); } catch (MalformedURLException e) { } catch (IOException e) { } if (cache != null) { try { cache.updateTypes(organisationName, artifactName, version, types); } catch (CacheAccessException e) { log.warn("cannot access cache", e); } } return types; } Code Sample 2: public boolean checkTypeChange(Class<?> clazz, File buildDir, File refFile) throws MojoExecutionException { if (!clazz.isPrimitive()) { ClassLoader cl = clazz.getClassLoader(); if (cl == loader) { if (clazz.isArray()) return checkTypeChange(getArrayType(clazz), buildDir, refFile); String path = clazz.getName().replace('.', File.separatorChar) + ".class"; File file = new File(buildDir, path); long lastMod = Long.MAX_VALUE; if (!file.exists()) { URL url = cl.getResource(path); if (url == null) throw new MojoExecutionException("Can't get URL for webservice class '" + clazz.getName() + "' from jar file."); else { try { JarURLConnection con = (JarURLConnection) url.openConnection(); lastMod = con.getJarEntry().getTime(); } catch (IOException x) { throw new MojoExecutionException("Can't get modification time for webservice class '" + clazz.getName() + "' from jar file."); } } } else { lastMod = file.lastModified(); } if (refFile.lastModified() < lastMod) return true; if (clazz.isInterface()) { Class<?>[] itfs = clazz.getInterfaces(); for (int i = 0; i < itfs.length; i++) { boolean changed = checkTypeChange(itfs[i], buildDir, refFile); if (changed) return true; } } else { Class<?> sup = clazz.getSuperclass(); boolean changed = checkTypeChange(sup, buildDir, refFile); if (changed) return true; } } } return false; }
11
Code Sample 1: public static String getHash(String input) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } m.update(input.getBytes(), 0, input.length()); return new BigInteger(1, m.digest()).toString(16); } Code Sample 2: public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
11
Code Sample 1: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } Code Sample 2: public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } }
11
Code Sample 1: public static void copyFromTo(String src, String des) { staticprintln("Copying:\"" + src + "\"\nto:\"" + des + "\""); try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(des).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.toString(); } } 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(); } }
11
Code Sample 1: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); 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: private void checkChartsyRegistration(String username, String password) { HttpPost post = new HttpPost(NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.chartsyRegisterURL")); String message = ""; try { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", username)); nvps.add(new BasicNameValuePair("password", password)); post.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = ProxyManager.httpClient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { String[] lines = EntityUtils.toString(entity).split("\n"); if (lines[0].equals("OK")) { RegisterAction.preferences.putBoolean("registred", true); RegisterAction.preferences.put("name", lines[1]); RegisterAction.preferences.put("email", lines[2]); RegisterAction.preferences.put("date", String.valueOf(Calendar.getInstance().getTimeInMillis())); RegisterAction.preferences.put("username", username); RegisterAction.preferences.put("password", new String(passwordTxt.getPassword())); if (lines[1] != null && !lines[1].isEmpty()) { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerDone.withUsername.message", lines[1]); } else { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerDone.noUsername.message"); } } else { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerAuthError.message"); } EntityUtils.consume(entity); } } catch (Exception ex) { message = NbBundle.getMessage(RegisterPanel.class, "RegisterPanel.registerConnectionError.message"); } finally { post.abort(); } messageLbl.setText(message); messageLbl.setVisible(true); } Code Sample 2: public Certificate(URL url) throws CertificateException { try { URLConnection con = url.openConnection(); InputStream in2 = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(in2)); String inputLine; StringBuffer cert = new StringBuffer(); while ((inputLine = in.readLine()) != null) { cert.append(inputLine); cert.append("\n"); } in.close(); this.certificate = cert.toString(); } catch (IOException ex) { throw new CertificateException("Unable to read in credential: " + ex.getMessage(), ex); } loadCredential(this.certificate); }
00
Code Sample 1: public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } } if (destination != null) { destination.close(); } } Code Sample 2: @MediumTest public void testUrlRewriteRules() throws Exception { ContentResolver resolver = getContext().getContentResolver(); GoogleHttpClient client = new GoogleHttpClient(resolver, "Test", false); Settings.Gservices.putString(resolver, "url:test", "http://foo.bar/ rewrite " + mServerUrl + "new/"); Settings.Gservices.putString(resolver, "digest", mServerUrl); try { HttpGet method = new HttpGet("http://foo.bar/path"); HttpResponse response = client.execute(method); String body = EntityUtils.toString(response.getEntity()); assertEquals("/new/path", body); } finally { client.close(); } }
00
Code Sample 1: public InputStream getInputStream(long offset) throws IOException { if (is != null && raf == null) { try { is.close(); } catch (Throwable th) { } finally { is = null; } } if (is == null && getUrl() != null && getFile() == null) { is = url.openStream(); } if (is == null) { if (getFile() != null) { raf = null; try { raf = new RandomAccessFile(getFile(), "r"); } catch (Exception ex) { } is = (raf != null) ? new RAFInputStream(raf, 0) : new BufferedInputStream(new FileInputStream(getFile()), 1024 * 30); } } if (is instanceof RAFInputStream) { RAFInputStream ris = (RAFInputStream) is; ris.seek(offset); } else { is.skip(offset); } return is; } Code Sample 2: public static void logout(String verify) throws NetworkException { HttpClient client = HttpUtil.newInstance(); HttpGet get = new HttpGet(HttpUtil.KAIXIN_LOGOUT_URL + HttpUtil.KAIXIN_PARAM_VERIFY + verify); HttpUtil.setHeader(get); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
00
Code Sample 1: public static boolean doExecuteBatchSQL(List<String> sql) { session = currentSession(); Connection conn = session.connection(); PreparedStatement ps = null; try { conn.setAutoCommit(false); Iterator iter = sql.iterator(); while (iter.hasNext()) { String sqlstr = (String) iter.next(); log("[SmsManager] doing sql:" + sqlstr); ps = conn.prepareStatement(sqlstr); ps.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); return true; } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } return false; } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } closeHibernateSession(); } } Code Sample 2: protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); }
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: public byte[] read(IFile input) { InputStream contents = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); contents = input.getContents(); IOUtils.copy(contents, baos); return baos.toByteArray(); } catch (IOException e) { Activator.logUnexpected(null, e); } catch (CoreException e) { Activator.logUnexpected(null, e); } finally { IOUtils.closeQuietly(contents); } return null; }
00
Code Sample 1: public static boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; } Code Sample 2: public static final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
00
Code Sample 1: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } } 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: private void createSaveServiceProps() throws MojoExecutionException { saveServiceProps = new File(workDir, "saveservice.properties"); try { FileWriter out = new FileWriter(saveServiceProps); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("saveservice.properties"), out); out.flush(); out.close(); System.setProperty("saveservice_properties", File.separator + "target" + File.separator + "jmeter" + File.separator + "saveservice.properties"); } catch (IOException e) { throw new MojoExecutionException("Could not create temporary saveservice.properties", e); } } Code Sample 2: @Override public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { URL baseUrl = this.baseUrl; if (this.baseUrl == null) { baseUrl = url; } InputStream in; try { in = url.openStream(); } catch (IOException ex) { throw new FileNotFoundException("Can't read " + url); } return load(new BufferedInputStream(in), baseUrl); }
11
Code Sample 1: protected File compress(File orig, IWrapCompression wrapper) throws IOException { File compressed = File.createTempFile("test.", ".gz"); FileOutputStream fos = new FileOutputStream(compressed); OutputStream wos = wrapper.wrap(fos); FileInputStream fis = new FileInputStream(orig); IOUtils.copy(fis, wos); IOUtils.closeQuietly(fis); IOUtils.closeQuietly(wos); return compressed; } Code Sample 2: public static void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: public TVRageShowInfo(String xmlShowName, String xmlSearchBy) { String[] tmp, tmp2; String line = ""; this.usrShowName = xmlShowName; try { URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); while ((line = in.readLine()) != null) { tmp = line.split("@"); if (tmp[0].equals("Show Name")) showName = tmp[1]; if (tmp[0].equals("Show URL")) showURL = tmp[1]; if (tmp[0].equals("Latest Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); latestSeasonNum = tmp2[0]; latestEpisodeNum = tmp2[1]; if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1); } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken(); } } if (tmp[0].equals("Next Episode")) { StringTokenizer st = new StringTokenizer(tmp[1], "^"); for (int i = 0; st.hasMoreTokens(); i++) { if (i == 0) { tmp2 = st.nextToken().split("x"); nextSeasonNum = tmp2[0]; nextEpisodeNum = tmp2[1]; if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1); } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken(); } } if (tmp[0].equals("Status")) status = tmp[1]; if (tmp[0].equals("Airtime") && tmp.length > 1) { airTime = tmp[1]; } } if (airTime.length() > 10) { tmp = airTime.split("at"); airTimeHour = tmp[1]; } in.close(); if (xmlSearchBy.equals("Showname SeriesNum")) { url = new URL(showURL); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = in.readLine()) != null) { if (line.indexOf("<b>Latest Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[5].indexOf(':') > -1) { tmp = tmp[5].split(":"); latestSeriesNum = tmp[0]; } } else if (line.indexOf("<b>Next Episode: </b>") > -1) { tmp = line.split("'>"); if (tmp[3].indexOf(':') > -1) { tmp = tmp[3].split(":"); nextSeriesNum = tmp[0]; } } } in.close(); } } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public void setPage(String url) { System.out.println("SetPage(" + url + ")"); if (url != null) { if (!url.startsWith("http://")) { url = "http://" + url; } boolean exists = false; for (int i = 0; i < urlComboBox.getItemCount(); i++) { if (((String) urlComboBox.getItemAt(i)).equals(url)) { exists = true; urlComboBox.setSelectedItem(url); } } if (!exists) { int i = urlComboBox.getSelectedIndex(); if (i == -1 || urlComboBox.getItemCount() == 0) { i = 0; } else { i++; } urlComboBox.insertItemAt(url, i); urlComboBox.setSelectedItem(url); } boolean image = false; for (final String element : imageExtensions) { if (url.endsWith(element)) { image = true; } } try { if (image) { final String html = "<html><img src=\"" + url + "\"></html>"; } else { final String furl = url; Runnable loadPage = new Runnable() { public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } }; new Thread(loadPage).start(); } } catch (final Throwable exception) { System.out.println("Error in Browser.setPage(): " + exception); } } }
11
Code Sample 1: public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); } Code Sample 2: public static boolean copy(File from, File to, Override override) throws IOException { FileInputStream in = null; FileOutputStream out = null; FileChannel srcChannel = null; FileChannel destChannel = null; if (override == null) override = Override.NEWER; switch(override) { case NEVER: if (to.isFile()) return false; break; case NEWER: if (to.isFile() && (from.lastModified() - LASTMODIFIED_DIFF_MILLIS) < to.lastModified()) return false; break; } to.getParentFile().mkdirs(); try { in = new FileInputStream(from); out = new FileOutputStream(to); srcChannel = in.getChannel(); destChannel = out.getChannel(); long position = 0L; long count = srcChannel.size(); while (position < count) { long chunk = Math.min(MAX_IO_CHUNK_SIZE, count - position); position += destChannel.transferFrom(srcChannel, position, chunk); } to.setLastModified(from.lastModified()); return true; } finally { CommonUtils.close(srcChannel); CommonUtils.close(destChannel); CommonUtils.close(out); CommonUtils.close(in); } }
11
Code Sample 1: public File nextEntry() { try { while (hasNext()) { String name = waitingArchEntry.getName(); name = name.substring(name.indexOf("/") + 1); File file = new File(targetDir.getAbsolutePath() + "/" + name); if (waitingArchEntry.isDirectory()) { file.mkdirs(); waitingArchEntry = ais.getNextEntry(); } else { OutputStream os = new FileOutputStream(file); try { IOUtils.copy(ais, os); } finally { IOUtils.closeQuietly(os); } return file; } } } catch (IOException e) { return null; } return null; } Code Sample 2: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
11
Code Sample 1: public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); } Code Sample 2: public String getHash(String key, boolean base64) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(key.getBytes()); if (base64) return new String(new Base64().encode(md.digest()), "UTF8"); else return new String(md.digest(), "UTF8"); }
00
Code Sample 1: public void adicionaCliente(ClienteBean cliente) { PreparedStatement pstmt = null; ResultSet rs = null; String sql = "insert into cliente(nome,cpf,telefone,cursoCargo,bloqueado,ativo,tipo) values(?,?,?,?,?,?,?)"; try { pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, cliente.getNome()); pstmt.setString(2, cliente.getCPF()); pstmt.setString(3, cliente.getTelefone()); pstmt.setString(4, cliente.getCursoCargo()); pstmt.setString(5, cliente.getBloqueado()); pstmt.setString(6, cliente.getAtivo()); pstmt.setString(7, cliente.getTipo()); pstmt.executeUpdate(); rs = pstmt.getGeneratedKeys(); if (rs.next()) { cliente.setIdCliente(rs.getLong(1)); } connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao inserir cliente.", ex1); } throw new RuntimeException("Erro ao inserir cliente.", ex); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } } Code Sample 2: public InputStream getResourceAsStream(String name) { try { URL url = getResource(name); System.out.println("Loading \"" + url + "\"..."); URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); System.out.println(httpURLConnection.getResponseMessage() + ", " + httpURLConnection.getContentLength() + " bytes" + ", " + new Date(httpURLConnection.getDate()) + ", " + new Date(httpURLConnection.getLastModified())); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } } return urlConnection.getInputStream(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
11
Code Sample 1: @Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + outputDigest + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } } Code Sample 2: public String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { } return digest; }
00
Code Sample 1: private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } } Code Sample 2: private final Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) { synchronized (results) { Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); Vector<Class<?>> v = new Vector<Class<?>>(); String fqcn = searchClass.getName(); List<URL> knownLocations = new ArrayList<URL>(); knownLocations.add(location); for (int loc = 0; loc < knownLocations.size(); loc++) { URL url = knownLocations.get(loc); File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Class<?> c = Class.forName(packageName + "." + classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { if (debug) { errors.add(cnfex); } } catch (Exception ex) { if (debug) { errors.add(ex); } } catch (NoClassDefFoundError ncdfe) { if (debug) { errors.add(ncdfe); } } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (!entry.isDirectory() && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Class c = Class.forName(classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (NoClassDefFoundError ncdfe) { errors.add(ncdfe); } catch (UnsatisfiedLinkError ule) { errors.add(ule); } catch (Exception exception) { errors.add(exception); } catch (Error error) { errors.add(error); } } } } catch (IOException ioex) { errors.add(ioex); } } } results.putAll(thisResult); Iterator<Class<?>> it = thisResult.keySet().iterator(); while (it.hasNext()) { v.add(it.next()); } return v; } }
11
Code Sample 1: public File takeFile(File f, String prefix, String suffix) throws IOException { File nf = createNewFile(prefix, suffix); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); FileOutputStream fos = new FileOutputStream(nf); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); f.delete(); return nf; } Code Sample 2: public static void copy(final String source, final String dest) { final File s = new File(source); final File w = new File(dest); try { final FileInputStream in = new FileInputStream(s); final FileOutputStream out = new FileOutputStream(w); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } }
00
Code Sample 1: public void run() { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Checking for updates at " + checkUrl); } URL url = new URL(checkUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String s = reader.readLine(); while (s != null) { content.append(s); s = reader.readLine(); } LOGGER.info("update-available", content.toString()); } else if (LOGGER.isDebugEnabled()) { LOGGER.debug("No update available (Response code " + connection.getResponseCode() + ")"); } } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Update check failed", e); } } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile()); FileInputStream fi = new FileInputStream(source); FileChannel fic = fi.getChannel(); MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length()); fic.close(); fi.close(); fi = null; if (!dest.exists()) { String destPath = dest.getPath(); log.debug("Destination path: {}", destPath); String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar)); log.debug("Destination dir: {}", destDir); File dir = new File(destDir); if (!dir.exists()) { if (dir.mkdirs()) { log.debug("Directory created"); } else { log.warn("Directory not created"); } } dir = null; } FileOutputStream fo = new FileOutputStream(dest); FileChannel foc = fo.getChannel(); foc.write(mbuf); foc.close(); fo.close(); fo = null; mbuf.clear(); mbuf = null; }
11
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: 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:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</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()); } Code Sample 2: private final void reOrderFriendsListByOnlineStatus() { boolean flag = true; while (flag) { flag = false; for (int i = 0; i < friendsCount - 1; i++) if (friendsListOnlineStatus[i] < friendsListOnlineStatus[i + 1]) { int j = friendsListOnlineStatus[i]; friendsListOnlineStatus[i] = friendsListOnlineStatus[i + 1]; friendsListOnlineStatus[i + 1] = j; long l = friendsListLongs[i]; friendsListLongs[i] = friendsListLongs[i + 1]; friendsListLongs[i + 1] = l; flag = true; } } }
00
Code Sample 1: public ProgramProfilingSymbol updateProgramProfilingSymbol(int id, int configID, int programSymbolID) throws AdaptationException { ProgramProfilingSymbol pps = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE ProgramProfilingSymbols SET " + "projectDeploymentConfigurationID = " + configID + ", " + "programSymbolID = " + programSymbolID + ", " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from ProgramProfilingSymbols WHERE " + "id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } pps = getProfilingSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramProfilingSymbol"; 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 pps; } Code Sample 2: private ContactModel convertJajahContactToContact(com.funambol.jajah.www.Contact jajahContact) throws JajahException { String temp; if (log.isTraceEnabled()) { log.trace("Converting Jajah contact to Foundation contact: Name:" + jajahContact.getName() + " Email:" + jajahContact.getEmail()); } try { ContactModel contactModel; Contact contact = new Contact(); if (jajahContact.getName() != null && jajahContact.getName().equals("") == false) { if (log.isDebugEnabled()) { log.debug("NAME: " + jajahContact.getName()); } contact.getName().getFirstName().setPropertyValue(jajahContact.getName()); } if (jajahContact.getEmail() != null && jajahContact.getEmail().equals("") == false) { if (log.isDebugEnabled()) { log.debug("EMAIL1_ADDRESS: " + jajahContact.getEmail()); } Email email1 = new Email(); email1.setEmailType(SIFC.EMAIL1_ADDRESS); email1.setPropertyValue(jajahContact.getEmail()); contact.getPersonalDetail().addEmail(email1); } if (jajahContact.getMobile() != null && jajahContact.getMobile().equals("") == false) { if (log.isDebugEnabled()) { log.debug("MOBILE_TELEPHONE_NUMBER: " + jajahContact.getMobile()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.MOBILE_TELEPHONE_NUMBER); temp = jajahContact.getMobile().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getLandline() != null && jajahContact.getLandline().equals("") == false) { if (log.isDebugEnabled()) { log.debug("HOME_TELEPHONE_NUMBER: " + jajahContact.getLandline()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.HOME_TELEPHONE_NUMBER); temp = jajahContact.getLandline().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getOffice() != null && jajahContact.getOffice().equals("") == false) { if (log.isDebugEnabled()) { log.debug("BUSINESS_TELEPHONE_NUMBER: " + jajahContact.getOffice()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.BUSINESS_TELEPHONE_NUMBER); temp = jajahContact.getOffice().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getBusinessDetail().addPhone(phone); } if (log.isDebugEnabled()) { log.debug("CONTACT_ID: " + jajahContact.getId()); } contactModel = new ContactModel(String.valueOf(jajahContact.getId()), contact); ContactToSIFC convert = new ContactToSIFC(null, null); String sifObject = convert.convert(contactModel); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(sifObject.getBytes()); String md5Hash = (new BigInteger(m.digest())).toString(); contactModel.setMd5Hash(md5Hash); return contactModel; } catch (Exception e) { throw new JajahException("JAJAH - convertJajahContactToContact error: " + e.getMessage()); } }
00
Code Sample 1: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_name); System.out.print("Overwrite existing file " + to_name + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("FileCopy: existing file was not overwritten."); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static XMLConfigurator loadFromDefaultSystemProperty() throws IOException { String urlStr = System.getProperty(DEFAULT_SYS_PROP_NAME); if (urlStr == null || urlStr.length() == 0) { return null; } InputStream in = null; DOMRetriever xmlDoc = null; try { URL url = new URL(urlStr); xmlDoc = new DOMRetriever(in = url.openStream()); } catch (MalformedURLException e) { throw new RuntimeException(e); } finally { if (in != null) in.close(); } return newInstance(xmlDoc); }
11
Code Sample 1: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: private void copyFile(File source, File dest) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); } Code Sample 2: public void copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
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 void objectParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int indexLastSeparator; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("object"); } else { nl = doc_[currentquestion].getElementsByTagName("object"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("data"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getFile(); sOldPath = sOldPath.replace('/', File.separatorChar); indexLastSeparator = sOldPath.lastIndexOf(File.separatorChar); String sSourcePath = sOldPath; sFilename = sOldPath.substring(indexLastSeparator + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static final void parse(String infile, String outfile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(infile)); DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile)); int w = Integer.parseInt(reader.readLine()); int h = Integer.parseInt(reader.readLine()); output.writeByte(w); output.writeByte(h); int lineCount = 2; try { do { for (int i = 0; i < h; i++) { lineCount++; String line = reader.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of file at line " + lineCount); } for (int j = 0; j < w; j++) { char c = line.charAt(j); System.out.print(c); output.writeByte(c); } System.out.println(""); } lineCount++; output.writeShort(Short.parseShort(reader.readLine())); } while (reader.readLine() != null); } finally { reader.close(); output.close(); } } Code Sample 2: public void handle() { FileChannel srcChannel, destChannel; String destOutFile = databaseName + ".script." + System.currentTimeMillis(); String destOutFileCompressed = databaseName + ".script." + System.currentTimeMillis() + ".gz"; if (rotateDest != null) { (new File(rotateDest)).mkdirs(); if (destOutFile.indexOf("/") != -1) { destOutFile = rotateDest + "/" + destOutFile.substring(destOutFile.lastIndexOf("/") + 1); } if (destOutFileCompressed.indexOf("/") != -1) { destOutFileCompressed = rotateDest + "/" + destOutFileCompressed.substring(destOutFileCompressed.lastIndexOf("/") + 1); } } if (rotateCompress) { try { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(destOutFileCompressed)); FileInputStream in = new FileInputStream(databaseName + ".script"); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); buf = null; in = null; out = null; Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFileCompressed + "'"); } catch (Exception e) { Debug.debug("Unable to rotate database file '" + databaseName + ".script': " + e); } } else { try { srcChannel = new FileInputStream(databaseName + ".script").getChannel(); } catch (IOException e) { Debug.debug("Unable to read file '" + databaseName + ".script' for database rotation."); return; } try { destChannel = new FileOutputStream(destOutFile).getChannel(); } catch (IOException e) { Debug.debug("Unable to rotate file to '" + destOutFile + "': " + e.getMessage()); return; } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); srcChannel = null; destChannel = null; } catch (IOException e) { Debug.debug("Unable to copy data for file rotation: " + e.getMessage()); return; } Debug.debug("Rotated database file '" + databaseName + ".script' to '" + destOutFile + "'"); } if (rotateDest != null) { long comparisonTime = rotateDays * (60 * 60 * 24 * 1000); long currentTime = System.currentTimeMillis(); File fileList[] = (new File(rotateDest)).listFiles(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = new java.util.Date(currentTime); String archiveFile = format1.format(date).toString() + ".zip"; if (rotateArchive != null) { archiveFile = rotateArchive + "/" + archiveFile; (new File(rotateArchive)).mkdirs(); } Archive archive = new Archive(archiveFile); for (int i = 0; i < fileList.length; i++) { String currentFilename = fileList[i].getName(); long timeDifference = (currentTime - fileList[i].lastModified()); if ((rotateCompress && currentFilename.endsWith(".gz")) || (!rotateCompress && currentFilename.indexOf(".script.") != -1)) { if (rotateDest != null) { currentFilename = rotateDest + "/" + currentFilename; } if (timeDifference > comparisonTime) { archive.addFile(fileList[i].getName(), currentFilename); fileList[i].delete(); } } } archive = null; fileList = null; format1 = null; date = null; } }
00
Code Sample 1: public Document load(java.net.URL url) throws DOMTestLoadException { Document doc = null; try { java.io.InputStream stream = url.openStream(); Object tidyObj = tidyConstructor.newInstance(new Object[0]); doc = (Document) parseDOMMethod.invoke(tidyObj, new Object[] { stream, null }); } catch (InvocationTargetException ex) { throw new DOMTestLoadException(ex.getTargetException()); } catch (Exception ex) { throw new DOMTestLoadException(ex); } return doc; } Code Sample 2: public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } }
00
Code Sample 1: public void onClick(View v) { String uriAPI = "http://www.sina.com"; HttpGet httpRequest = new HttpGet(uriAPI); try { HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == 200) { String strResult = EntityUtils.toString(httpResponse.getEntity()); strResult = eregi_replace("(\r\n|\r|\n|\n\r)", "", strResult); mTextView1.setText(strResult); } else { mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString()); } } catch (ClientProtocolException e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } catch (IOException e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } catch (Exception e) { mTextView1.setText(e.getMessage().toString()); e.printStackTrace(); } } Code Sample 2: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
00
Code Sample 1: public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); sql = "DELETE FROM usuario WHERE cod_usuario =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
00
Code Sample 1: public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException { HttpAsyncClient httpclient = new DefaultHttpAsyncClient(); httpclient.start(); if (dataSource != null && dataSource.size() > 0) { final CountDownLatch latch = new CountDownLatch(dataSource.size()); for (int i = 0; i < dataSource.size(); i++) { final HttpGet request = new HttpGet(dataSource.get(i)); httpclient.execute(request, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine()); try { HttpEntity he = response.getEntity(); try { String resp = EntityUtils.toString(he, "gb2312"); if (resp != null && resp.length() > 0) { SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp); sohuStockBeanList.add(shstBean); } count++; } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } latch.countDown(); } catch (RuntimeException re) { latch.countDown(); } } public void failed(final Exception ex) { latch.countDown(); } public void cancelled() { latch.countDown(); } }); } latch.await(); System.out.println("done"); } if (httpclient != null) { httpclient.shutdown(); } System.out.println(sohuStockBeanList.size()); } Code Sample 2: public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
00
Code Sample 1: public final void loadAllData(final String ticker, final File output, final CSVFormat outputFormat, final Date from, final Date to) { try { final URL url = buildURL(ticker, from, to); final InputStream is = url.openStream(); final ReadCSV csv = new ReadCSV(is, true, CSVFormat.ENGLISH); final PrintWriter tw = new PrintWriter(new FileWriter(output)); tw.println("date,time,open price,high price,low price," + "close price,volume,adjusted price"); while (csv.next() && !shouldStop()) { final Date date = csv.getDate("date"); final double adjClose = csv.getDouble("adj close"); final double open = csv.getDouble("open"); final double close = csv.getDouble("close"); final double high = csv.getDouble("high"); final double low = csv.getDouble("low"); final double volume = csv.getDouble("volume"); final NumberFormat df = NumberFormat.getInstance(); df.setGroupingUsed(false); final StringBuilder line = new StringBuilder(); line.append(NumericDateUtil.date2Long(date)); line.append(outputFormat.getSeparator()); line.append(NumericDateUtil.time2Int(date)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(open, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(high, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(low, this.precision)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(close, this.precision)); line.append(outputFormat.getSeparator()); line.append(df.format(volume)); line.append(outputFormat.getSeparator()); line.append(outputFormat.format(adjClose, this.precision)); tw.println(line.toString()); } tw.close(); } catch (final IOException ex) { throw new LoaderError(ex); } } Code Sample 2: public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
00
Code Sample 1: @Override public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException { String key = logFileNameExtractor.getFileName(fileStatus); int wasWritten = 0; FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key); RollBackOutputStream outputStream = null; File file = null; try { file = getOutputFile(key); lastWrittenFile = file; outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true); outputStream.mark(); wasWritten = IOUtils.copy(input, outputStream); if (postWriteAction != null) { postWriteAction.run(wasWritten); } } catch (Throwable t) { LOG.error(t.toString(), t); if (outputStream != null && wasWritten > 0) { LOG.error("Rolling back file " + file.getAbsolutePath()); try { outputStream.rollback(); } catch (IOException e) { throwException(e); } catch (InterruptedException e) { throw e; } } throwException(t); } finally { try { fileOutputStreamPool.releaseFile(key); } catch (IOException e) { throwException(e); } } return wasWritten; } Code Sample 2: @Override public void convert() throws Exception { URL url = new URL("http://qsardb.jrc.it/qmrf/download.jsp?filetype=xml&id=" + Integer.parseInt(this.id)); InputStream is = url.openStream(); try { QMRF qmrf = QmrfUtil.loadQmrf(is); Qmrf2Qdb.convert(getQdb(), qmrf); } finally { is.close(); } }
00
Code Sample 1: protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo); if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } try { int ind = pathInfo.lastIndexOf("."); if (ind != -1 && ind < pathInfo.length()) { String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } } Code Sample 2: public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } Code Sample 2: private void saveMessage(String server, Message message, byte[] bytes) throws Exception { ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) getPortalDao().getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); long orgId = 0; String className = ""; long classId = 0; if (message.getBody() instanceof Entity) { Entity entity = (Entity) message.getBody(); orgId = entity.getOrgId(); className = entity.getClass().getName(); classId = entity.getId(); } ps = conn.prepareStatement("insert into light_replication_message (orgId,server,event,className,classId,message,createDate) values(?,?,?,?,?,?,?);"); ps.setLong(1, orgId); ps.setString(2, server); ps.setString(3, message.getEvent().toString()); ps.setString(4, className); ps.setLong(5, classId); ps.setBytes(6, bytes); ps.setTimestamp(7, new Timestamp(System.currentTimeMillis())); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { conn.rollback(); ps.close(); conn.close(); e.printStackTrace(); throw new Exception(e); } }
11
Code Sample 1: private void parseTemplate(File templateFile, Map dataMap) throws ContainerException { Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module); Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(templateFile)); } catch (FileNotFoundException e) { throw new ContainerException(e); } String targetDirectoryName = args.length > 1 ? args[1] : null; if (targetDirectoryName == null) { targetDirectoryName = target; } String targetDirectory = ofbizHome + targetDirectoryName + args[0]; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { throw new ContainerException("Unable to create target directory - " + targetDirectory); } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } Writer writer = null; try { writer = new FileWriter(targetDirectory + templateFile.getName()); } catch (IOException e) { throw new ContainerException(e); } try { FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer); } catch (Exception e) { throw new ContainerException(e); } try { writer.flush(); writer.close(); } catch (IOException e) { throw new ContainerException(e); } } Code Sample 2: public static void copyFile(File source, File destination) throws IOException { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(destination).getChannel(); long size = in.size(); MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buffer); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; } Code Sample 2: private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
00
Code Sample 1: public void testResponseTimeout() throws Exception { server.enqueue(new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4")); server.enqueue(new MockResponse().setBody("DEF")); server.play(); URLConnection urlConnection = server.getUrl("/").openConnection(); urlConnection.setReadTimeout(1000); InputStream in = urlConnection.getInputStream(); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); try { in.read(); fail(); } catch (SocketTimeoutException expected) { } URLConnection urlConnection2 = server.getUrl("/").openConnection(); InputStream in2 = urlConnection2.getInputStream(); assertEquals('D', in2.read()); assertEquals('E', in2.read()); assertEquals('F', in2.read()); assertEquals(-1, in2.read()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(0, server.takeRequest().getSequenceNumber()); } Code Sample 2: public void play(File file) { try { URL url = new URL("http://127.0.0.1:8081/play.html?type=4&file=" + file.getAbsolutePath() + "&name=toto"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private PrecomputedAnimatedModel loadPrecomputedModel_(URL url) { if (precompCache.containsKey(url.toExternalForm())) { return (precompCache.get(url.toExternalForm()).copy()); } TextureLoader.getInstance().getTexture(""); List<SharedGroup> frames = new ArrayList<SharedGroup>(); Map<String, Animation> animations = new Hashtable<String, Animation>(); if (url.toExternalForm().endsWith(".amo")) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String objFileName = reader.readLine(); objFileName = url.toExternalForm().substring(0, url.toExternalForm().lastIndexOf("/")) + "/" + objFileName; frames = loadOBJFrames(objFileName); String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); String animName = tokenizer.nextToken(); int from = Integer.valueOf(tokenizer.nextToken()); int to = Integer.valueOf(tokenizer.nextToken()); tokenizer.nextToken(); animations.put(animName, new Animation(animName, from, to)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { frames = loadOBJFrames(url.toExternalForm()); } PrecomputedAnimatedModel precompModel = new PrecomputedAnimatedModel(frames, animations); precompCache.put(url.toExternalForm(), precompModel); return (precompModel); } Code Sample 2: private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } }
00
Code Sample 1: private void _scanForMetaData(URL _url) throws java.io.IOException { if (DEBUG.Enabled) System.out.println(this + " _scanForMetaData: xml props " + mXMLpropertyList); if (DEBUG.Enabled) System.out.println("*** Opening connection to " + _url); markAccessAttempt(); Properties metaData = scrapeHTMLmetaData(_url.openConnection(), 2048); if (DEBUG.Enabled) System.out.println("*** Got meta-data " + metaData); markAccessSuccess(); String title = metaData.getProperty("title"); if (title != null && title.length() > 0) { setProperty("title", title); title = title.replace('\n', ' ').trim(); setTitle(title); } try { setByteSize(Integer.parseInt((String) getProperty("contentLength"))); } catch (Exception e) { } } Code Sample 2: public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
11
Code Sample 1: private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; } Code Sample 2: public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
00
Code Sample 1: public DataSetInfo(String request) throws AddeURLException { URLConnection urlc; BufferedReader reader; debug = debug || request.indexOf("debug=true") >= 0; try { URL url = new URL(request); urlc = url.openConnection(); reader = new BufferedReader(new InputStreamReader(urlc.getInputStream())); } catch (AddeURLException ae) { status = -1; throw new AddeURLException("No datasets found"); } catch (Exception e) { status = -1; throw new AddeURLException("Error opening connection: " + e); } int numBytes = ((AddeURLConnection) urlc).getInitialRecordSize(); if (debug) System.out.println("DataSetInfo: numBytes = " + numBytes); if (numBytes == 0) { status = -1; throw new AddeURLException("No datasets found"); } else { data = new char[numBytes]; try { int start = 0; while (start < numBytes) { int numRead = reader.read(data, start, (numBytes - start)); if (debug) System.out.println("bytes read = " + numRead); start += numRead; } } catch (IOException e) { status = -1; throw new AddeURLException("Error reading dataset info:" + e); } int numNames = data.length / 80; descriptorTable = new Hashtable(numNames); if (debug) System.out.println("Number of descriptors = " + numNames); for (int i = 0; i < numNames; i++) { String temp = new String(data, i * 80, 80); if (debug) System.out.println("Parsing: >" + temp + "<"); if (temp.trim().equals("")) continue; String descriptor = temp.substring(0, 12).trim(); if (debug) System.out.println("Descriptor = " + descriptor); String comment = descriptor; int pos = temp.indexOf('"'); if (debug) System.out.println("Found quote at " + pos); if (pos >= 23) { comment = temp.substring(pos + 1).trim(); if (comment.equals("")) comment = descriptor; } if (debug) System.out.println("Comment = " + comment); descriptorTable.put(comment, descriptor); } } } Code Sample 2: @Override public DaeScene loadScene(URL url) throws IOException, IncorrectFormatException, ParsingErrorException { NullArgumentException.check(url); boolean baseURLWasNull = setBaseURLFromModelURL(url); DaeScene scene = loadScene(url.openStream()); if (baseURLWasNull) { popBaseURL(); } return (scene); }
00
Code Sample 1: public static String getWebPage(URL urlObj) { try { String content = ""; InputStreamReader is = new InputStreamReader(urlObj.openStream()); BufferedReader reader = new BufferedReader(is); String line; while ((line = reader.readLine()) != null) { content += line; } return content; } catch (IOException e) { throw new Error("The page " + quote(urlObj.toString()) + "could not be retrieved." + "\nThis is could be caused by a number of things:" + "\n" + "\n - the computer hosting the web page you want is down, or has returned an error" + "\n - your computer does not have Internet access" + "\n - the heat death of the universe has occurred, taking down all web servers with it"); } } Code Sample 2: public boolean login(String strUrl, String loginName, String loginPwd) throws ApplicationException { String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; String urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; boolean isLogin = false; txtList.add(new HtmlFormText("loginName", loginName)); txtList.add(new HtmlFormText("loginPwd", loginPwd)); txtList.add(new HtmlFormText("navMode", "I")); txtList.add(new HtmlFormText("action", "login")); try { url = new URL(urlString); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.write((starter + boundary + returnChar).getBytes()); for (int i = 0; i < txtList.size(); i++) { HtmlFormText htmltext = (HtmlFormText) txtList.get(i); dos.write(htmltext.getTranslated()); if (i + 1 < txtList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } else if (fileList.size() > 0) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String cookieVal = conn.getHeaderField(HEADER_SETCOOKIE); if (cookieVal != null) { cookie = cookieVal.substring(0, cookieVal.indexOf(";")); } String tempstr; int line = 0; while (null != ((tempstr = br.readLine()))) { if (!tempstr.equals("")) { if ("window.location.replace(\"/Home.do\");".indexOf(returnMessage.append(formatLine(tempstr)).toString()) != -1) { isLogin = true; break; } line++; } } txtList.clear(); fileList.clear(); } catch (Exception e) { log.error(e, e); throw new ApplicationException(FormErrorConstant.DB_APP_BASE_URL_ERROR); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } return isLogin; }
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public List<String> query(String query) throws IOException { List<String> list = new LinkedList<String>(); query = URLEncoder.encode(query, "UTF-8"); String queryurl = baseurl + "?type=tuples&lang=itql&format=csv&query=" + query; URL url = new URL(queryurl); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); while (line != null) { list.add(line); line = reader.readLine(); } reader.close(); return list; } Code Sample 2: public URLConnection makeURLcon() { URI uri; URL url; try { uri = new URI(this.URLString); url = uri.toURL(); this.urlcon = (HttpURLConnection) url.openConnection(); } catch (final URISyntaxException e) { e.printStackTrace(); } catch (final MalformedURLException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } return this.urlcon; }
11
Code Sample 1: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } } Code Sample 2: private String buildShaHashOf(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(source.getBytes()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } }
11
Code Sample 1: private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } } Code Sample 2: 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(); } } }
00
Code Sample 1: private void showAboutBox() { String message = new String("Error: Resource Not Found."); java.net.URL url = ClassLoader.getSystemResource("docs/about.html"); if (url != null) { try { StringBuffer buf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while (reader.ready()) { buf.append(reader.readLine()); } message = buf.toString(); } catch (IOException ex) { message = new String("IO Error."); } } JOptionPane.showOptionDialog(this, message, "About jBudget", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null); } Code Sample 2: public static Coordinate getCoordenadas(String RCoURL) { Coordinate coord = new Coordinate(); String pURL; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniX = "<xcen>"; String iniY = "<ycen>"; String finX = "</xcen>"; String finY = "</ycen>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; if (RCoURL.contains("/") || RCoURL.contains("\\") || RCoURL.contains(".")) pURL = RCoURL; else { if (RCoURL.length() > 14) pURL = baseURL[1].replace("<RC>", RCoURL.substring(0, 14)); else pURL = baseURL[1].replace("<RC>", RCoURL); } try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); coord.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); coord.setDescription(coord.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniX)) { ini = str.indexOf(iniX) + iniX.length(); fin = str.indexOf(finX); coord.setLongitude(Double.parseDouble(str.substring(ini, fin))); } if (str.contains(iniY)) { ini = str.indexOf(iniY) + iniY.length(); fin = str.indexOf(finY); coord.setLatitude(Double.parseDouble(str.substring(ini, fin))); } } } in.close(); } catch (Exception e) { System.err.println(e); } return coord; }
00
Code Sample 1: public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } Code Sample 2: protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } }
00
Code Sample 1: private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } } Code Sample 2: PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException { this.dir = dir; this.name = name; this.updates = dir.getUpdates(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IOUtils.copy(data, stream); updates.setNewData(getFullName(), stream.toByteArray()); stream.close(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
11
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 boolean ponerRivalxRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = " + dato + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
11
Code Sample 1: public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } } Code Sample 2: private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
00
Code Sample 1: private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } Code Sample 2: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/jar"); byte[] bufor = new byte[BUF_LEN]; ServletContext context = getServletContext(); URL url = context.getResource(FILE_NAME); InputStream in = url.openStream(); OutputStream out = response.getOutputStream(); while (in.read(bufor) != -1) out.write(bufor); in.close(); out.close(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { getCisUtils().debug("Resolving entity publicId=" + pPublicId + ", systemId=" + pSystemId); final String res; if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(pPublicId)) { res = "resources/web-app_2_3.dtd"; } else { return null; } URL url = getClass().getResource(res); if (url == null) { throw new SAXException("Failed to locate resource: " + res); } InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toExternalForm()); return isource; }
11
Code Sample 1: public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException { if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1"); if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength); if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'"); HashCash result = new HashCash(); MessageDigest md = MessageDigest.getInstance("SHA1"); result.myResource = resource; result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions); result.myDate = date; result.myVersion = version; String prefix; SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); switch(version) { case 0: prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); md.reset(); md.update(result.myToken.getBytes()); result.myValue = numberOfLeadingZeros(md.digest()); break; case 1: result.myValue = value; prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":"; result.myToken = generateCash(prefix, value, md); break; default: throw new IllegalArgumentException("Only supported versions are 0 and 1"); } return result; } Code Sample 2: static String hash(String text) { try { StringBuffer plugins = new StringBuffer(); for (PlayPlugin plugin : Play.plugins) { plugins.append(plugin.getClass().getName()); } MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update((Play.version + plugins.toString() + text).getBytes("utf-8")); byte[] digest = messageDigest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { int value = digest[i]; if (value < 0) { value += 256; } builder.append(Integer.toHexString(value)); } return builder.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
11
Code Sample 1: public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected HttpResponseImpl makeRequest(final HttpMethod m, final String requestId) { try { HttpResponseImpl ri = new HttpResponseImpl(); ri.setRequestMethod(m); ri.setResponseCode(_client.executeMethod(m)); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(m.getResponseBodyAsStream(), bos); ri.setResponseBody(bos.toByteArray()); notifyOfRequestSuccess(requestId, m, ri); return ri; } catch (HttpException ex) { notifyOfRequestFailure(requestId, m, ex); } catch (IOException ex) { notifyOfRequestFailure(requestId, m, ex); } return null; }
00
Code Sample 1: public static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; } Code Sample 2: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
11
Code Sample 1: private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } } Code Sample 2: public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); }
00
Code Sample 1: public static String encode(String plaintext) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not encrypt password for ISA db verification"); } } Code Sample 2: public static String upload(File tmpFile, URL url) throws IOException { StringBuffer reply = new StringBuffer(); URLConnection uc = url.openConnection(); ClientHttpRequest request = new ClientHttpRequest(uc); String file = "file"; String filename = tmpFile.getName(); InputStream fileinput = new FileInputStream(tmpFile); request.setParameter(file, filename, fileinput); InputStream serverInput = request.post(); BufferedReader in = new BufferedReader(new InputStreamReader(serverInput)); String line = in.readLine(); while (line != null) { reply.append(line + "\n"); line = in.readLine(); } in.close(); return reply.toString(); }
00
Code Sample 1: public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; } 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: protected void downloadJar(URL downloadURL, File jarFile, IProgressListener pl) { BufferedOutputStream out = null; InputStream in = null; URLConnection urlConnection = null; try { urlConnection = downloadURL.openConnection(); out = new BufferedOutputStream(new FileOutputStream(jarFile)); in = urlConnection.getInputStream(); int len = in.available(); Log.log("downloading jar with size: " + urlConnection.getContentLength()); if (len < 1) len = 1024; byte[] buffer = new byte[len]; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } catch (Exception e) { } finally { if (out != null) { try { out.close(); } catch (IOException ignore) { } } if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: public void SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } } Code Sample 2: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
00
Code Sample 1: public static InputStream sendReq(String url, String content, ConnectData data) { try { URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setUseCaches(false); setUA(con); con.setRequestProperty("Accept-Charset", "utf-8"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data.cookie != null) con.setRequestProperty("Cookie", data.cookie); HttpURLConnection httpurl = (HttpURLConnection) con; httpurl.setRequestMethod("POST"); Writer wr = new OutputStreamWriter(con.getOutputStream()); wr.write(content); wr.flush(); con.connect(); InputStream is = con.getInputStream(); is = new BufferedInputStream(is); wr.close(); parseCookie(con, data); return is; } catch (IOException ioe) { Log.except("failed to send request " + url, ioe); } return null; } Code Sample 2: private synchronized void resetUserDictionary() { if (this.fChecker == null) return; if (this.fUserDictionary != null) { this.fChecker.removeDictionary(this.fUserDictionary); this.fUserDictionary.unload(); this.fUserDictionary = null; } IPreferenceStore store = SpellActivator.getDefault().getPreferenceStore(); String filePath = store.getString(PreferenceConstants.SPELLING_USER_DICTIONARY); IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager(); try { filePath = variableManager.performStringSubstitution(filePath); } catch (CoreException e) { SpellActivator.log(e); return; } if (filePath.length() > 0) { try { File file = new File(filePath); if (!file.exists() && !file.createNewFile()) return; final URL url = new URL("file", null, filePath); InputStream stream = url.openStream(); if (stream != null) { try { this.fUserDictionary = new PersistentSpellDictionary(url); this.fChecker.addDictionary(this.fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } }
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 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: 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: @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
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: private void generateArchetype(final IProject project, final IDataModel model, final IProgressMonitor monitor, final boolean offline) throws CoreException, InterruptedException, IOException { if (getArchetypeArtifactId(model) != null) { final Properties properties = new Properties(); properties.put("archetypeArtifactId", getArchetypeArtifactId(model)); properties.put("archetypeGroupId", getArchetypeGroupId(model)); properties.put("archetypeVersion", getArchetypeVersion(model)); String artifact = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_ARTIFACT_ID); if (artifact == null || artifact.trim().length() == 0) { artifact = project.getName(); } properties.put("artifactId", artifact); String group = (String) model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_GROUP_ID); if (group == null || group.trim().length() == 0) { group = project.getName(); } properties.put("groupId", group); properties.put("version", model.getProperty(IMavenFacetInstallDataModelProperties.PROJECT_VERSION)); final StringBuffer sb = new StringBuffer(System.getProperty("user.home")).append(File.separator); sb.append(".m2").append(File.separator).append("repository"); final String local = sb.toString(); Logger.getLog().debug("Local Maven2 repository :: " + local); properties.put("localRepository", local); if (!offline) { final String sbRepos = getRepositories(); properties.put("remoteRepositories", sbRepos); } final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating project using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { String dfPom = getPomFile(group, artifact); ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (IOException e) { } } if (SiteManager.isHttpProxyEnable()) { addProxySettings(properties); } workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); String goalName = "archetype:create"; if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } goalName = updateGoal(goalName); workingCopy.setAttribute(ATTR_GOALS, goalName); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(monitor, workingCopy, project, timeout); monitor.setTaskName("Moving to workspace"); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), ArchetypePOMHelper.getProjectDirectory(project)); monitor.worked(1); performMavenInstall(monitor, project, offline); project.refreshLocal(2, monitor); } catch (final IOException ioe) { Logger.log(Logger.ERROR, "I/O exception. One probably solution is absence " + "of mvn2 archetypes or not the correct version, " + "in your local repository. Please, check existence " + "of this archetype."); Logger.getLog().error("I/O Exception arised creating mvn2 archetype", ioe); throw ioe; } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } } monitor.worked(1); }
11
Code Sample 1: private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } Code Sample 2: public String storeUploadedZip(byte[] zip, String name) { List filesToStore = new ArrayList(); int i = 0; ZipInputStream zipIs = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry zipEntry = zipIs.getNextEntry(); while (zipEntry != null) { if (zipEntry.isDirectory() == false) { i++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zipIs, baos); baos.close(); } zipIs.closeEntry(); zipEntry = zipIs.getNextEntry(); } }
11
Code Sample 1: public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } Code Sample 2: public void download(String contentUuid, File path) throws WebServiceClientException { try { URL url = new URL(getPath("/download/" + contentUuid)); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); OutputStream output = new FileOutputStream(path); IoUtils.copyBytes(inputStream, output); IoUtils.close(inputStream); IoUtils.close(output); } catch (IOException ioex) { throw new WebServiceClientException("Could not download or saving content to path [" + path.getAbsolutePath() + "]", ioex); } catch (Exception ex) { throw new WebServiceClientException("Could not download content from web service.", ex); } }
11
Code Sample 1: public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
11
Code Sample 1: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: @TestTargets({ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verifies that the ObjectInputStream constructor calls checkPermission on security manager.", method = "ObjectInputStream", args = { InputStream.class }) }) public void test_ObjectInputStream2() throws IOException { class TestSecurityManager extends SecurityManager { boolean called; Permission permission; void reset() { called = false; permission = null; } @Override public void checkPermission(Permission permission) { if (permission instanceof SerializablePermission) { called = true; this.permission = permission; } } } class TestObjectInputStream extends ObjectInputStream { TestObjectInputStream(InputStream s) throws StreamCorruptedException, IOException { super(s); } } class TestObjectInputStream_readFields extends ObjectInputStream { TestObjectInputStream_readFields(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public GetField readFields() throws IOException, ClassNotFoundException, NotActiveException { return super.readFields(); } } class TestObjectInputStream_readUnshared extends ObjectInputStream { TestObjectInputStream_readUnshared(InputStream s) throws StreamCorruptedException, IOException { super(s); } @Override public Object readUnshared() throws IOException, ClassNotFoundException { return super.readUnshared(); } } long id = new java.util.Date().getTime(); String filename = "SecurityPermissionsTest_" + id; File f = File.createTempFile(filename, null); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f)); oos.writeObject(new Node()); oos.flush(); oos.close(); f.deleteOnExit(); TestSecurityManager s = new TestSecurityManager(); System.setSecurityManager(s); s.reset(); new ObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must not call checkPermission on security manager on a class which neither overwrites methods readFields nor readUnshared", !s.called); s.reset(); new TestObjectInputStream_readFields(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readFields", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); s.reset(); new TestObjectInputStream_readUnshared(new FileInputStream(f)); assertTrue("ObjectInputStream(InputStream) ctor must call checkPermission on security manager on a class which overwrites method readUnshared", s.called); assertEquals("Name of SerializablePermission is not correct", "enableSubclassImplementation", s.permission.getName()); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } } Code Sample 2: private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
00
Code Sample 1: private void calculateCoverageAndSpecificity(String mainCat) throws IOException, JSONException { for (String cat : Rules.categoryTree.get(mainCat)) { for (String queryString : Rules.queries.get(cat)) { String urlEncodedQueryString = URLEncoder.encode(queryString, "UTF-8"); URL url = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + urlEncodedQueryString + "?appid=" + yahoo_ap_id + "&count=4&format=json&sites=" + site); URLConnection con = url.openConnection(); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); JSONObject jsonObject = json.getJSONObject("ysearchresponse"); String totalhits = jsonObject.getString("totalhits"); long totalhitsLong = Long.parseLong(totalhits); QueryInfo qinfo = new QueryInfo(queryString, totalhitsLong); queryInfoMap.put(queryString, qinfo); cov.put(cat, cov.get(cat) + totalhitsLong); if (totalhitsLong == 0) { continue; } ja = jsonObject.getJSONArray("resultset_web"); for (int j = 0; j < ja.length(); j++) { JSONObject k = ja.getJSONObject(j); String dispurl = filterBold(k.getString("url")); qinfo.addUrl(dispurl); } } } calculateSpecificity(mainCat); } Code Sample 2: public void excluirCliente(String cpf) { PreparedStatement pstmt = null; String sql = "delete from cliente where cpf = ?"; try { pstmt = connection.prepareStatement(sql); pstmt.setString(1, cpf); pstmt.executeUpdate(); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (SQLException ex1) { throw new RuntimeException("Erro ao exclir ciente.", ex1); } throw new RuntimeException("Erro ao excluir cliente.", ex); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException ex) { throw new RuntimeException("Ocorreu um erro no banco de dados.", ex); } } }
11
Code Sample 1: public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; } 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(); }
00
Code Sample 1: public void testJTLM_publish911() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); AlignmentType alignment = AlignmentType.compress; Transmogrifier encoder = new Transmogrifier(); EXIDecoder decoder = new EXIDecoder(); Scanner scanner; InputSource inputSource; encoder.setAlignmentType(alignment); decoder.setAlignmentType(alignment); encoder.setEXISchema(grammarCache); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/JTLM/publish911.xml"); inputSource = new InputSource(url.toString()); inputSource.setByteStream(url.openStream()); byte[] bts; int n_events, n_texts; encoder.encode(inputSource); bts = baos.toByteArray(); decoder.setEXISchema(grammarCache); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (exiEvent.getCharacters().length() == 0) { --n_events; continue; } if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(JTLMTest.publish911_centennials[n], exiEvent.getCharacters().makeString()); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(96576, n_events); } 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: public static String getHash(String key) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); return new BigInteger(digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { return key; } } Code Sample 2: public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } }
00
Code Sample 1: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); FSDataInputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); System.out.println("\n"); in.seek(0); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public static void copyFiles(String strPath, String dstPath) throws IOException { File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { if (list[i].lastIndexOf(SVN) != -1) { if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } else { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFiles(src1, dest1); } } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } } Code Sample 2: private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
11
Code Sample 1: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } } 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 Object deployNewService(String scNodeRmiName, String userName, String password, String name, String jarName, String serviceClass, String serviceInterface, Logger log) throws RemoteException, MalformedURLException, StartServiceException, NotBoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SessionException { try { SCNodeInterface node = (SCNodeInterface) Naming.lookup(scNodeRmiName); String session = node.login(userName, password); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(new FileInputStream(jarName), baos); ServiceAdapterIfc adapter = node.deploy(session, name, baos.toByteArray(), jarName, serviceClass, serviceInterface); if (adapter != null) { return new ExternalDomain(node, adapter, adapter.getUri(), log).getProxy(Thread.currentThread().getContextClassLoader()); } } catch (Exception e) { log.warn("Could not send deploy command: " + e.getMessage(), e); } return null; } Code Sample 2: private void handleInclude(Element elem) throws Exception { String source = getTextContent(elem); URL url = null; try { url = new URL(source); } catch (MalformedURLException e) { url = XmlConfig.class.getResource(source); } Document doc = db.parse(url.openStream()); handleDocument(doc); }
00
Code Sample 1: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = (new BASE64Encoder()).encode(raw); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; } Code Sample 2: public BasicTraceImpl() { out = System.out; traceEnable = new HashMap(); URL url = Hive.getURL("trace.cfg"); if (url != null) try { InputStream input = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String line; for (line = line = in.readLine(); line != null; line = in.readLine()) { int i = line.indexOf("="); if (i > 0) { String name = line.substring(0, i).trim(); String value = line.substring(i + 1).trim(); traceEnable.put(name, Boolean.valueOf(value).booleanValue() ? ((Object) (Boolean.TRUE)) : ((Object) (Boolean.FALSE))); } } input.close(); } catch (IOException io) { System.out.println(io); } TRACE = getEnable(THIS); }
00
Code Sample 1: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } Code Sample 2: public static String get_content(String _url) throws Exception { URL url = new URL(_url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; String content = new String(); while ((inputLine = in.readLine()) != null) { content += inputLine; } in.close(); return content; }
00
Code Sample 1: public CertificateID(String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull()); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert); digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new DEROctetString(digest.digest()); PublicKey issuerKey = issuerCert.getPublicKey(); ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest()); DERInteger serialNumber = new DERInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } } Code Sample 2: public void run() { btnReintentar.setEnabled(false); try { lblEstado.setText("Conectando con servidor..."); escribir("\nConectando con servidor..."); URL url = new URL("http://apeiron.sourceforge.net/version.php"); lblEstado.setText("Obteniendo informaci�n de versi�n..."); escribir("Ok\n"); escribir("Obteniendo informaci�n sobre �ltima versi�n..."); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String linea = br.readLine(); escribir("Ok\n"); if (linea != null) { escribir("Versi�n mas reciente: " + linea + "\n"); if (Principal.version < Double.parseDouble(linea)) { lblEstado.setText("Hay una nueva versi�n: Apeiron " + linea); escribir("Puede obtener la actualizaci�n de: http://apeiron.sourceforge.net\n"); btnActualizar.setEnabled(true); setVisible(true); } else { lblEstado.setText("Usted tiene la �ltima versi�n"); } } br.close(); } catch (MalformedURLException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } catch (IOException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } btnReintentar.setEnabled(true); }
11
Code Sample 1: @SuppressWarnings("unchecked") public static void zip(String input, OutputStream out) { File file = new File(input); ZipOutputStream zip = null; FileInputStream in = null; try { if (file.exists()) { Collection<File> items = new ArrayList(); if (file.isDirectory()) { items = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); zip = new ZipOutputStream(out); zip.putNextEntry(new ZipEntry(file.getName() + "/")); Iterator iter = items.iterator(); while (iter.hasNext()) { File item = (File) iter.next(); in = new FileInputStream(item); zip.putNextEntry(new ZipEntry(file.getName() + "/" + item.getName())); IOUtils.copy(in, zip); IOUtils.closeQuietly(in); zip.closeEntry(); } IOUtils.closeQuietly(zip); } } else { log.info("-->>���ļ���û���ļ�"); } } catch (Exception e) { log.error("����ѹ��" + input + "�������", e); throw new RuntimeException("����ѹ��" + input + "�������", e); } finally { try { if (null != zip) { zip.close(); zip = null; } if (null != in) { in.close(); in = null; } } catch (Exception e) { log.error("�ر��ļ�������"); } } } 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) { logger.error(Logger.SECURITY_FAILURE, "Problem decoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: private static boolean DownloadDB() { URL url = null; BufferedWriter inWriter = null; String line; try { url = new URL(URL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); inWriter = new BufferedWriter(new FileWriter(InFileName)); while ((line = reader.readLine()) != null) { inWriter.write(line); inWriter.newLine(); } inWriter.close(); } catch (Exception e) { try { inWriter.close(); } catch (IOException ignored) { } e.printStackTrace(); return false; } return true; }
00
Code Sample 1: private static List retrieveQuotes(Report report, Symbol symbol, String prefix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, prefix, startDate, endDate); EODQuoteFilter filter = new GoogleEODQuoteFilter(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("GOOGLE_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 void connect() throws SocketException, IOException { Log.i(TAG, "Test attempt login to " + ftpHostname + " as " + ftpUsername); ftpClient = new FTPClient(); ftpClient.connect(this.ftpHostname, this.ftpPort); ftpClient.login(ftpUsername, ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { String error = "Login failure (" + reply + ") : " + ftpClient.getReplyString(); Log.e(TAG, error); throw new IOException(error); } }
11
Code Sample 1: private void loadMascotLibrary() { if (isMascotLibraryLoaded) return; try { boolean isLinux = false; boolean isAMD64 = false; String mascotLibraryFile; if (Configurator.getOSName().toLowerCase().contains("linux")) { isLinux = true; } if (Configurator.getOSArch().toLowerCase().contains("amd64")) { isAMD64 = true; } if (isLinux) { if (isAMD64) { mascotLibraryFile = "libmsparserj-64.so"; } else { mascotLibraryFile = "libmsparserj-32.so"; } } else { if (isAMD64) { mascotLibraryFile = "msparserj-64.dll"; } else { mascotLibraryFile = "msparserj-32.dll"; } } logger.warn("Using: " + mascotLibraryFile); URL mascot_lib = MascotDAO.class.getClassLoader().getResource(mascotLibraryFile); if (mascot_lib != null) { logger.debug("Mascot library URL: " + mascot_lib); tmpMascotLibraryFile = File.createTempFile("libmascot.so.", ".tmp", new File(System.getProperty("java.io.tmpdir"))); InputStream in = mascot_lib.openStream(); OutputStream out = new FileOutputStream(tmpMascotLibraryFile); IOUtils.copy(in, out); in.close(); out.close(); System.load(tmpMascotLibraryFile.getAbsolutePath()); isMascotLibraryLoaded = true; } else { throw new ConverterException("Could not load Mascot Library for system: " + Configurator.getOSName() + Configurator.getOSArch()); } } catch (IOException e) { throw new ConverterException("Error loading Mascot library: " + e.getMessage(), e); } } Code Sample 2: private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void 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!"); }