label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static String getStringHash(String fileName) { try { MessageDigest digest = MessageDigest.getInstance("md5"); digest.reset(); digest.update(fileName.getBytes()); byte messageDigest[] = digest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) builder.append(Integer.toHexString(0xFF & messageDigest[i])); String result = builder.toString(); return result; } catch (NoSuchAlgorithmException ex) { return fileName; } } Code Sample 2: @Override public void testAction(ITestThread testThread) throws Throwable { try { final InputStream urlIn = new URL("http://jdistunit.sourceforge.net").openStream(); final int availableBytes = urlIn.available(); if (0 == availableBytes) { throw new IllegalStateException("Zero bytes on target host."); } in = new BufferedReader(new InputStreamReader(urlIn)); String line; while (null != (line = in.readLine())) { page.append(line); page.append('\n'); if (0 != lineDelay) { OS.sleep(lineDelay); } if (null != testThread && testThread.isActionStopped()) { break; } } } finally { if (null != in) { in.close(); in = null; } } }
00
Code Sample 1: public String get(String question) { try { System.out.println(url + question); URL urlonlineserver = new URL(url + question); BufferedReader in = new BufferedReader(new InputStreamReader(urlonlineserver.openStream())); String inputLine; String returnstring = ""; while ((inputLine = in.readLine()) != null) returnstring += inputLine; in.close(); return returnstring; } catch (IOException e) { return ""; } } Code Sample 2: public boolean pollLocation(int device) { if (device < numDevices) { try { HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); JSONObject object = (JSONObject) JSONValue.parse(reader); JSONArray array = ((JSONArray) object.get("content")); object = (JSONObject) array.get(device); IPhoneLocation iPhoneLocation = getLocation(object); if (iPhoneLocation != null) { iPhoneRouteList.get(device).addLocation(iPhoneLocation); } } catch (ClientProtocolException ex) { logger.log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return false; } } else { logger.log(Level.WARNING, "Device {0} is out of range ({1} max)", new Object[] { (device + 1), numDevices }); return false; } return true; }
00
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkdirs(dst)) { return false; } File contents[] = src.listFiles(); for (int i = 0; i < contents.length; i++) { copy(contents[i], dstFS, new Path(dst, contents[i].getName()), deleteSource, conf); } } else if (src.isFile()) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = dstFS.create(dst); IOUtils.copyBytes(in, out, conf); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return FileUtil.fullyDelete(src); } else { return true; } }
00
Code Sample 1: protected Properties loadFile(String fileName) { Properties prop = new Properties(); try { String packageName = getClass().getName(); packageName = packageName.substring(0, packageName.lastIndexOf(".")); String src = "src"; if (mavenBuild) { src = src + File.separator + "test" + File.separator + "resources"; } packageName = src + File.separator + packageName.replace('.', File.separatorChar); packageName += File.separator; packageName += fileName; URL url0 = new File(packageName).toURI().toURL(); final InputStream input = url0.openStream(); prop.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return prop; } Code Sample 2: public static void main(String[] args) { try { int encodeFlag = 0; if (args[0].equals("-e")) { encodeFlag = Base64.ENCODE; } else if (args[0].equals("-d")) { encodeFlag = Base64.DECODE; } String infile = args[1]; String outfile = args[2]; File fin = new File(infile); FileInputStream fis = new FileInputStream(fin); BufferedInputStream bis = new BufferedInputStream(fis); Base64.InputStream b64in = new Base64.InputStream(bis, encodeFlag | Base64.DO_BREAK_LINES); File fout = new File(outfile); FileOutputStream fos = new FileOutputStream(fout); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buff = new byte[1024]; int read = -1; while ((read = b64in.read(buff)) >= 0) { bos.write(buff, 0, read); } bos.close(); b64in.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private static String getDigestPassword(String streamId, String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw (RuntimeException) new IllegalStateException().initCause(e); } md.update((streamId + password).getBytes()); byte[] uid = md.digest(); int length = uid.length; StringBuilder digPass = new StringBuilder(); for (int i = 0; i < length; ) { int k = uid[i++]; int iint = k & 0xff; String buf = Integer.toHexString(iint); if (buf.length() == 1) { buf = "0" + buf; } digPass.append(buf); } return digPass.toString(); } Code Sample 2: private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
00
Code Sample 1: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } Code Sample 2: @Override public boolean register(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); try { if (this.getDbServ().queryFeelerUser(username) != null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); this.getDbServ().addFeelerUser(username, passwordMd5); return this.identification(username, password); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static final boolean zipExtract(String zipfile, String name, String dest) { boolean f = false; try { InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().equals(name)) { FileOutputStream out = new FileOutputStream(dest); byte b[] = new byte[TEMP_FILE_BUFFER_SIZE]; int len = 0; while ((len = zin.read(b)) != -1) out.write(b, 0, len); out.close(); f = true; break; } } zin.close(); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } return (f); }
00
Code Sample 1: public static String getTextFromUrl(final String url) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(HtmlUtil.quoteHtml(line)).append("\r"); } return result.toString(); } catch (final IOException exception) { return exception.getMessage(); } finally { InputOutputUtil.close(bufferedReader); InputOutputUtil.close(inputStreamReader); } } Code Sample 2: private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
00
Code Sample 1: public void unzip(final File outDir) throws IOException { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if (entry != null) { File file = this.createFile(outDir, entry.getName()); if (!entry.isDirectory()) { FileOutputStream output = new FileOutputStream(file); IOUtils.copy(input, output); output.close(); } } } input.close(); } Code Sample 2: public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,nextval('pilot_id_seq'))"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
11
Code Sample 1: @Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } } Code Sample 2: public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: public static String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } md.update(plaintext.getBytes(Charset.defaultCharset())); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static final String Digest(String credentials, String algorithm, String encoding) { try { MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); if (encoding == null) { md.update(credentials.getBytes()); } else { md.update(credentials.getBytes(encoding)); } return (HexUtils.convert(md.digest())); } catch (Exception ex) { log.error(ex); return credentials; } }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); }
00
Code Sample 1: public static String getTitleFromURLFast(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_title_line = null; String x_lc_line = null; int x_title = -1; int x_end = -1; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_title = x_lc_line.indexOf("<title"); if (x_title != -1) { x_end = x_lc_line.indexOf("</title>"); x_title_line = x_line.substring((x_title + 7), (x_end == -1 ? x_line.length() : x_end)); break; } } return x_title_line; } Code Sample 2: public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); }
11
Code Sample 1: private String md5(String s) { StringBuffer hexString = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hashPart = Integer.toHexString(0xFF & messageDigest[i]); if (hashPart.length() == 1) { hashPart = "0" + hashPart; } hexString.append(hashPart); } } catch (NoSuchAlgorithmException e) { Log.e(this.getClass().getSimpleName(), "MD5 algorithm not present"); } return hexString != null ? hexString.toString() : null; } Code Sample 2: public static String calculate(String message, String algorithm, boolean base64) throws IllegalArgumentException { MessageDigest md = null; try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { String error = "'" + algorithm + "' is not a supported MessageDigest algorithm."; LOG.error(error, e); throw new IllegalArgumentException(error); } md.update(message.getBytes()); byte[] digestData = md.digest(); String digest = null; if (base64) { Base64Encoder enc = new Base64Encoder(); enc.translate(digestData); digest = new String(enc.getCharArray()); } else { digest = byteArrayToHex(digestData); } return digest; }
00
Code Sample 1: public static String encripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "encripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "encripta(String)"); } } Code Sample 2: public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { System.out.println("newBundle"); if (baseName == null || locale == null || format == null || loader == null) throw new NullPointerException(); ResourceBundle bundle = null; if (format.equals("xml")) { String bundleName = toBundleName(baseName, locale); String resourceName = toResourceName(bundleName, format); System.out.println(resourceName); InputStream stream = null; if (reload) { URL url = loader.getResource(resourceName); System.out.println(url.toExternalForm()); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); stream = connection.getInputStream(); } } } else { stream = loader.getResourceAsStream(resourceName); } if (stream != null) { InputSource source = new InputSource(stream); try { bundle = new XMLResourceBundle(source); } catch (SAXException saxe) { throw new IOException(saxe); } } } return bundle; }
00
Code Sample 1: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: public static Map putFile(DispatchContext dctx, Map context) { Debug.logInfo("[putFile] starting...", module); InputStream localFile = null; try { localFile = new FileInputStream((String) context.get("localFilename")); } catch (IOException ioe) { Debug.logError(ioe, "[putFile] Problem opening local file", module); return ServiceUtil.returnError("ERROR: Could not open local file"); } List errorList = new ArrayList(); FTPClient ftp = new FTPClient(); try { Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module); ftp.connect((String) context.get("hostname")); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { Debug.logInfo("[putFile] Server refused connection", module); errorList.add("connection refused"); } else { String username = (String) context.get("username"); String password = (String) context.get("password"); Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module); if (!ftp.login(username, password)) { Debug.logInfo("[putFile] login failed", module); errorList.add("Login failed (" + username + ", " + password + ")"); } else { Boolean binaryTransfer = (Boolean) context.get("binaryTransfer"); boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue(); if (binary) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } Boolean passiveMode = (Boolean) context.get("passiveMode"); boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue(); if (passive) { ftp.enterLocalPassiveMode(); } Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module); if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) { Debug.logInfo("[putFile] store was unsuccessful", module); errorList.add("File not sent succesfully: " + ftp.getReplyString()); } else { Debug.logInfo("[putFile] store was successful", module); List siteCommands = (List) context.get("siteCommands"); if (siteCommands != null) { Iterator ci = siteCommands.iterator(); while (ci.hasNext()) { String command = (String) ci.next(); Debug.logInfo("[putFile] sending SITE command: " + command, module); if (!ftp.sendSiteCommand(command)) { errorList.add("SITE command (" + command + ") failed: " + ftp.getReplyString()); } } } } } ftp.logout(); } } catch (IOException ioe) { Debug.log(ioe, "[putFile] caught exception: " + ioe.getMessage(), module); errorList.add("Problem with FTP transfer: " + ioe.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException dce) { Debug.logWarning(dce, "[putFile] Problem with FTP disconnect", module); } } } try { localFile.close(); } catch (IOException ce) { Debug.logWarning(ce, "[putFile] Problem closing local file", module); } if (errorList.size() > 0) { Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module); return ServiceUtil.returnError(errorList); } Debug.logInfo("[putFile] finished successfully", module); return ServiceUtil.returnSuccess(); }
00
Code Sample 1: @Override public void onClick(View v) { Log.d(Config.SS_TAG, "Sending POST request to server..."); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { JSONObject callJson = new JSONObject(); callJson.put("method", "ping"); callJson.put("void", "null"); callsJson.put(0, callJson); requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); JSONObject result = resultsJson.getJSONObject(0); String returnValue = result.getJSONObject("data").getString("return"); Log.d(Config.SS_TAG, "Response message: " + returnValue); } else { Log.e(Config.SS_TAG, "Unsuccessful ping..."); } } catch (Exception e) { Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet"); e.printStackTrace(); } } Code Sample 2: public String transmit(String input, String filePath) throws Exception { if (cookie == null || "".equals(urlString)) { return null; } String txt = ""; StringBuffer returnMessage = new StringBuffer(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; try { url = new URL(urlString); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); conn.setUseCaches(false); conn.setRequestProperty(HEADER_COOKIE, cookie); 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()); } } for (int i = 0; i < fileList.size(); i++) { HtmlFormFile htmlfile = (HtmlFormFile) fileList.get(i); dos.write(htmlfile.getTranslated()); if (i + 1 < fileList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); txt = transactFormStr(br); if (!"".equals(filePath) && !"null".equals(filePath)) { RandomAccessFile raf = new RandomAccessFile(filePath, "rw"); raf.seek(raf.length()); raf.writeBytes(txt + "\n"); raf.close(); } txtList.clear(); fileList.clear(); } catch (Exception e) { log.error(e, e); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } return txt; }
00
Code Sample 1: public void createControl(Composite parent) { top = new Composite(parent, SWT.NONE); top.setLayout(new GridLayout()); top.setLayoutData(new GridData(GridData.FILL_BOTH)); ComposedAdapterFactory factories = new ComposedAdapterFactory(); factories.addAdapterFactory(new EcoreItemProviderAdapterFactory()); factories.addAdapterFactory(new NotationAdapterFactory()); factories.addAdapterFactory(new ResourceItemProviderAdapterFactory()); modelViewer = new TreeViewer(top, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); modelViewer.getTree().setLayoutData(new GridData(GridData.FILL_BOTH)); modelViewer.setContentProvider(new AdapterFactoryContentProvider(factories) { public boolean hasChildren(Object object) { boolean result = super.hasChildren(object); if (object instanceof Diagram) { result = false; } if (object instanceof EPackage && result == false) { result = !DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()).isEmpty(); } return result; } public Object[] getChildren(Object object) { Object[] result = super.getChildren(object); if (object instanceof EPackage) { List<Diagram> list = DiagramUtil.getDiagrams((EPackage) object, editor.getDiagram().eResource()); if (list.size() != 0) { Object[] newResult = new Object[result.length + list.size()]; for (int i = 0; i < result.length; i++) { newResult[i] = result[i]; } for (int i = 0; i < list.size(); i++) { newResult[result.length + i] = list.get(i); } return newResult; } } return result; } }); modelViewer.setLabelProvider(new AdapterFactoryLabelProvider(factories) { public String getText(Object element) { String result = super.getText(element); if (element instanceof Diagram) { if (editor.getDiagram() == element) { result += " *"; } } return result; } public String getColumnText(Object object, int columnIndex) { String result = super.getText(object); if (object instanceof Diagram) { if (editor.getDiagram() == object) { result += " (active)"; } } return result; } }); modelViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { setDiagramSelection(modelViewer.getSelection()); } }); modelViewer.addDragSupport(DND.DROP_COPY, new Transfer[] { LocalTransfer.getInstance() }, new TreeDragListener()); modelViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); Object selectedObject = selection.getFirstElement(); if (selectedObject instanceof Diagram) { openDiagram((Diagram) selectedObject); } } }); createContextMenuFor(modelViewer); editor.getDiagramGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { selectionInDiagramChange(event); } }); this.getSite().setSelectionProvider(modelViewer); setInput(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: public TextureData newTextureData(URL url, int internalFormat, int pixelFormat, boolean mipmap, String fileSuffix) throws IOException { InputStream stream = new BufferedInputStream(url.openStream()); try { return newTextureData(stream, internalFormat, pixelFormat, mipmap, fileSuffix); } finally { stream.close(); } }
00
Code Sample 1: public synchronized void readConfiguration() throws IOException, SecurityException { String path; InputStream inputStream; path = System.getProperty("java.util.logging.config.file"); if ((path == null) || (path.length() == 0)) { String url = (System.getProperty("gnu.classpath.home.url") + "/logging.properties"); inputStream = new URL(url).openStream(); } else inputStream = new java.io.FileInputStream(path); try { readConfiguration(inputStream); } finally { inputStream.close(); } } Code Sample 2: protected void syncMessages(Message message) { if (message.getEvent() == Event.CONNECT || message.getEvent() == Event.SYNC_DONE) return; logger.info(String.format("remove stale replication messages: %s", message.toString())); String className = ""; long classId = 0; if (message.getBody() instanceof Entity) { Entity entity = (Entity) message.getBody(); className = entity.getClass().getName(); classId = entity.getId(); } ConnectionProvider cp = null; Connection conn = null; PreparedStatement ps = null; try { SessionFactoryImplementor impl = (SessionFactoryImplementor) portalDao.getSessionFactory(); cp = impl.getConnectionProvider(); conn = cp.getConnection(); conn.setAutoCommit(false); ps = conn.prepareStatement("delete from light_replication_message where event=? and className=? and classId=?"); ps.setString(1, message.getEvent().toString()); ps.setString(2, className); ps.setLong(3, classId); ps.executeUpdate(); conn.commit(); ps.close(); conn.close(); } catch (Exception e) { try { conn.rollback(); ps.close(); conn.close(); } catch (Exception se) { } } }
00
Code Sample 1: public static final String md5(final String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String h = Integer.toHexString(0xFF & messageDigest[i]); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { } return ""; } Code Sample 2: public static boolean copy(final File from, final File to) { if (from.isDirectory()) { to.mkdirs(); for (final String name : Arrays.asList(from.list())) { if (!copy(from, to, name)) { if (COPY_DEBUG) { System.out.println("Failed to copy " + name + " from " + from + " to " + to); } return false; } } } else { try { final FileInputStream is = new FileInputStream(from); final FileChannel ifc = is.getChannel(); final FileOutputStream os = makeFile(to); if (USE_NIO) { final FileChannel ofc = os.getChannel(); ofc.transferFrom(ifc, 0, from.length()); } else { pipe(is, os, false); } is.close(); os.close(); } catch (final IOException ex) { if (COPY_DEBUG) { System.out.println("Failed to copy " + from + " to " + to + ": " + ex); } return false; } } final long time = from.lastModified(); setLastModified(to, time); final long newtime = to.lastModified(); if (COPY_DEBUG) { if (newtime != time) { System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime)); to.setLastModified(time); final long morenewtime = to.lastModified(); return false; } else { System.out.println("Timestamp for " + to + " set successfully."); } } return time == newtime; }
00
Code Sample 1: private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } } Code Sample 2: private static void loadManifests() { Perl5Util util = new Perl5Util(); try { for (Enumeration e = classLoader.getResources("META-INF/MANIFEST.MF"); e.hasMoreElements(); ) { URL url = (URL) e.nextElement(); if (util.match("/" + pluginPath.replace('\\', '/') + "/", url.getFile())) { InputStream inputStream = url.openStream(); manifests.add(new Manifest(inputStream)); inputStream.close(); } } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public String report() { if (true) return "-"; StringBuffer parameter = new StringBuffer("?"); if (getRecord_ID() == 0) return "ID=0"; if (getRecord_ID() == 1) { parameter.append("ISSUE="); HashMap htOut = get_HashMap(); try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutput oOut = new ObjectOutputStream(bOut); oOut.writeObject(htOut); oOut.flush(); String hexString = Secure.convertToHexString(bOut.toByteArray()); parameter.append(hexString); } catch (Exception e) { log.severe(e.getLocalizedMessage()); return "New-" + e.getLocalizedMessage(); } } else { try { parameter.append("RECORDID=").append(getRecord_ID()); parameter.append("&DBADDRESS=").append(URLEncoder.encode(getDBAddress(), "UTF-8")); parameter.append("&COMMENTS=").append(URLEncoder.encode(getComments(), "UTF-8")); } catch (Exception e) { log.severe(e.getLocalizedMessage()); return "Update-" + e.getLocalizedMessage(); } } InputStreamReader in = null; String target = "http://dev1/wstore/issueReportServlet"; try { StringBuffer urlString = new StringBuffer(target).append(parameter); URL url = new URL(urlString.toString()); URLConnection uc = url.openConnection(); in = new InputStreamReader(uc.getInputStream()); } catch (Exception e) { String msg = "Cannot connect to http://" + target; if (e instanceof FileNotFoundException || e instanceof ConnectException) msg += "\nServer temporarily down - Please try again later"; else { msg += "\nCheck connection - " + e.getLocalizedMessage(); log.log(Level.FINE, msg); } return msg; } return readResponse(in); } Code Sample 2: public SWORDEntry ingestDepost(final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException { try { ZipFileAccess tZipFile = new ZipFileAccess(super.getTempDir()); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); _datastreamList.add(tDatastream); _datastreamList.addAll(tZipFile.getFiles(tZipTempFileName)); int i = 0; boolean found = false; for (i = 0; i < _datastreamList.size(); i++) { if (_datastreamList.get(i).getId().equalsIgnoreCase("mets")) { found = true; break; } } if (found) { SAXBuilder tBuilder = new SAXBuilder(); _mets = new METSObject(tBuilder.build(((LocalDatastream) _datastreamList.get(i)).getPath())); LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove(i); new File(tLocalMETSDS.getPath()).delete(); _datastreamList.add(_mets.getMETSDs()); _datastreamList.addAll(_mets.getMetadataDatastreams()); } else { throw new SWORDException("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml"); } SWORDEntry tEntry = super.ingestDepost(pDeposit, pServiceDocument); tZipFile.removeLocalFiles(); return tEntry; } catch (IOException tIOExcpt) { String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString(); LOG.error(tMessage); tIOExcpt.printStackTrace(); throw new SWORDException(tMessage, tIOExcpt); } catch (JDOMException tJDOMExcpt) { String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString(); LOG.error(tMessage); tJDOMExcpt.printStackTrace(); throw new SWORDException(tMessage, tJDOMExcpt); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: 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(); } } Code Sample 2: public RobotList<Percentage> sort_incr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
00
Code Sample 1: @Override protected svm_model loadModel(InputStream inputStream) throws IOException { File tmpFile = File.createTempFile("tmp", ".mdl"); FileOutputStream output = new FileOutputStream(tmpFile); try { IOUtils.copy(inputStream, output); return libsvm.svm.svm_load_model(tmpFile.getPath()); } finally { output.close(); tmpFile.delete(); } } Code Sample 2: private String getShaderIncludeSource(String path) throws Exception { URL url = this.getClass().getResource(path); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); boolean run = true; String str; String ret = new String(); while (run) { str = in.readLine(); if (str != null) ret += str + "\n"; else run = false; } in.close(); return ret; }
00
Code Sample 1: protected Document SendRequest(Document request) throws WsmanException { HttpURLConnection conn = null; Document response = null; stampRequest(request); boolean printDebug = System.getProperty("intel.management.wsman.debug", "false").equals("true"); int retry = 2; while (retry > 0) { try { if (conn != null) { conn.disconnect(); } URL url = new URL((String) properties.get("Address")); Proxy proxy = (Proxy) properties.get("HttpProxy"); if (proxy != null) conn = (HttpURLConnection) url.openConnection(proxy); else conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { HttpsURLConnection sslConn = (HttpsURLConnection) conn; SSLSocketFactory factory = (SSLSocketFactory) properties.get("SSLSocketFactory"); X509TrustManager tm = (X509TrustManager) properties.get("X509TrustManager"); HostnameVerifier verifier = (HostnameVerifier) properties.get("HostnameVerifier"); X509KeyManager km = (X509KeyManager) properties.get("X509KeyManager"); if (factory == null && (km != null || tm != null)) { X509KeyManager[] keys = null; X509TrustManager[] trusts = null; SSLContext sc = SSLContext.getInstance("SSL"); if (km != null) { keys = new X509KeyManager[1]; keys[0] = km; } if (tm != null) { trusts = new X509TrustManager[1]; trusts[0] = tm; } sc.init(keys, trusts, null); factory = sc.getSocketFactory(); properties.put("SSLSocketFactory", factory); } if (factory != null) sslConn.setSSLSocketFactory(factory); if (verifier != null) sslConn.setHostnameVerifier(verifier); } Object auth = properties.get("AuthScheme"); if (auth != null && auth.equals("kerberos")) { Oid spnegoMecOid = new Oid("1.3.6.1.5.5.2"); GSSManager manager = org.ietf.jgss.GSSManager.getInstance(); String spnName = "HTTP/" + url.getHost(); int spnPort = url.getPort(); if (spnPort == 16992 || spnPort == 16993 || spnPort == 623 || spnPort == 624) { spnName = spnName + ":" + Integer.toString(spnPort); } GSSName gssName = manager.createName(spnName, null); GSSContext context = manager.createContext(gssName, spnegoMecOid, null, GSSCredential.DEFAULT_LIFETIME); context.requestCredDeleg(true); byte[] token = new byte[0]; token = context.initSecContext(token, 0, token.length); String tokenStr = WsmanUtils.getBase64String(token); conn.addRequestProperty("Authorization", "Negotiate " + tokenStr); } else if (auth != null && auth.equals("basic")) { java.net.Authenticator.requestPasswordAuthentication(url.getHost(), null, url.getPort(), url.getProtocol(), "", "basic"); String tokenStr = ""; conn.addRequestProperty("Authorization", "Basic " + tokenStr); } conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8"); conn.setDoOutput(true); if (printDebug) System.out.println(getXmlLoader().formatDocument(request)); getXmlLoader().saveDocument(request, conn.getOutputStream()); InputStream s = conn.getInputStream(); response = getXmlLoader().loadDocument(s); if (printDebug) { System.out.println(getXmlLoader().formatDocument(response)); } conn.getResponseCode(); retry = 0; conn.disconnect(); conn = null; } catch (IOException ioException) { retry--; int max = conn.getHeaderFields().size(); for (int i = 0; i < max; i++) { String t = conn.getHeaderField(i); t.toString(); } conn.getRequestProperty("Authorization"); conn.getHeaderField("Authorization"); Object errObj = getResponse(conn); if (errObj != null && errObj instanceof Document) { response = (Document) errObj; retry = 0; throw new WsmanException(this, response); } else if (errObj != null) throw new WsmanException(ioException); if (retry == 0) throw new WsmanException(ioException); } catch (Exception exception) { retry = 0; throw new WsmanException(exception); } } return response; } Code Sample 2: public String calcMD5(String sequence) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(sequence.toString().toUpperCase().getBytes()); BigInteger md5hash = new BigInteger(1, md5.digest()); String sequence_md5 = md5hash.toString(16); while (sequence_md5.length() < 32) { sequence_md5 = "0" + sequence_md5; } return sequence_md5; }
00
Code Sample 1: Bundle install(String location, InputStream is) throws BundleException { synchronized (bundlesLock) { SecurityManager securityManager = System.getSecurityManager(); if (securityManager != null) { securityManager.checkPermission(new AdminPermission(new StringBuilder("(location=").append(location).append(")").toString(), org.osgi.framework.AdminPermission.EXTENSIONLIFECYCLE)); } long bundleId = getNextBundleId(); AbstractBundle bundle = null; try { if (is == null) { URL url = new URL(location); is = url.openStream(); } File temp = new File(getTempFolder(), Long.toString(System.currentTimeMillis())); OutputStream os; os = new FileOutputStream(temp); IOUtil.copy(is, os); os.close(); is.close(); Manifest manifest = ManifestUtil.getJarManifest(new FileInputStream(temp)); Dictionary headers = ManifestUtil.toDictionary(manifest); Version version = Version.parseVersion((String) headers.get(Constants.BUNDLE_VERSION)); File cache = createNewCache(bundleId, version); File manifestFile = new File(cache, BUNDLE_MANIFEST_FILE); os = new FileOutputStream(manifestFile); ManifestUtil.storeManifest(headers, os); os.close(); if (isBundleInstalled((String) headers.get(Constants.BUNDLE_SYMBOLICNAME))) { throw new BundleException(new StringBuilder("Bundle(location=").append(location).append(") already installed.").toString()); } ManifestEntry[] entries = ManifestEntry.parse(headers.get(Constants.FRAGMENT_HOST)); if (entries != null) { if (entries[0].hasAttribute("extension")) { String extension = entries[0].getAttributeValue("extension"); if (extension.equals("bootclasspath")) { String symbolicName = entries[0].getName(); if (!symbolicName.equals(framework.getSymbolicName()) && !symbolicName.equals(Constants.SYSTEM_BUNDLE_SYMBOLICNAME)) { throw new BundleException(new StringBuilder("Trying to install a fragment Bundle(location=").append(location).append(") with extension 'bootclasspath' but host is not System Bundle.").toString(), new UnsupportedOperationException()); } } } } String requiredEE = (String) headers.get(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT); if (requiredEE != null) { BundleContext context = framework.getBundleContext(); String ee = context.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT); if (!ee.contains(requiredEE)) { throw new BundleException(new StringBuilder("Bundle(location=").append(location).append(") requires an unsopperted execution environment (=").append(requiredEE).append(").").toString()); } } if (FrameworkUtil.isFragmentHost(headers)) { bundle = new FragmentBundle(framework); } else { bundle = new HostBundle(framework); } File bundlefile = new File(cache, Storage.BUNDLE_FILE); temp.renameTo(bundlefile); long lastModified = bundlefile.lastModified(); BundleInfo info = new BundleInfo(bundleId, location, lastModified, framework.getInitialBundleStartLevel()); info.setHeaders(headers); info.setCache(cache); storeBundleInfo(info); bundleInfosByBundle.put(bundle, info); BundleURLClassPath classPath = createBundleURLClassPath(bundle, version, bundlefile, cache, false); classPathsByBundle.put(bundle, new BundleURLClassPath[] { classPath }); synchronized (bundlesLock) { bundles = (Bundle[]) ArrayUtil.add(bundles, bundle); } return bundle; } catch (Exception e) { if (bundle != null) { File bundleFolder = getBundleFolder(bundleId); try { IOUtil.delete(bundleFolder); } catch (IOException e1) { } } e.printStackTrace(); throw new BundleException(e.getMessage(), e); } } } Code Sample 2: @Override public String baiDuHotNews() { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://news.baidu.com/z/wise_topic_processor/wise_hotwords_list.php?bd_page_type=1&tn=wapnews_hotwords_list&type=1&index=1&pfr=3-11-bdindex-top-3--"); String hostNews = ""; try { HttpResponse response = client.execute(httpGet); HttpEntity httpEntity = response.getEntity(); BufferedReader buffer = new BufferedReader(new InputStreamReader(httpEntity.getContent())); String line = ""; boolean todayNewsExist = false, firstNewExist = false; int newsCount = -1; while ((line = buffer.readLine()) != null) { if (todayNewsExist || line.contains("<div class=\"news_title\">")) todayNewsExist = true; else continue; if (firstNewExist || line.contains("<div class=\"list-item\">")) { firstNewExist = true; newsCount++; } else continue; if (todayNewsExist && firstNewExist && (newsCount == 1)) { Pattern hrefPattern = Pattern.compile("<a.*>(.+?)</a>.*"); Matcher matcher = hrefPattern.matcher(line); if (matcher.find()) { hostNews = matcher.group(1); break; } else newsCount--; } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return hostNews; }
11
Code Sample 1: public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: protected synchronized String encryptThis(String seed, String text) throws EncryptionException { String encryptedValue = null; String textToEncrypt = text; if (seed != null) { textToEncrypt = seed.toLowerCase() + text; } try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(textToEncrypt.getBytes("UTF-8")); encryptedValue = (new BASE64Encoder()).encode(md.digest()); } catch (Exception e) { throw new EncryptionException(e); } return encryptedValue; }
11
Code Sample 1: public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser(""); fc.setMultiSelectionEnabled(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int option = 0; boolean save = m_data != null; if (save) option = fc.showSaveDialog(this); else option = fc.showOpenDialog(this); if (option != JFileChooser.APPROVE_OPTION) return; File file = fc.getSelectedFile(); if (file == null) return; log.info(file.toString()); try { if (save) { FileOutputStream os = new FileOutputStream(file); byte[] buffer = (byte[]) m_data; os.write(buffer); os.flush(); os.close(); log.config("Save to " + file + " #" + buffer.length); } else { FileInputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int length = -1; while ((length = is.read(buffer)) != -1) os.write(buffer, 0, length); is.close(); byte[] data = os.toByteArray(); m_data = data; log.config("Load from " + file + " #" + data.length); os.close(); } } catch (Exception ex) { log.log(Level.WARNING, "Save=" + save, ex); } try { fireVetoableChange(m_columnName, null, m_data); } catch (PropertyVetoException pve) { } } Code Sample 2: public void backupFile(File fromFile, File toFile) { FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } catch (IOException e) { log.error(e.getMessage()); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public static void 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 static String hashPassword(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); byte result[] = md5.digest("InTeRlOgY".getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String s = Integer.toHexString(result[i]); int length = s.length(); if (length >= 2) { sb.append(s.substring(length - 2, length)); } else { sb.append("0"); sb.append(s); } } return "{md5}" + sb.toString(); } catch (NoSuchAlgorithmException e) { return password; } } Code Sample 2: public long getLastModified() { if (lastModified == 0) { if (connection == null) try { connection = url.openConnection(); } catch (IOException e) { } if (connection != null) lastModified = connection.getLastModified(); } return lastModified; }
11
Code Sample 1: private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } Code Sample 2: public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; }
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 String getProxy(String userName, String password) throws Exception { URL url = new URL(httpURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream()); outputToServlet.writeObject(userName); outputToServlet.writeObject(password); outputToServlet.flush(); outputToServlet.close(); ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream()); return inputFromServlet.readObject() + ""; }
00
Code Sample 1: public void setInternalReferences() { for (int i = 0; i < REFSPECS.length; i++) { REFSPECS[i].setTypeRefs(conn); } String sql, sql2; try { String[][] params2 = { { "PACKAGE", "name" }, { "CLASSTYPE", "qualifiedname" }, { "MEMBER", "qualifiedname" }, { "EXECMEMBER", "fullyqualifiedname" } }; for (int i = 0; i < params2.length; i++) { log.traceln("\tProcessing seetag " + params2[i][0] + " references.."); sql = "select r.sourcedoc_id, " + params2[i][0] + ".id, " + params2[i][0] + "." + params2[i][1] + " from REFERENCE r, " + params2[i][0] + " where r.refdoc_name = " + params2[i][0] + "." + params2[i][1] + " and r.refdoc_id is null"; Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); sql2 = "update REFERENCE set refdoc_id=? where sourcedoc_id=? and refdoc_name=?"; PreparedStatement pstmt = conn.prepareStatement(sql2); while (rset.next()) { pstmt.clearParameters(); pstmt.setInt(1, rset.getInt(2)); pstmt.setInt(2, rset.getInt(1)); pstmt.setString(3, rset.getString(3)); pstmt.executeUpdate(); } pstmt.close(); rset.close(); stmt.close(); conn.commit(); } } catch (SQLException ex) { log.error("Internal Reference Update Failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } } Code Sample 2: private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; }
11
Code Sample 1: public static long copy(File src, File dest) throws UtilException { FileChannel srcFc = null; FileChannel destFc = null; try { srcFc = new FileInputStream(src).getChannel(); destFc = new FileOutputStream(dest).getChannel(); long srcLength = srcFc.size(); srcFc.transferTo(0, srcLength, destFc); return srcLength; } catch (IOException e) { throw new UtilException(e); } finally { try { if (srcFc != null) srcFc.close(); srcFc = null; } catch (IOException e) { } try { if (destFc != null) destFc.close(); destFc = null; } catch (IOException e) { } } } Code Sample 2: @Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
11
Code Sample 1: FileCacheInputStreamFountain(FileCacheInputStreamFountainFactory factory, InputStream in) throws IOException { file = factory.createFile(); OutputStream out = new FileOutputStream(file); IOUtils.copy(in, out); in.close(); out.close(); } Code Sample 2: public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
11
Code Sample 1: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); 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(); } }
00
Code Sample 1: private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } } Code Sample 2: public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
00
Code Sample 1: @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getLocalPrincipal", args = { }) public final void test_getLocalPrincipal() { try { URL url = new URL("https://localhost:55555"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); try { connection.getLocalPrincipal(); fail("IllegalStateException wasn't thrown"); } catch (IllegalStateException ise) { } } catch (Exception e) { fail("Unexpected exception " + e + " for exception case"); } try { HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508"); assertNull(con.getLocalPrincipal()); con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509"); assertNotNull("Local principal is null", con.getLocalPrincipal()); } catch (Exception e) { fail("Unexpected exception " + e); } } Code Sample 2: public void createMessageBuffer(String messageBufferName, MessageBufferPolicy messageBufferPolicyObj) throws AppFabricException { String messageBufferPolicy = messageBufferPolicyObj.getMessageBufferPolicy(); if (messageBufferPolicy == null) { throw new AppFabricException("MessageBufferPolicy can not be null"); } MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String messageBufferUri = msgBufferUtilObj.getCreateMessageBufferUri(messageBufferName); if (messageBufferUri == null) { throw new AppFabricException("MessageBufferUri can not be null"); } String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); } catch (AppFabricException e) { throw e; } catch (Exception e) { throw new AppFabricException(e.getMessage()); } try { messageBufferUri = messageBufferUri.replaceAll("http", "https"); URL urlConn = new URL(messageBufferUri); HttpURLConnection connection; if (httpWebProxy_ != null) connection = (HttpURLConnection) urlConn.openConnection(httpWebProxy_); else connection = (HttpURLConnection) urlConn.openConnection(); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_ATOM_XML()); connection.setRequestProperty("Content-Length", "" + messageBufferPolicy.length()); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); connection.setRequestProperty("Expect", "100-continue"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(messageBufferPolicy); wr.flush(); wr.close(); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.CreateMessageBuffer_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if ((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_ACCEPTED) || (connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_CREATED) || (connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_OK)) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (LoggerUtil.getIsLoggingOn()) { StringBuilder responseXML = new StringBuilder(); responseXML.append(responseCode); responseXML.append(response.toString()); SDKLoggerHelper.logMessage(URLEncoder.encode(responseXML.toString(), "UTF-8"), SDKLoggerHelper.RecordType.CreateMessageBuffer_RESPONSE); } } else { if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.CreateMessageBuffer_RESPONSE); throw new AppFabricException("MessageBuffer could not be created or updated. Error. Response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new AppFabricException(e.getMessage()); } }
11
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
11
Code Sample 1: 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; } Code Sample 2: protected void sendDoc(File indir, File outdir, File orig, Document doc, ServiceEndpoint ep) { ep.setMethod("simpleDocumentTransfer"); Document response = null; try { response = protocolHandler.sendMessage(ep, doc); } catch (TransportException e) { logger.warn("Message was not accepted, will try again later"); return; } String serial = String.valueOf(System.currentTimeMillis()); File origCopy = new File(outdir, orig.getName() + "." + serial); File respDrop = new File(outdir, orig.getName() + "." + serial + ".resp"); FileOutputStream respos = null; try { respos = new FileOutputStream(respDrop); serializeDocument(respos, response); } catch (IOException e) { logger.warn("Failed to dump response"); return; } finally { try { respos.close(); } catch (IOException ignored) { } } FileInputStream in = null; FileOutputStream out = null; byte[] buffer = new byte[2048]; try { in = new FileInputStream(orig); out = new FileOutputStream(origCopy); int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy original"); return; } finally { try { in.close(); out.close(); } catch (IOException ignored) { } } orig.delete(); logger.info("File processed: " + orig.getName()); }
11
Code Sample 1: public void run() { Vector<Update> updates = new Vector<Update>(); if (dic != null) updates.add(dic); if (gen != null) updates.add(gen); if (res != null) updates.add(res); if (help != null) updates.add(help); for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) { Update update = (Update) iterator.next(); try { File temp = File.createTempFile("fm_" + update.getType(), ".jar"); temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); URL url = new URL(update.getAction()); URLConnection conn = url.openConnection(); com.diccionarioderimas.Utils.setupProxy(conn); InputStream in = conn.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; int total = 0; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); total += read; if (total > 10000) { progressBar.setValue(progressBar.getValue() + total); total = 0; } } out.close(); in.close(); String fileTo = basePath + "diccionariorimas.jar"; if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html"; if (update.getType() == Update.RESBC) { Utils.unzip(temp, new File(fileTo)); } else { Utils.copyFile(new FileInputStream(temp), new File(fileTo)); } } catch (Exception e) { e.printStackTrace(); } } setVisible(false); if (gen != null || res != null) { try { new Main(null, basePath, false); } catch (Exception e) { new ErrorDialog(frame, e); } } String restart = ""; if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario."; JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE); } Code Sample 2: private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } }
11
Code Sample 1: public static String encrypt(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { throw new WebDocRuntimeException(ex); } md.update(text.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); return hash.toString(HEX); } Code Sample 2: public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; }
11
Code Sample 1: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } Code Sample 2: private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
11
Code Sample 1: public void downloadFile(OutputStream os, int fileId) throws IOException, SQLException { Connection conn = null; try { conn = ds.getConnection(); Guard.checkConnectionNotNull(conn); PreparedStatement ps = conn.prepareStatement("select * from FILE_BODIES where file_id=?"); ps.setInt(1, fileId); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new FileNotFoundException("File with id=" + fileId + " not found!"); } Blob blob = rs.getBlob("data"); InputStream is = blob.getBinaryStream(); IOUtils.copyLarge(is, os); } finally { JdbcDaoHelper.safeClose(conn, log); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: @Override public DownloadingItem download(Playlist playlist, String title, File folder, StopDownloadCondition condition, String uuid) throws IOException, StoreStateException { boolean firstIteration = true; Iterator<PlaylistEntry> entries = playlist.getEntries().iterator(); DownloadingItem prevItem = null; File[] previousDownloadedFiles = new File[0]; while (entries.hasNext()) { PlaylistEntry entry = entries.next(); DownloadingItem item = null; LOGGER.info("Downloading from '" + entry.getTitle() + "'"); InputStream is = RESTHelper.inputStream(entry.getUrl()); boolean stopped = false; File nfile = null; try { nfile = createFileStream(folder, entry); item = new DownloadingItem(nfile, uuid.toString(), title, entry, new Date(), getPID(), condition); if (previousDownloadedFiles.length > 0) { item.setPreviousFiles(previousDownloadedFiles); } addItem(item); if (prevItem != null) deletePrevItem(prevItem); prevItem = item; stopped = IOUtils.copyStreams(is, new FileOutputStream(nfile), condition); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); radioScheduler.fireException(e); if (!condition.isStopped()) { File[] nfiles = new File[previousDownloadedFiles.length + 1]; System.arraycopy(previousDownloadedFiles, 0, nfiles, 0, previousDownloadedFiles.length); nfiles[nfiles.length - 1] = item.getFile(); previousDownloadedFiles = nfiles; if ((!entries.hasNext()) && (firstIteration)) { firstIteration = false; entries = playlist.getEntries().iterator(); } continue; } } if (stopped) { item.setState(ProcessStates.STOPPED); this.radioScheduler.fireStopDownloading(item); return item; } } return null; } Code Sample 2: @Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance(SHA1); md.update(text.getBytes(CHAR_SET), 0, text.length()); byte[] mdbytes = md.digest(); return byteToHex(mdbytes); } Code Sample 2: public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: private void handleInterfaceUp(long eventID, long nodeID, String ipAddr, String eventTime) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (eventID == -1 || nodeID == -1 || ipAddr == null) { log.warn(EventConstants.INTERFACE_UP_EVENT_UEI + " ignored - info incomplete - eventid/nodeid/ipAddr: " + eventID + "/" + nodeID + "/" + ipAddr); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); if (openOutageExists(dbConn, nodeID, ipAddr)) { try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGES_FOR_INTERFACE); outageUpdater.setLong(1, eventID); outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime)); outageUpdater.setLong(3, nodeID); outageUpdater.setString(4, ipAddr); int count = outageUpdater.executeUpdate(); outageUpdater.close(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("handleInterfaceUp: interfaceUp closed " + count + " outages for nodeid/ip " + nodeID + "/" + ipAddr + " in DB"); } catch (SQLException se) { log.warn("Rolling back transaction, interfaceUp could not be recorded for nodeId/ipaddr: " + nodeID + "/" + ipAddr, se); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason: ", sqle); } } } else { log.warn("\'" + EventConstants.INTERFACE_UP_EVENT_UEI + "\' for " + nodeID + "/" + ipAddr + " ignored."); } } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceUp\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } } Code Sample 2: public boolean restore(File directory) { log.debug("restore file from directory " + directory.getAbsolutePath()); try { if (!directory.exists()) return false; String[] operationFileNames = directory.list(); if (operationFileNames.length < 6) { log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath()); return false; } int fileCount = 0; for (int i = 0; i < operationFileNames.length; i++) { if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue; log.debug("found file: " + operationFileNames[i]); fileCount++; File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]); File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]); FileReader in = new FileReader(filein); FileWriter out = new FileWriter(fileout); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } if (fileCount < 6) return false; return true; } catch (Exception e) { log.error("Exception while restoring operations files, may not be complete: " + e); return false; } }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } } Code Sample 2: public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public void testResolveURL() throws Exception { System.out.println("resolveURL"); File bigFile = new File("./src/test/java/big.json"); File smallFile = new File("./src/test/java/sample1.json"); Object[] urls = new Object[] { "http://json-schema.org/schema", "http://json-schema.org/hyper-schema", "http://json-schema.org/json-ref", "http://json-schema.org/interfaces", "http://json-schema.org/geo", "http://json-schema.org/card", "http://json-schema.org/calendar", "http://json-schema.org/address", bigFile }; JSONSchemaURIResolverImpl uriResolver = new JSONSchemaURIResolverImpl(); JSONSchemaURIResolverImpl uriResolver2 = new JSONSchemaURIResolverImpl(); try { InputStream is = new URL((String) urls[0]).openStream(); is.close(); } catch (ConnectException cex) { for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver.register(((File) urls[i]).toURI().toURL(), urls[i]); } } } catch (Exception ex) { } for (int i = 2; i < urls.length; i++) { if (urls[i] instanceof String) { String url = (String) urls[i]; uriResolver2.register(new URL(url), new File("./src/test/java/" + url.replace(":", "_").replace("/", "_") + ".schema.json")); } else if (urls[i] instanceof File) { uriResolver2.register(((File) urls[i]).toURI().toURL(), urls[i]); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURI(new URI((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } for (Object source : urls) { try { if (source instanceof String) { StreamSource ss = uriResolver2.resolveURL(new URL((String) source), null); assertNotNull(ss.getReader()); assertNull(ss.getInputStream()); ss.getReader().close(); assertTrue((new URL((String) source)).equals(uriResolver2.lastURL)); assertFalse((new URL((String) source)).equals(uriResolver2.lastMapped)); } } catch (Throwable th) { fail("Unexpected problem: " + source + ". Error: " + th); } } uriResolver2.register(new URL("ftp://localhost/1"), bigFile); uriResolver2.register(new URL("ftp://localhost/2"), smallFile); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile); try { Reader r1 = uriResolver2.resolveURL(new URL("ftp://localhost/2"), null).getReader(); Reader r2 = uriResolver2.resolveURL(new URL("ftp://localhost/2#2"), null).getReader(); int ch = 0; while ((ch = r1.read()) != -1) { assertEquals(ch, r2.read()); } assertEquals(-1, r2.read()); } catch (Throwable th) { fail("Failed while testing identity of same mapped files. Error: " + th); } uriResolver2.register(new URL("ftp://localhost/1"), null); uriResolver2.register(new URL("ftp://localhost/2"), null); uriResolver2.register(new URL("ftp://localhost/2#2"), null); uriResolver2.register(new URL("ftp://localhost/1"), bigFile, true); uriResolver2.register(new URL("ftp://localhost/2"), smallFile, true); uriResolver2.register(new URL("ftp://localhost/2#2"), smallFile, true); uriResolver2.unregister(new URL("ftp://localhost/1"), true); uriResolver2.unregister(new URL("ftp://localhost/2"), true); uriResolver2.unregister(new URL("ftp://localhost/2#2"), true); } Code Sample 2: private static InputStream openStream(final URL url) throws IOException { try { return (InputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return url.openStream(); } }); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } }
00
Code Sample 1: @Override public boolean setupDatabaseSchema() { Configuration cfg = Configuration.getInstance(); Connection con = getConnection(); if (null == con) return false; try { String sql = FileTool.readFile(cfg.getProperty("database.sql.rootdir") + System.getProperty("file.separator") + cfg.getProperty("database.sql.mysql.setupschema")); sql = sql.replaceAll(MYSQL_SQL_SCHEMA_REPLACEMENT, StateSaver.getInstance().getDatabaseSettings().getSchema()); con.setAutoCommit(false); Statement stmt = con.createStatement(); String[] sqlParts = sql.split(";"); for (String sqlPart : sqlParts) { if (sqlPart.trim().length() > 0) stmt.executeUpdate(sqlPart); } con.commit(); JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionsuccess"), language.getProperty("dialog.information.title"), JOptionPane.INFORMATION_MESSAGE); return true; } catch (SQLException e) { Logger.logException(e); } try { if (con != null) con.rollback(); } catch (SQLException e) { Logger.logException(e); } JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionerror"), language.getProperty("dialog.error.title"), JOptionPane.ERROR_MESSAGE); return false; } Code Sample 2: private Document getResponse(HttpGet request) throws ClientProtocolException, IOException, ParserConfigurationException, IllegalStateException, SAXException, NoRoutesException { HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != HTTP_STATUS_OK) throw new ClientProtocolException("The HTTP request is wrong."); allResponse = EntityUtils.toString(response.getEntity()); String responseText = ""; switch(modeOption) { case DRIVING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case WALKING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case PUBLIC_TRANSIT: String responseWithErrors = ""; try { responseWithErrors = allResponse.substring(allResponse.indexOf("<div id=\"tsp\">"), allResponse.indexOf("<div class=\"ddwpt\" id=\"panel_ddw1\" oi=\"wi1\">")); } catch (Exception e) { throw new NoRoutesException(); } responseText = responseWithErrors.replaceAll(".gif\">", ".gif\"/>").replaceAll("colspan=2", "colspan=\"2\"").replaceAll("nowrap", "").replaceAll("&laquo;", "").replaceAll("&nbsp;", "").replaceAll("&raquo;", ""); break; } File xmlFile = new File("./data/temp/response.xml"); PrintWriter writer = new PrintWriter(xmlFile); writer.println(responseText); writer.close(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); return dBuilder.parse(xmlFile); }
00
Code Sample 1: protected void handleUrl(URL url) throws Exception { File file = new File(dir.getAbsolutePath() + "/" + new Date().getTime() + "." + this.ext); FileWriter writer = new FileWriter(file); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; while ((s = in.readLine()) != null) { writer.write(s + "\n"); } in.close(); writer.close(); } Code Sample 2: public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException { final File dstFolder = dstFile.getParentFile(); dstFolder.mkdirs(); if (!dstFolder.exists()) { throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath()); } final InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(dstFile); if (gzipContent) { out = new GZIPOutputStream(out); } try { final byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { in.close(); out.close(); } }
11
Code Sample 1: private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: protected static List<Pattern> getBotPatterns() { List<Pattern> patterns = new ArrayList<Pattern>(); try { Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt"); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8")); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { Pattern pattern = Pattern.compile(line); patterns.add(pattern); } } in.close(); } } catch (IOException e) { throw new RuntimeException("Error reading bot user-agent configuration", e); } return patterns; } Code Sample 2: public int delete(BusinessObject o) throws DAOException { int delete = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CURRENCY")); pst.setInt(1, curr.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
00
Code Sample 1: public String md5(String password) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } m.update(password.getBytes(), 0, password.length()); return new BigInteger(1, m.digest()).toString(16); } Code Sample 2: public RSClassLoader(Map<String, byte[]> classes, URL source) { try { CodeSource codeSource = new CodeSource(source, (CodeSigner[]) null); domain = new ProtectionDomain(codeSource, getPermissions()); this.classes = classes; String s = getClass().getResource("RSClassLoader.class").toString(); s = s.replace("bot/RSClassLoader.class", "client/RandomAccessFile.class"); URL url = new URL(s); InputStream is = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(5000); is = new BufferedInputStream(url.openStream()); byte[] buff = new byte[1024]; int len = -1; while ((len = is.read(buff)) != -1) bos.write(buff, 0, len); byte[] data = bos.toByteArray(); this.classes.put("org.rsbot.client.RandomAccessFile", data); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); } } catch (final Exception ignored) { } }
11
Code Sample 1: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } } Code Sample 2: private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
00
Code Sample 1: public static void main(String[] args) { int dizi[] = { 23, 78, 45, 8, 3, 32, 56, 39, 92, 28 }; boolean test = false; int kars = 0; int tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } for (int i = 0; i < dizi.length; i++) { System.out.print(dizi[i] + " "); } for (int i = 0; i < 5; i++) { System.out.println("i" + i); } } Code Sample 2: public String sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException, NotFoundException { logger.debug(request.getRequestLine().toString()); DefaultHttpClient httpclient = HttpUtil.getNewHttpClient(); configureProxy(httpclient); if (login != null) { final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET))); request.addHeader("Authorization", "Basic: " + credentials); } request.addHeader("Accept-Encoding", "gzip,deflate"); HttpResponse httpResponse = httpclient.execute((HttpUriRequest) request); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server."); } if (responseCode == HttpStatus.SC_FORBIDDEN) { throw new AuthenticationException("Forbidden. Please check the user has proper permissions."); } HttpEntity responseEntity = httpResponse.getEntity(); String responseBody = EntityUtils.toString(responseEntity); if (responseCode == HttpStatus.SC_NOT_FOUND) { throw new NotFoundException("Server returned '404 not found'. response body:" + responseBody); } if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) { List<String> errors = RedmineXMLParser.parseErrors(responseBody); throw new RedmineException(errors); } httpclient.getConnectionManager().shutdown(); return responseBody; }
00
Code Sample 1: public static String encryptPasswd(String pass) { try { if (pass == null || pass.length() == 0) return pass; MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(pass.getBytes("UTF-8")); return Base64OutputStream.encode(sha.digest()); } catch (Throwable t) { throw new SystemException(t); } } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
11
Code Sample 1: public static boolean ejecutarDMLTransaccion(List<String> tirasSQL) throws Exception { boolean ok = true; try { getConexion(); conexion.setAutoCommit(false); Statement st = conexion.createStatement(); for (String cadenaSQL : tirasSQL) { if (st.executeUpdate(cadenaSQL) < 1) { ok = false; break; } } if (ok) conexion.commit(); else conexion.rollback(); conexion.setAutoCommit(true); conexion.close(); } catch (SQLException e) { if (conexion != null && !conexion.isClosed()) { conexion.rollback(); } throw new Exception("Error en Transaccion"); } catch (Exception e) { throw new Exception("Error en Transaccion"); } return ok; } Code Sample 2: public int batchTransactionUpdate(List<String> queryStrLisyt, Connection con) throws Exception { int ret = 0; Statement stmt; if (con != null) { con.setAutoCommit(false); stmt = con.createStatement(); try { stmt.executeUpdate("START TRANSACTION;"); for (int i = 0; i < queryStrLisyt.size(); i++) { stmt.addBatch(queryStrLisyt.get(i)); } int[] updateCounts = stmt.executeBatch(); for (int i = 0; i < updateCounts.length; i++) { FileLogger.debug("batch update result:" + updateCounts[i] + ", Statement.SUCCESS_NO_INFO" + Statement.SUCCESS_NO_INFO); if (updateCounts[i] == Statement.SUCCESS_NO_INFO || updateCounts[i] > 0) { ret++; } else if (updateCounts[i] == Statement.EXECUTE_FAILED) ; { throw new Exception("query failed, while process batch update"); } } con.commit(); } catch (Exception e) { ret = 0; FileLogger.debug(e.getMessage()); con.rollback(); } finally { con.setAutoCommit(true); stmt.close(); } } return ret; }
00
Code Sample 1: public String read(String url) throws IOException { URL myurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(myurl.openStream())); StringBuffer sb = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) sb.append(inputLine); in.close(); return sb.toString(); } Code Sample 2: public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); } Code Sample 2: @Override public void run() { if (mMode == 0) { long currentVersion = Version.extractVersion(App.getVersion()); if (currentVersion == 0) { mMode = 2; RESULT = MSG_UP_TO_DATE; return; } long versionAvailable = currentVersion; mMode = 2; try { StringBuilder buffer = new StringBuilder(mCheckURL); try { NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); if (!ni.isLoopback()) { if (ni.isUp()) { if (!ni.isVirtual()) { buffer.append('?'); byte[] macAddress = ni.getHardwareAddress(); for (byte one : macAddress) { buffer.append(Integer.toHexString(one >>> 4 & 0xF)); buffer.append(Integer.toHexString(one & 0xF)); } } } } } catch (Exception exception) { } URL url = new URL(buffer.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = in.readLine(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, "\t"); if (tokenizer.hasMoreTokens()) { try { if (tokenizer.nextToken().equalsIgnoreCase(mProductKey)) { String token = tokenizer.nextToken(); long version = Version.extractVersion(token); if (version > versionAvailable) { versionAvailable = version; } } } catch (Exception exception) { } } line = in.readLine(); } } catch (Exception exception) { } if (versionAvailable > currentVersion) { Preferences prefs = Preferences.getInstance(); String humanReadableVersion = Version.getHumanReadableVersion(versionAvailable); NEW_VERSION_AVAILABLE = true; RESULT = MessageFormat.format(MSG_OUT_OF_DATE, humanReadableVersion); if (versionAvailable > Version.extractVersion(prefs.getStringValue(MODULE, LAST_VERSION_KEY, App.getVersion()))) { prefs.setValue(MODULE, LAST_VERSION_KEY, humanReadableVersion); prefs.save(); mMode = 1; EventQueue.invokeLater(this); return; } } else { RESULT = MSG_UP_TO_DATE; } } else if (mMode == 1) { if (App.isNotificationAllowed()) { String result = getResult(); mMode = 2; if (WindowUtils.showConfirmDialog(null, result, MSG_UPDATE_TITLE, JOptionPane.OK_CANCEL_OPTION, new String[] { MSG_UPDATE_TITLE, MSG_IGNORE_TITLE }, MSG_UPDATE_TITLE) == JOptionPane.OK_OPTION) { goToUpdate(); } } else { DelayedTask.schedule(this, 250); } } }
11
Code Sample 1: static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException { try { method.getParams().setSoTimeout(timeout * 1000); int status = -1; Object result = null; System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString()); TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration(); HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword()); status = httpClient.executeMethod(method); System.out.println("Received response. status = " + status); if (status == HttpStatus.SC_OK) { InputStream inputStream = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(inputStream, baos); String response = new String(baos.toByteArray(), "UTF-8"); System.out.println(response); if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response); } else { throw new HttpRequestFailureException(status); } return result; } catch (SocketTimeoutException e) { throw new HttpRequestTimeoutException(e); } finally { method.releaseConnection(); } } Code Sample 2: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public static void main(String[] args) { if (args.length == 0) { System.out.println("Specify name of the file, just one entry per line"); System.exit(0); } File inFile = new File(args[0]); BufferedReader myBR = null; File outFile = new File(args[0] + ".xml"); BufferedWriter myBW = null; try { myBR = new BufferedReader(new FileReader(inFile)); myBW = new BufferedWriter(new FileWriter(outFile)); } catch (Exception ex) { System.out.println("IN: " + inFile.getAbsolutePath()); System.out.println("OUT: " + outFile.getAbsolutePath()); ex.printStackTrace(); System.exit(0); } try { String readLine; while ((readLine = myBR.readLine()) != null) { myBW.write("<dbColumn name=\"" + readLine + "\" display=\"" + readLine + "\" panel=\"CENTER\" >"); myBW.write("\n"); myBW.write("<dbType name=\"text\" maxVal=\"10\" defaultVal=\"\" sizeX=\"5\"/>"); myBW.write("\n"); myBW.write("</dbColumn>"); myBW.write("\n"); } myBW.close(); myBR.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } System.out.println("OUT: " + outFile.getAbsolutePath()); System.out.println("erzeugt"); } Code Sample 2: private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public void read(Model m, String url) throws JenaException { try { URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url); } catch (FileNotFoundException e) { throw new DoesNotExistException(url); } catch (IOException e) { throw new JenaException(e); } } Code Sample 2: private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
11
Code Sample 1: public static String md5(String text) { String hashed = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes(), 0, text.length()); hashed = new BigInteger(1, digest.digest()).toString(16); } catch (Exception e) { Log.e(ctGlobal.tag, "ctCommon.md5: " + e.toString()); } return hashed; } Code Sample 2: public synchronized String decrypt(String plaintext) throws Exception { MessageDigest md = null; String strhash = new String((new BASE64Decoder()).decodeBuffer(plaintext)); System.out.println("strhash1122 " + strhash); try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } byte raw[] = md.digest(); try { md.update(new String(raw).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } System.out.println("plain text " + strhash); String strcode = new String(raw); System.out.println("strcode.." + strcode); return strcode; }
00
Code Sample 1: private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); } Code Sample 2: public String uploadVideo(String ticketId, String filePath) { TreeMap<String, String> uploadParams = new TreeMap<String, String>(); String url = "http://www.vimeo.com/services/upload/"; uploadParams.put("api_key", apiKey); uploadParams.put("auth_token", this.TEMP_AUTH_TOKEN); uploadParams.put("ticket_id", ticketId); uploadParams.put("format", "json"); String signature = this.generateAppSignature(uploadParams); uploadParams.put("api_sig", signature); ClientHttpRequest request = null; try { request = new ClientHttpRequest(new URL(url).openConnection()); } catch (IOException e) { e.printStackTrace(); } for (Entry<String, String> param : uploadParams.entrySet()) { try { request.setParameter(param.getKey(), param.getValue()); } catch (IOException e) { e.printStackTrace(); } } InputStream videoInput = null; try { videoInput = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { request.setParameter("video", filePath, videoInput); } catch (IOException e) { e.printStackTrace(); } InputStream response = null; try { response = request.post(); } catch (IOException e) { e.printStackTrace(); } try { InputStreamReader inR = new InputStreamReader(response); BufferedReader buf = new BufferedReader(inR); String line; try { while ((line = buf.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return "hey"; }
00
Code Sample 1: @Override public void execute() throws BuildException { final String GC_USERNAME = "google-code-username"; final String GC_PASSWORD = "google-code-password"; if (StringUtils.isBlank(this.projectName)) throw new BuildException("undefined project"); if (this.file == null) throw new BuildException("undefined file"); if (!this.file.exists()) throw new BuildException("file not found :" + file); if (!this.file.isFile()) throw new BuildException("not a file :" + file); if (this.config == null) throw new BuildException("undefined config"); if (!this.config.exists()) throw new BuildException("file not found :" + config); if (!this.config.isFile()) throw new BuildException("not a file :" + config); PostMethod post = null; try { Properties cfg = new Properties(); FileInputStream fin = new FileInputStream(this.config); cfg.loadFromXML(fin); fin.close(); if (!cfg.containsKey(GC_USERNAME)) throw new BuildException("undefined " + GC_USERNAME + " in " + this.config); if (!cfg.containsKey(GC_PASSWORD)) throw new BuildException("undefined " + GC_PASSWORD + " in " + this.config); HttpClient client = new HttpClient(); post = new PostMethod("https://" + projectName + ".googlecode.com/files"); post.addRequestHeader("User-Agent", getClass().getName()); post.addRequestHeader("Authorization", "Basic " + Base64.encode(cfg.getProperty(GC_USERNAME) + ":" + cfg.getProperty(GC_PASSWORD))); List<Part> parts = new ArrayList<Part>(); String s = this.summary; if (StringUtils.isBlank(s)) { s = this.file.getName() + " (" + TimeUtils.toYYYYMMDD() + ")"; } parts.add(new StringPart("summary", s)); for (String lbl : this.labels.split("[, \t\n]+")) { if (StringUtils.isBlank(lbl)) continue; parts.add(new StringPart("label", lbl.trim())); } parts.add(new FilePart("filename", this.file)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()); post.setRequestEntity(requestEntity); int status = client.executeMethod(post); if (status != 201) { throw new BuildException("http status !=201 : " + post.getResponseBodyAsString()); } else { IOUtils.copyTo(post.getResponseBodyAsStream(), new NullOutputStream()); } } catch (BuildException e) { throw e; } catch (Exception e) { throw new BuildException(e); } finally { if (post != null) post.releaseConnection(); } } Code Sample 2: public final InputSource getInputSource() { if (url == null) throw new RuntimeException("Cannot find table defs"); try { InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); return new InputSource(reader); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; } Code Sample 2: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: public DAS getDAS() throws MalformedURLException, IOException, ParseException, DASException, DODSException { InputStream is; if (fileStream != null) is = parseMime(fileStream); else { URL url = new URL(urlString + ".das" + projString + selString); if (dumpDAS) { System.out.println("--DConnect.getDAS to " + url); copy(url.openStream(), System.out); System.out.println("\n--DConnect.getDAS END1"); dumpBytes(url.openStream(), 100); System.out.println("\n-DConnect.getDAS END2"); } is = openConnection(url); } DAS das = new DAS(); try { das.parse(is); } finally { is.close(); if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect(); } return das; } Code Sample 2: public void doGet(HttpServletRequest request_, HttpServletResponse response) throws IOException, ServletException { Writer out = null; DatabaseAdapter dbDyn = null; PreparedStatement st = null; try { RenderRequest renderRequest = null; RenderResponse renderResponse = null; ContentTypeTools.setContentType(response, ContentTypeTools.CONTENT_TYPE_UTF8); out = response.getWriter(); AuthSession auth_ = (AuthSession) renderRequest.getUserPrincipal(); if (auth_ == null) { throw new IllegalStateException("You have not enough right to execute this operation"); } PortletSession session = renderRequest.getPortletSession(); dbDyn = DatabaseAdapter.getInstance(); String index_page = PortletService.url("mill.price.index", renderRequest, renderResponse); Long id_shop = null; if (renderRequest.getParameter(ShopPortlet.NAME_ID_SHOP_PARAM) != null) { id_shop = PortletService.getLong(renderRequest, ShopPortlet.NAME_ID_SHOP_PARAM); } else { Long id_ = (Long) session.getAttribute(ShopPortlet.ID_SHOP_SESSION); if (id_ == null) { response.sendRedirect(index_page); return; } id_shop = id_; } session.removeAttribute(ShopPortlet.ID_SHOP_SESSION); session.setAttribute(ShopPortlet.ID_SHOP_SESSION, id_shop); if (auth_.isUserInRole("webmill.edit_price_list")) { Long id_item = PortletService.getLong(renderRequest, "id_item"); if (id_item == null) throw new IllegalArgumentException("id_item not initialized"); if (RequestTools.getString(renderRequest, "action").equals("update")) { dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_PRICE_ITEM_DESCRIPTION a " + "where exists " + " ( select null from WM_PRICE_LIST b " + " where b.id_shop = ? and b.id_item = ? and " + " a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #1 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_PRICE_ITEM_DESCRIPTION " + "(ID_PRICE_ITEM_DESCRIPTION, ID_ITEM, TEXT)" + "(select seq_WM_PRICE_ITEM_DESCRIPTION.nextval, ID_ITEM, ? " + " from WM_PRICE_LIST b where b.ID_SHOP = ? and b.ID_ITEM = ? )"; try { int idx = 0; int offset = 0; int j = 0; byte[] b = StringTools.getBytesUTF(RequestTools.getString(renderRequest, "n")); st = dbDyn.prepareStatement(sql_); while ((idx = StringTools.getStartUTF(b, 2000, offset)) != -1) { st.setString(1, new String(b, offset, idx - offset, "utf-8")); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); st.addBatch(); offset = idx; if (j > 10) break; j++; } int[] updateCounts = st.executeBatch(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); out.write("Error #2 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); if (st != null) { DatabaseManager.close(st); st = null; } } } if (RequestTools.getString(renderRequest, "action").equals("new_image") && renderRequest.getParameter("id_image") != null) { Long id_image = PortletService.getLong(renderRequest, "id_image"); dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_IMAGE_PRICE_ITEMS a " + "where exists " + " ( select null from WM_PRICE_LIST b " + "where b.id_shop = ? and b.id_item = ? and " + "a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #3 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_IMAGE_PRICE_ITEMS " + "(id_IMAGE_PRICE_ITEMS, id_item, ID_IMAGE_DIR)" + "(select seq_WM_IMAGE_PRICE_ITEMS.nextval, id_item, ? " + " from WM_PRICE_LIST b where b.id_shop = ? and b.id_item = ? )"; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_image); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); int updateCounts = st.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); log.error("Error insert image", e0); out.write("Error #4 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); DatabaseManager.close(st); st = null; } } if (true) throw new Exception("Need refactoring"); } } catch (Exception e) { log.error(e); out.write(ExceptionTools.getStackTrace(e, 20, "<br>")); } finally { DatabaseManager.close(dbDyn, st); st = null; dbDyn = null; } }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void copyZip() { InputStream is; OutputStream os; String javacZip = ""; try { if ("windows".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacWin.zip"; is = UnZip.class.getResourceAsStream("javacWin.zip"); } else if ("linux".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacLinux.zip"; is = UnZip.class.getResourceAsStream("javacLinux.zip"); } is = UnZip.class.getResourceAsStream(javacZip); File tempZip = File.createTempFile("tempJavacJTraductor", ".zip"); tempZip.mkdir(); tempZip.deleteOnExit(); os = FileUtils.openOutputStream(tempZip); IOUtils.copy(is, os); is.close(); os.close(); extractZip(tempZip.getPath()); } catch (Exception ex) { JOptionPane.showMessageDialog(PseutemView.mainPanel, "Error al copiar los archivos temporales necesarios para ejecutar el programa:\n\n" + ex, "Error copiando.", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: private void anneal(final float maxGamma, final float gammaAccel, final float objectiveTolerance, final float objectiveAccel, final float scoreTolerance, final float paramTolerance, final float distanceLimit, final float randomLimit, final long randomSeed, final BufferedDocuments<Phrase> references, final int n, final int maxNbest, File stateFile, boolean keepState) { float gamma = 0; boolean annealObjective = true; double[] convergedScores = new double[n]; double[] totalLogScores = new double[n]; boolean[] isConverged = new boolean[n]; GradientPoint[] initPoints = new GradientPoint[n]; GradientPoint[] prevInitPoints = new GradientPoint[n]; GradientPoint[] bestInitPoints = new GradientPoint[n]; GradientPoint[] prevMinPoints = new GradientPoint[n]; Random rand = new Random(randomSeed); Time time = new Time(); if (stateFile != null && stateFile.length() > 0) { time.reset(); try { ObjectInputStream stream = new ObjectInputStream(new FileInputStream(stateFile)); gamma = stream.readFloat(); annealObjective = stream.readBoolean(); convergedScores = (double[]) stream.readObject(); totalLogScores = (double[]) stream.readObject(); isConverged = (boolean[]) stream.readObject(); initPoints = (GradientPoint[]) stream.readObject(); prevInitPoints = (GradientPoint[]) stream.readObject(); bestInitPoints = (GradientPoint[]) stream.readObject(); prevMinPoints = (GradientPoint[]) stream.readObject(); rand = (Random) stream.readObject(); int size = stream.readInt(); for (int id = 0; id < size; id++) { Feature feature = FEATURES.getRaw(CONFIG, stream.readUTF(), 0f); if (feature.getId() != id) throw new Exception("Features have changed"); } evaluation.read(stream); stream.close(); output.println("# Resuming from previous optimization state (" + time + ")"); output.println(); } catch (Exception e) { e.printStackTrace(); Log.getInstance().severe("Failed loading optimization state (" + stateFile + "): " + e.getMessage()); } } else { final int evaluations = ProjectedEvaluation.CFG_OPT_HISTORY_SIZE.getValue(); final GradientPoint[] randPoints = new GradientPoint[n * evaluations]; for (int i = 0; i < n; i++) { evaluation.setParallelId(i); for (int j = 0; j < evaluations; j++) { if (i != 0) randPoints[i * n + j] = getRandomPoint(rand, randPoints[0], distanceLimit, null); evaluate(references, i + ":" + j); if (i == 0) { randPoints[0] = new GradientPoint(evaluation, null); gamma = LogFeatureModel.FEAT_MODEL_GAMMA.getValue(); break; } } } for (int i = 0; i < randPoints.length; i++) if (randPoints[i] != null) randPoints[i] = new GradientPoint(evaluation, randPoints[i], output); for (int i = 0; i < n; i++) { prevInitPoints[i] = null; initPoints[i] = randPoints[i * n]; if (i != 0) for (int j = 1; j < evaluations; j++) if (randPoints[i * n + j].getScore() < initPoints[i].getScore()) initPoints[i] = randPoints[i * n + j]; bestInitPoints[i] = initPoints[i]; convergedScores[i] = Float.MAX_VALUE; } } for (int searchCount = 1; ; searchCount++) { boolean isFinished = true; for (int i = 0; i < n; i++) isFinished = isFinished && isConverged[i]; if (isFinished) { output.println("*** N-best list converged. Modifying annealing schedule. ***"); output.println(); if (annealObjective) { boolean objectiveConverged = true; for (int i = 0; objectiveConverged && i < n; i++) objectiveConverged = isConverged(bestInitPoints[i].getScore(), convergedScores[i], objectiveTolerance, SCORE_EPSILON); annealObjective = false; for (Metric<ProjectedSentenceEvaluation> metric : AbstractEvaluation.CFG_EVAL_METRICS.getValue()) if (metric.doAnnealing()) { float weight = metric.getWeight(); if (weight != 0) if (objectiveConverged) metric.setWeight(0); else { annealObjective = true; metric.setWeight(weight / objectiveAccel); } } } if (!annealObjective) { if (Math.abs(gamma) >= maxGamma) { GradientPoint bestPoint = bestInitPoints[0]; for (int i = 1; i < n; i++) if (bestInitPoints[i].getScore() < bestPoint.getScore()) bestPoint = bestInitPoints[i]; output.format("Best Score: %+.7g%n", bestPoint.getScore()); output.println(); bestPoint = new GradientPoint(evaluation, bestPoint, output); break; } gamma *= gammaAccel; if (Math.abs(gamma) + GAMMA_EPSILON >= maxGamma) gamma = gamma >= 0 ? maxGamma : -maxGamma; } for (int i = 0; i < n; i++) { convergedScores[i] = bestInitPoints[i].getScore(); initPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], gamma, output); bestInitPoints[i] = initPoints[i]; prevInitPoints[i] = null; prevMinPoints[i] = null; isConverged[i] = false; } searchCount = 0; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; if (n > 1) output.println("Minimizing point " + i); Gradient gradient = initPoints[i].getGradient(); for (int id = 0; id < FEATURES.size(); id++) output.format("GRAD %-65s %-+13.7g%n", FEATURES.getName(id), gradient.get(id)); output.println(); time.reset(); GradientPoint minPoint = minimize(initPoints[i], prevInitPoints[i], bestInitPoints[i], scoreTolerance, paramTolerance, distanceLimit, randomLimit, rand); final float[] weights = minPoint.getWeights(); for (int j = 0; j < weights.length; j++) output.format("PARM %-65s %-+13.7g%n", FEATURES.getName(j), weights[j]); output.println(); output.format("Minimum Score: %+.7g (average distance of %.2f)%n", minPoint.getScore(), minPoint.getAverageDistance()); output.println(); output.println("# Minimized gradient (" + time + ")"); output.println(); output.flush(); isConverged[i] = weights == initPoints[i].getWeights(); prevInitPoints[i] = initPoints[i]; prevMinPoints[i] = minPoint; initPoints[i] = minPoint; } for (int i = 0; i < n; i++) { if (isConverged[i]) continue; isConverged[i] = isConvergedScore("minimum", prevMinPoints[i], prevInitPoints[i], scoreTolerance) && isConvergedWeights(prevMinPoints[i], prevInitPoints[i], paramTolerance); prevMinPoints[i].setWeightsAndRescore(evaluation); evaluation.setParallelId(i); evaluate(references, Integer.toString(i)); } Set<Point> prunePoints = new HashSet<Point>(); prunePoints.addAll(Arrays.asList(bestInitPoints)); prunePoints.addAll(Arrays.asList(prevInitPoints)); prunePoints.addAll(Arrays.asList(initPoints)); evaluation.prune(prunePoints, maxNbest, output); for (int i = 0; i < n; i++) { final boolean bestIsPrev = bestInitPoints[i] == prevInitPoints[i]; final boolean bestIsInit = bestInitPoints[i] == initPoints[i]; bestInitPoints[i] = new GradientPoint(evaluation, bestInitPoints[i], bestIsInit ? output : null); if (bestIsPrev) prevInitPoints[i] = bestInitPoints[i]; if (bestIsInit) initPoints[i] = bestInitPoints[i]; if (!bestIsPrev && prevInitPoints[i] != null) { prevInitPoints[i] = new GradientPoint(evaluation, prevInitPoints[i], null); if (prevInitPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = prevInitPoints[i]; } if (!bestIsInit) { initPoints[i] = new GradientPoint(evaluation, initPoints[i], output); if (initPoints[i].getScore() <= bestInitPoints[i].getScore()) bestInitPoints[i] = initPoints[i]; } } for (int i = 0; i < n; i++) if (isConverged[i]) if (prevMinPoints[i] == null) { output.println("# Convergence failed: no previous minimum is defined"); output.println(); isConverged[i] = false; } else { isConverged[i] = isConvergedScore("best known", bestInitPoints[i], initPoints[i], scoreTolerance) && isConvergedScore("previous minimum", prevMinPoints[i], initPoints[i], scoreTolerance); } if (stateFile != null) { time.reset(); try { File dir = stateFile.getCanonicalFile().getParentFile(); File temp = File.createTempFile("cunei-opt-", ".tmp", dir); ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(temp)); stream.writeFloat(gamma); stream.writeBoolean(annealObjective); stream.writeObject(convergedScores); stream.writeObject(totalLogScores); stream.writeObject(isConverged); stream.writeObject(initPoints); stream.writeObject(prevInitPoints); stream.writeObject(bestInitPoints); stream.writeObject(prevMinPoints); stream.writeObject(rand); stream.writeInt(FEATURES.size()); for (int id = 0; id < FEATURES.size(); id++) stream.writeUTF(FEATURES.getName(id)); evaluation.write(stream); stream.close(); if (!temp.renameTo(stateFile)) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(temp).getChannel(); out = new FileOutputStream(stateFile).getChannel(); in.transferTo(0, in.size(), out); temp.delete(); } finally { if (in != null) in.close(); if (out != null) out.close(); } } output.println("# Saved optimization state (" + time + ")"); output.println(); } catch (IOException e) { Log.getInstance().severe("Failed writing optimization state: " + e.getMessage()); } } } if (stateFile != null && !keepState) stateFile.delete(); } Code Sample 2: private void copyIntoFile(String resource, File output) throws IOException { FileOutputStream out = null; InputStream in = null; try { out = FileUtils.openOutputStream(output); in = GroovyInstanceTest.class.getResourceAsStream(resource); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }
11
Code Sample 1: public static String computeMD5(InputStream input) { InputStream digestStream = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); digestStream = new DigestInputStream(input, md5); IOUtils.copy(digestStream, new NullOutputStream()); return new String(Base64.encodeBase64(md5.digest()), "UTF-8"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(digestStream); } } Code Sample 2: public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); }
00
Code Sample 1: private String fetchHtml(URL url) throws IOException { URLConnection connection; if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort)); connection = url.openConnection(proxy); } else { connection = url.openConnection(); } Object content = connection.getContent(); if (content instanceof InputStream) { return IOUtils.toString(InputStream.class.cast(content)); } else { String msg = "Bad content type! " + content.getClass(); log.error(msg); throw new IOException(msg); } } Code Sample 2: public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; }
00
Code Sample 1: public static String getRandomUserAgent() { if (USER_AGENT_CACHE == null) { Collection<String> userAgentsCache = new ArrayList<String>(); try { URL url = Tools.getResource(UserAgent.class.getClassLoader(), "user-agents-browser.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { userAgentsCache.add(str); } in.close(); USER_AGENT_CACHE = userAgentsCache.toArray(new String[userAgentsCache.size()]); } catch (Exception e) { System.err.println("Can not read file; using default user-agent; error message: " + e.getMessage()); return DEFAULT_USER_AGENT; } } return USER_AGENT_CACHE[new Random().nextInt(USER_AGENT_CACHE.length)]; } Code Sample 2: public Reader getConfResourceAsReader(String name) { try { URL url = getResource(name); if (url == null) { LOG.info(name + " not found"); return null; } else { LOG.info("found resource " + name + " at " + url); } return new InputStreamReader(url.openStream()); } catch (Exception e) { return null; } }
11
Code Sample 1: public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); Options options = new Options(); options.addOption("p", "put", false, "put a file in the DHT overlay"); options.addOption("g", "get", false, "get a file from the DHT"); options.addOption("r", "remove", false, "remove a file from the DHT"); options.addOption("u", "update", false, "updates the lease"); options.addOption("j", "join", false, "join the DHT overlay"); options.addOption("c", "config", true, "the configuration file"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("a", "app", true, "the application ID"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String configFile = null; String mode = null; String secretStr = null; int ttl = 9999; String keyStr = null; String file = null; int appId = 0; if (cmd.hasOption("j")) { mode = "join"; } if (cmd.hasOption("p")) { mode = "put"; } if (cmd.hasOption("g")) { mode = "get"; } if (cmd.hasOption("r")) { mode = "remove"; } if (cmd.hasOption("u")) { mode = "update"; } if (cmd.hasOption("c")) { configFile = cmd.getOptionValue("c"); } if (cmd.hasOption("k")) { keyStr = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secretStr = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("a")) { appId = Integer.parseInt(cmd.getOptionValue("a")); } if (mode == null) { System.err.println("ERROR: --put or --get or --remove or --join or --update is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (configFile == null) { System.err.println("ERROR: --config is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } Properties conf = new Properties(); conf.load(new FileInputStream(configFile)); DHT dht = new DHT(conf); if (mode.equals("join")) { dht.join(); } else if (mode.equals("put")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("putting file " + file); FileInputStream in = new FileInputStream(file); byte[] tmp = new byte[1000000]; int num = in.read(tmp); byte[] value = new byte[num]; System.arraycopy(tmp, 0, value, 0, num); in.close(); if (dht.put((short) appId, keyStr.getBytes(), value, ttl, secretStr.getBytes()) < 0) { logger.info("There was an error while putting a key-value."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("get")) { if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("getting file " + file); ArrayList<byte[]> values = new ArrayList<byte[]>(); if (dht.get((short) appId, keyStr.getBytes(), Integer.MAX_VALUE, values) < 0) { logger.info("There was an error while getting a value."); System.exit(0); } if (values.size() == 0 || values == null) { System.out.println("No values returned."); System.exit(0); } FileOutputStream out = new FileOutputStream(file); System.out.println("Found " + values.size() + " values -- saving the first one only."); out.write(values.get(0)); out.close(); System.out.println("Ok!"); } else if (mode.equals("remove")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } if (secretStr == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("removing <key,value> for key=" + keyStr); if (dht.remove((short) appId, keyStr.getBytes(), secretStr.getBytes()) < 0) { logger.info("There was an error while removing a key."); System.exit(0); } System.out.println("Ok!"); } else if (mode.equals("update")) { if (keyStr == null) { System.err.println("ERROR: --key is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DHT", options); System.exit(1); } logger.info("updating <key,value> for key=" + keyStr); if (dht.updateLease((short) appId, keyStr.getBytes(), ttl) < 0) { logger.info("There was an error while updating data lease."); System.exit(0); } System.out.println("Ok!"); } DHT.getInstance().stop(); } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
11
Code Sample 1: public static final String MD5(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String newValue = hash.toString(16); return newValue; } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return null; } } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
11
Code Sample 1: public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) { try { Class.forName("org.sqlite.JDBC"); String fileName = pictogramsPath + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { int idL = 0, idT = 0; G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\""); while (rs.next()) { idL = rs.getInt("id"); } rs.close(); stat.close(); stat = G.conn.createStatement(); rs = stat.executeQuery("select id from type where name=\"" + type + "\""); while (rs.next()) { idT = rs.getInt("id"); } rs.close(); stat.close(); String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length()); String idOrig = id; String pathSrc = pictogramToAddPath; String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, word.toLowerCase()); stmt.setInt(2, idL); stmt.setInt(3, idT); stmt.setString(4, id); stmt.setString(5, idOrig); stmt.executeUpdate(); stmt.close(); G.conn.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
00
Code Sample 1: protected URL[][] getImageLinks(final URL url) { Lexer lexer; URL[][] ret; if (null != url) { try { lexer = new Lexer(url.openConnection()); ret = extractImageLinks(lexer, url); } catch (Throwable t) { System.out.println(t.getMessage()); ret = NONE; } } else ret = NONE; return (ret); } Code Sample 2: protected void unZip() throws PersistenceException { boolean newZip = false; try { if (null == backup) { mode = (String) context.get(Context.MODE); if (null == mode) mode = Context.MODE_NAME_RESTORE; backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY); logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backupDirectory.mkdirs(); } else if (!backupDirectory.exists()) { throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist."); } backup = new File(backupDirectory + "/" + getBackupName() + ".zip"); logger.debug("Got zip file {" + backup.getAbsolutePath() + "}"); } File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip"); _explodedDirectory.mkdirs(); _explodedDirectory.delete(); backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName()); backupDirectory.mkdirs(); logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}"); if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) { newZip = true; backup.createNewFile(); } else if (!backup.exists()) { throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist."); } if (newZip) return; ZipFile zip = new ZipFile(backup); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); logger.debug("Inflating: " + entry); File destFile = new File(backupDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { InputStream in = null; OutputStream out = null; try { in = zip.getInputStream(entry); out = new FileOutputStream(destFile); IOUtils.copy(in, out); } finally { if (null != out) out.close(); if (null != in) in.close(); } } } } catch (IOException e) { logger.error("Unable to unzip {" + backup + "}", e); throw new PersistenceException(e); } }
00
Code Sample 1: public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) { return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyStream(in, out, 1024); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } } Code Sample 2: public boolean smsResponse(String customerPhoneNumber) throws ClientProtocolException, IOException { boolean message = true; String textMessage = "La%20sua%20prenotazione%20e%60%20andata%20a%20buon%20fine"; DefaultHttpClient httpclient = new DefaultHttpClient(); String uri = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String other = "http://smswizard.globalitalia.it/smsgateway/send.asp"; String url = uri + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=" + "%2b393285683484" + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=Web Hotel" + "&ID=11762"; String urlProva = other + "?" + "Account=sardricerche" + "&Password=v8LomdZT" + "&PhoneNumbers=" + customerPhoneNumber + "&SMSData=" + textMessage + "&Recipients=1" + "&Sender=+393337589951" + "&ID=11762"; HttpPost httpPost = new HttpPost(urlProva); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); return message; }
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: @Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
11
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: 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(); } }
00
Code Sample 1: public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } } Code Sample 2: static MenuListener openRecentHandler() { MenuListener handler = new MenuListener() { public void menuSelected(final MenuEvent event) { final JMenu menu = (JMenu) event.getSource(); menu.removeAll(); String[] recentURLSpecs = Application.getApp().getRecentURLSpecs(); for (int index = 0; index < recentURLSpecs.length; index++) { String urlSpec = recentURLSpecs[index]; JMenuItem menuItem = new JMenuItem(urlSpec); menu.add(menuItem); menuItem.setAction(openURLAction(urlSpec)); menuItem.setText(urlSpec); try { new java.net.URL(urlSpec).openStream(); } catch (java.io.IOException exception) { menuItem.setEnabled(false); } } menu.addSeparator(); final JMenuItem clearItem = new JMenuItem("Clear"); clearItem.setAction(new AbstractAction() { public void actionPerformed(final ActionEvent event) { Application.getApp().clearRecentItems(); } }); clearItem.setText("Clear"); menu.add(clearItem); } public void menuCanceled(final MenuEvent event) { } public void menuDeselected(final MenuEvent event) { } }; return handler; }
11
Code Sample 1: public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } } Code Sample 2: private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); }
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: @Override public void start() { System.err.println("start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); super.start(); model = new ApplicationModel(); model.setExceptionHandler(new ExceptionHandler() { public void handle(Throwable t) { t.printStackTrace(); } public void handleUncaught(Throwable t) { t.printStackTrace(); } }); model.setApplet(true); model.dom.getOptions().setAutolayout(false); System.err.println("ApplicationModel created @ " + (System.currentTimeMillis() - t0) + " msec"); model.addDasPeersToApp(); System.err.println("done addDasPeersToApp @ " + (System.currentTimeMillis() - t0) + " msec"); try { System.err.println("Formatters: " + DataSourceRegistry.getInstance().getFormatterExtensions()); } catch (Exception ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } ApplicationModel appmodel = model; dom = model.getDocumentModel(); String debug = getParameter("debug"); if (debug != null && !debug.equals("true")) { } int width = getIntParameter("width", 700); int height = getIntParameter("height", 400); String fontParam = getStringParameter("font", ""); String column = getStringParameter("column", ""); String row = getStringParameter("row", ""); String scolor = getStringParameter("color", ""); String srenderType = getStringParameter("renderType", ""); String stimeRange = getStringParameter("timeRange", ""); String sfillColor = getStringParameter("fillColor", ""); String sforegroundColor = getStringParameter("foregroundColor", ""); String sbackgroundColor = getStringParameter("backgroundColor", ""); String title = getStringParameter("plot.title", ""); String xlabel = getStringParameter("plot.xaxis.label", ""); String xrange = getStringParameter("plot.xaxis.range", ""); String xlog = getStringParameter("plot.xaxis.log", ""); String xdrawTickLabels = getStringParameter("plot.xaxis.drawTickLabels", ""); String ylabel = getStringParameter("plot.yaxis.label", ""); String yrange = getStringParameter("plot.yaxis.range", ""); String ylog = getStringParameter("plot.yaxis.log", ""); String ydrawTickLabels = getStringParameter("plot.yaxis.drawTickLabels", ""); String zlabel = getStringParameter("plot.zaxis.label", ""); String zrange = getStringParameter("plot.zaxis.range", ""); String zlog = getStringParameter("plot.zaxis.log", ""); String zdrawTickLabels = getStringParameter("plot.zaxis.drawTickLabels", ""); statusCallback = getStringParameter("statusCallback", ""); timeCallback = getStringParameter("timeCallback", ""); clickCallback = getStringParameter("clickCallback", ""); if (srenderType.equals("fill_to_zero")) { srenderType = "fillToZero"; } setInitializationStatus("readParameters"); System.err.println("done readParameters @ " + (System.currentTimeMillis() - t0) + " msec"); String vap = getParameter("vap"); if (vap != null) { InputStream in = null; try { URL url = new URL(vap); System.err.println("load vap " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); in = url.openStream(); System.err.println("open vap stream " + url + " @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.doOpen(in, null); System.err.println("done open vap @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.waitUntilIdle(false); System.err.println("done load vap and waitUntilIdle @ " + (System.currentTimeMillis() - t0) + " msec"); Canvas cc = appmodel.getDocumentModel().getCanvases(0); System.err.println("vap height, width= " + cc.getHeight() + "," + cc.getWidth()); width = getIntParameter("width", cc.getWidth()); height = getIntParameter("height", cc.getHeight()); System.err.println("output height, width= " + width + "," + height); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } } appmodel.getCanvas().setSize(width, height); appmodel.getCanvas().revalidate(); appmodel.getCanvas().setPrintingTag(""); dom.getOptions().setAutolayout("true".equals(getParameter("autolayout"))); if (!dom.getOptions().isAutolayout() && vap == null) { if (!row.equals("")) { dom.getController().getCanvas().getController().setRow(row); } if (!column.equals("")) { dom.getController().getCanvas().getController().setColumn(column); } dom.getCanvases(0).getRows(0).setTop("0%"); dom.getCanvases(0).getRows(0).setBottom("100%"); } if (!fontParam.equals("")) { appmodel.canvas.setBaseFont(Font.decode(fontParam)); } JMenuItem item; item = new JMenuItem(new AbstractAction("Reset Zoom") { public void actionPerformed(ActionEvent e) { resetZoom(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(item); overviewMenuItem = new JCheckBoxMenuItem(new AbstractAction("Context Overview") { public void actionPerformed(ActionEvent e) { addOverview(); } }); dom.getPlots(0).getController().getDasPlot().getDasMouseInputAdapter().addMenuItem(overviewMenuItem); if (sforegroundColor != null && !sforegroundColor.equals("")) { appmodel.canvas.setForeground(Color.decode(sforegroundColor)); } if (sbackgroundColor != null && !sbackgroundColor.equals("")) { appmodel.canvas.setBackground(Color.decode(sbackgroundColor)); } getContentPane().setLayout(new BorderLayout()); System.err.println("done set parameters @ " + (System.currentTimeMillis() - t0) + " msec"); String surl = getParameter("url"); String process = getStringParameter("process", ""); String script = getStringParameter("script", ""); if (surl == null) { surl = getParameter("dataSetURL"); } if (surl != null && !surl.equals("")) { DataSource dsource; try { dsource = DataSetURI.getDataSource(surl); System.err.println("get dsource for " + surl + " @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" got dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); } catch (NullPointerException ex) { throw new RuntimeException("No such data source: ", ex); } catch (Exception ex) { ex.printStackTrace(); dsource = null; } DatumRange timeRange1 = null; if (!stimeRange.equals("")) { timeRange1 = DatumRangeUtil.parseTimeRangeValid(stimeRange); TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb != null) { System.err.println("do tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); tsb.setTimeRange(timeRange1); System.err.println("done tsb.setTimeRange @ " + (System.currentTimeMillis() - t0) + " msec"); } } QDataSet ds; if (dsource != null) { TimeSeriesBrowse tsb = dsource.getCapability(TimeSeriesBrowse.class); if (tsb == null) { try { System.err.println("do getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); System.err.println(" dsource=" + dsource); System.err.println(" dsource.getClass()=" + dsource.getClass()); if (dsource.getClass().toString().contains("CsvDataSource")) System.err.println(" WHY IS THIS CsvDataSource!?!?"); ds = dsource == null ? null : dsource.getDataSet(loadInitialMonitor); for (int i = 0; i < Math.min(12, ds.length()); i++) { System.err.printf("ds[%d]=%s\n", i, ds.slice(i)); } System.err.println("loaded ds: " + ds); System.err.println("done getDataSet @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (Exception ex) { throw new RuntimeException(ex); } } } System.err.println("do setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); appmodel.setDataSource(dsource); System.err.println("done setDataSource @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("dataSourceSet"); if (stimeRange != null && !stimeRange.equals("")) { try { System.err.println("wait for idle @ " + (System.currentTimeMillis() - t0) + " msec (due to stimeRange)"); appmodel.waitUntilIdle(true); System.err.println("done wait for idle @ " + (System.currentTimeMillis() - t0) + " msec"); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } if (UnitsUtil.isTimeLocation(dom.getTimeRange().getUnits())) { dom.setTimeRange(timeRange1); } } setInitializationStatus("dataSetLoaded"); } System.err.println("done dataSetLoaded @ " + (System.currentTimeMillis() - t0) + " msec"); Plot p = dom.getController().getPlot(); if (!title.equals("")) { p.setTitle(title); } Axis axis = p.getXaxis(); if (!xlabel.equals("")) { axis.setLabel(xlabel); } if (!xrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(xrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!xlog.equals("")) { axis.setLog("true".equals(xlog)); } if (!xdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(xdrawTickLabels)); } axis = p.getYaxis(); if (!ylabel.equals("")) { axis.setLabel(ylabel); } if (!yrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(yrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!ylog.equals("")) { axis.setLog("true".equals(ylog)); } if (!ydrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(ydrawTickLabels)); } axis = p.getZaxis(); if (!zlabel.equals("")) { axis.setLabel(zlabel); } if (!zrange.equals("")) { try { Units u = axis.getController().getDasAxis().getUnits(); DatumRange newRange = DatumRangeUtil.parseDatumRange(zrange, u); axis.setRange(newRange); } catch (ParseException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } } if (!zlog.equals("")) { axis.setLog("true".equals(zlog)); } if (!zdrawTickLabels.equals("")) { axis.setDrawTickLabels("true".equals(zdrawTickLabels)); } if (srenderType != null && !srenderType.equals("")) { try { RenderType renderType = RenderType.valueOf(srenderType); dom.getController().getPlotElement().setRenderType(renderType); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } } System.err.println("done setRenderType @ " + (System.currentTimeMillis() - t0) + " msec"); if (!scolor.equals("")) { try { dom.getController().getPlotElement().getStyle().setColor(Color.decode(scolor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sfillColor.equals("")) { try { dom.getController().getPlotElement().getStyle().setFillColor(Color.decode(sfillColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sforegroundColor.equals("")) { try { dom.getOptions().setForeground(Color.decode(sforegroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } if (!sbackgroundColor.equals("")) { try { dom.getOptions().setBackground(Color.decode(sbackgroundColor)); } catch (Exception ex) { ex.printStackTrace(); } } surl = getParameter("dataSetURL"); if (surl != null) { if (surl.startsWith("about:")) { setDataSetURL(surl); } else { } } getContentPane().remove(progressComponent); getContentPane().add(model.getCanvas()); System.err.println("done add to applet @ " + (System.currentTimeMillis() - t0) + " msec"); validate(); System.err.println("done applet.validate @ " + (System.currentTimeMillis() - t0) + " msec"); repaint(); appmodel.getCanvas().setVisible(true); initializing = false; repaint(); System.err.println("ready @ " + (System.currentTimeMillis() - t0) + " msec"); setInitializationStatus("ready"); dom.getController().getPlot().getXaxis().addPropertyChangeListener(Axis.PROP_RANGE, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { timeCallback(String.valueOf(evt.getNewValue())); } }); if (!clickCallback.equals("")) { String clickCallbackLabel = "Applet Click"; int i = clickCallback.indexOf(","); if (i != -1) { int i2 = clickCallback.indexOf("label="); if (i2 != -1) clickCallbackLabel = clickCallback.substring(i2 + 6).trim(); clickCallback = clickCallback.substring(0, i).trim(); } final DasPlot plot = dom.getPlots(0).getController().getDasPlot(); MouseModule mm = new MouseModule(plot, new CrossHairRenderer(plot, null, plot.getXAxis(), plot.getYAxis()), clickCallbackLabel) { @Override public void mousePressed(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseDragged(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } @Override public void mouseReleased(MouseEvent e) { e = SwingUtilities.convertMouseEvent(plot, e, plot.getCanvas()); clickCallback(dom.getPlots(0).getId(), plot, e); } }; plot.getDasMouseInputAdapter().setPrimaryModule(mm); } p.getController().getDasPlot().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getXaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getYaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); dom.getPlots(0).getZaxis().getController().getDasAxis().getDasMouseInputAdapter().removeMenuItem("Properties"); if (getStringParameter("contextOverview", "off").equals("on")) { Runnable run = new Runnable() { public void run() { dom.getController().waitUntilIdle(); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(AutoplotApplet.class.getName()).log(Level.SEVERE, null, ex); } dom.getController().waitUntilIdle(); doSetOverview(true); } }; new Thread(run).start(); } System.err.println("done start AutoplotApplet " + VERSION + " @ " + (System.currentTimeMillis() - t0) + " msec"); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private void makeConn(String filename1, String filename2) { String basename = "http://www.bestmm.com/"; String urlname = basename + filename1 + "/pic/" + filename2 + ".jpg"; URL url = null; try { url = new URL(urlname); } catch (MalformedURLException e) { System.err.println("URL Format Error!"); System.exit(1); } try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.err.println("Error IO"); System.exit(2); } }
00
Code Sample 1: public void run() { logger.info("downloading '" + url.toString() + "' to: " + dstFile.getAbsolutePath()); Preferences prefs = Preferences.userRoot().node("gvsig.downloader"); int timeout = prefs.getInt("timeout", 60000); DataOutputStream dos; try { DataInputStream is; OutputStreamWriter os = null; HttpURLConnection connection = null; if (url.getProtocol().equals("https")) { disableHttsValidation(); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(timeout); if (data != null) { connection.setRequestProperty("SOAPAction", "post"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); os = new OutputStreamWriter(connection.getOutputStream()); os.write(data); os.flush(); is = new DataInputStream(connection.getInputStream()); } else { is = new DataInputStream(url.openStream()); } dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile))); byte[] buffer = new byte[1024 * 4]; long readed = 0; for (int i = is.read(buffer); !Utilities.getCanceled(groupID) && i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } if (os != null) { os.close(); } dos.close(); is.close(); is = null; dos = null; if (Utilities.getCanceled(groupID)) { logger.warning("[RemoteServices] '" + url + "' CANCELED."); dstFile.delete(); dstFile = null; } else { Utilities.addDownloadedURL(url, dstFile.getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); Utilities.downloadException = e; } } Code Sample 2: @Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
00
Code Sample 1: public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } } Code Sample 2: public static String md5(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException { StringBuffer result = new StringBuffer(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes("utf-8")); byte[] digest = md.digest(); for (byte b : digest) { result.append(String.format("%02X ", b & 0xff)); } return result.toString(); }
11
Code Sample 1: public static String digestString(String data) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; } Code Sample 2: private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; }
00
Code Sample 1: public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); } Code Sample 2: @Override public int run() { Enumeration<?> e; try { e = About.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (e.hasMoreElements()) { final URL url = (URL) e.nextElement(); if (url.toString().indexOf("renaissance") != -1) { final InputStream is = url.openStream(); Properties p = new Properties(); p.load(is); for (Entry<?, ?> entry : p.entrySet()) { System.err.println(entry); } } } } catch (IOException e1) { logger.fatal("Caught an exception " + e1); return 1; } System.err.println("Classpath is " + System.getProperty("java.class.path")); return 0; }
11
Code Sample 1: public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
11
Code Sample 1: @Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } } Code Sample 2: public static void copy(String from, String to) throws Exception { File inputFile = new File(from); File outputFile = new File(to); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); }
00
Code Sample 1: protected boolean check(String username, String password, String realm, String nonce, String nc, String cnonce, String qop, String uri, String response, HttpServletRequest request) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update((byte) ':'); md.update(realm.getBytes()); md.update((byte) ':'); md.update(password.getBytes()); byte[] ha1 = md.digest(); md.reset(); md.update(request.getMethod().getBytes()); md.update((byte) ':'); md.update(uri.getBytes()); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes()); md.update((byte) ':'); md.update(nonce.getBytes()); md.update((byte) ':'); md.update(nc.getBytes()); md.update((byte) ':'); md.update(cnonce.getBytes()); md.update((byte) ':'); md.update(qop.getBytes()); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes()); byte[] digest = md.digest(); return response.equals(encode(digest)); } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: private static final void addFile(ZipArchiveOutputStream os, File file, String prefix) throws IOException { ArchiveEntry entry = os.createArchiveEntry(file, file.getAbsolutePath().substring(prefix.length() + 1)); os.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, os); fis.close(); os.closeArchiveEntry(); } Code Sample 2: public boolean crear() { int result = 0; String sql = "insert into divisionxTorneo" + "(torneo_idTorneo, tipoTorneo_idTipoTorneo, nombreDivision, descripcion, numJugadores, numFechas, terminado, tipoDesempate, rondaActual, ptosxbye)" + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(); result = 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 (result > 0); }
00
Code Sample 1: public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: public static String hash(final String s) { if (s == null || s.length() == 0) return null; try { final MessageDigest hashEngine = MessageDigest.getInstance("SHA-1"); hashEngine.update(s.getBytes("iso-8859-1"), 0, s.length()); return convertToHex(hashEngine.digest()); } catch (final Exception e) { return null; } }