id
int32
0
901k
id1
int32
74
23.7M
id2
int32
74
23.7M
func1
stringlengths
234
68.5k
func2
stringlengths
234
68.5k
label
bool
2 classes
901,000
10,713,685
20,009,109
public static boolean unzip_and_merge(String infile, String outfile) { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(infile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); FileOutputStream fos = new FileOutputStream(outfile); dest = new BufferedOutputStream(fos, BUFFER); while (zis.getNextEntry() != null) { int count; byte data[] = new byte[BUFFER]; while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); } dest.close(); zis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); }
true
901,001
6,908,540
21,461,878
public void create_list() { try { String data = URLEncoder.encode("PHPSESSID", "UTF-8") + "=" + URLEncoder.encode(this.get_session(), "UTF-8"); URL url = new URL(URL_LOLA + FILE_CREATE_LIST); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; line = rd.readLine(); wr.close(); rd.close(); System.out.println("Gene list saved in LOLA"); } catch (Exception e) { System.out.println("error in createList()"); e.printStackTrace(); } }
private boolean verifyAppId(String appid) { try { String urlstr = "http://" + appid + ".appspot.com"; URL url = new URL(urlstr); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); return buf.toString().contains("hyk-proxy"); } catch (Exception e) { } return false; }
true
901,002
3,058,818
12,101,435
public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
true
901,003
11,651,293
22,423,727
public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); }
public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
true
901,004
19,204,595
8,250,731
protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
false
901,005
21,321,505
13,536,658
public void run() { try { IOUtils.copy(is, os); os.flush(); } catch (IOException ioe) { logger.error("Unable to copy", ioe); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
private String protectMarkup(String content, String markupRegex, String replaceSource, String replaceTarget) { Matcher matcher = Pattern.compile(markupRegex, Pattern.MULTILINE | Pattern.DOTALL).matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String protectedMarkup = matcher.group(); protectedMarkup = protectedMarkup.replaceAll(replaceSource, replaceTarget); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(protectedMarkup.getBytes("UTF-8")); String hash = bytesToHash(digest.digest()); matcher.appendReplacement(result, hash); c_protectionMap.put(hash, protectedMarkup); m_hashList.add(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } matcher.appendTail(result); return result.toString(); }
false
901,006
9,257,486
21,285,620
public static boolean dumpFile(String from, File to, String lineBreak) { try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from))); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to))); String line = null; while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak); in.close(); out.close(); } catch (Exception e) { Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e)); return false; } return true; }
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
true
901,007
5,854,498
19,875,183
public void handleMessage(Message message) throws Fault { InputStream is = message.getContent(InputStream.class); if (is == null) { return; } CachedOutputStream bos = new CachedOutputStream(); try { IOUtils.copy(is, bos); is.close(); bos.close(); sendMsg("Inbound Message \n" + "--------------" + bos.getOut().toString() + "\n--------------"); message.setContent(InputStream.class, bos.getInputStream()); } catch (IOException e) { throw new Fault(e); } }
private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
true
901,008
2,831,663
3,260,787
public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } }
public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).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(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
true
901,009
3,558,514
2,285,441
private synchronized void ensureParsed() throws IOException, BadIMSCPException { if (cp != null) return; if (on_disk == null) { on_disk = createTemporaryFile(); OutputStream to_disk = new FileOutputStream(on_disk); IOUtils.copy(in.getInputStream(), to_disk); to_disk.close(); } try { ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser(); parser.parse(on_disk); cp = parser.getPackage(); } catch (BadParseException x) { throw new BadIMSCPException("Cannot parse content package", x); } }
static synchronized Person lookup(PhoneNumber number, String siteName) { Vector<Person> foundPersons = new Vector<Person>(5); if (number.isFreeCall()) { Person p = new Person("", "FreeCall"); p.addNumber(number); foundPersons.add(p); } else if (number.isSIPNumber() || number.isQuickDial()) { Person p = new Person(); p.addNumber(number); foundPersons.add(p); } else if (ReverseLookup.rlsMap.containsKey(number.getCountryCode())) { nummer = number.getAreaNumber(); rls_list = ReverseLookup.rlsMap.get(number.getCountryCode()); Debug.info("Begin reverselookup for: " + nummer); if (nummer.startsWith(number.getCountryCode())) nummer = nummer.substring(number.getCountryCode().length()); city = ""; for (int i = 0; i < rls_list.size(); i++) { yield(); rls = rls_list.get(i); if (!siteName.equals("") && !siteName.equals(rls.getName())) { Debug.warning("This lookup should be done using a specific site, skipping"); continue; } prefix = rls.getPrefix(); ac_length = rls.getAreaCodeLength(); if (!nummer.startsWith(prefix)) nummer = prefix + nummer; urlstr = rls.getURL(); if (urlstr.contains("$AREACODE")) { urlstr = urlstr.replaceAll("\\$AREACODE", nummer.substring(prefix.length(), ac_length + prefix.length())); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else if (urlstr.contains("$PFXAREACODE")) { urlstr = urlstr.replaceAll("\\$PFXAREACODE", nummer.substring(0, prefix.length() + ac_length)); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else urlstr = urlstr.replaceAll("\\$NUMBER", nummer); Debug.info("Reverse lookup using: " + urlstr); url = null; data = new String[dataLength]; try { url = new URL(urlstr); if (url != null) { try { con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(15000); con.addRequestProperty("User-Agent", userAgent); con.connect(); header = ""; charSet = ""; for (int j = 0; ; j++) { String headerName = con.getHeaderFieldKey(j); String headerValue = con.getHeaderField(j); if (headerName == null && headerValue == null) { break; } if ("content-type".equalsIgnoreCase(headerName)) { String[] split = headerValue.split(";", 2); for (int k = 0; k < split.length; k++) { if (split[k].trim().toLowerCase().startsWith("charset=")) { String[] charsetSplit = split[k].split("="); charSet = charsetSplit[1].trim(); } } } header += headerName + ": " + headerValue + " | "; } Debug.debug("Header of " + rls.getName() + ":" + header); Debug.debug("CHARSET : " + charSet); BufferedReader d; if (charSet.equals("")) { d = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); } else { d = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } int lines = 0; while (null != ((str = d.readLine()))) { data[lines] = str; yield(); if (lines >= dataLength) { System.err.println("Result > " + dataLength + " Lines"); break; } lines++; } d.close(); Debug.info("Begin processing response from " + rls.getName()); for (int j = 0; j < rls.size(); j++) { yield(); firstname = ""; lastname = ""; company = ""; street = ""; zipcode = ""; city = ""; Person p = null; patterns = rls.getEntry(j); Pattern namePattern = null; Pattern streetPattern = null; Pattern cityPattern = null; Pattern zipcodePattern = null; Pattern firstnamePattern = null; Pattern lastnamePattern = null; Matcher nameMatcher = null; Matcher streetMatcher = null; Matcher cityMatcher = null; Matcher zipcodeMatcher = null; Matcher firstnameMatcher = null; Matcher lastnameMatcher = null; if (!patterns[ReverseLookupSite.NAME].equals("") && (patterns[ReverseLookupSite.FIRSTNAME].equals("") && patterns[ReverseLookupSite.LASTNAME].equals(""))) { namePattern = Pattern.compile(patterns[ReverseLookupSite.NAME]); } if (!patterns[ReverseLookupSite.STREET].equals("")) { streetPattern = Pattern.compile(patterns[ReverseLookupSite.STREET]); } if (!patterns[ReverseLookupSite.CITY].equals("")) { cityPattern = Pattern.compile(patterns[ReverseLookupSite.CITY]); } if (!patterns[ReverseLookupSite.ZIPCODE].equals("")) { zipcodePattern = Pattern.compile(patterns[ReverseLookupSite.ZIPCODE]); } if (!patterns[ReverseLookupSite.FIRSTNAME].equals("")) { firstnamePattern = Pattern.compile(patterns[ReverseLookupSite.FIRSTNAME]); } if (!patterns[ReverseLookupSite.LASTNAME].equals("")) { lastnamePattern = Pattern.compile(patterns[ReverseLookupSite.LASTNAME]); } for (int line = 0; line < dataLength; line++) { if (data[line] != null) { int spaceAlternative = 160; data[line] = data[line].replaceAll(new Character((char) spaceAlternative).toString(), " "); if (lastnamePattern != null) { lastnameMatcher = lastnamePattern.matcher(data[line]); if (lastnameMatcher.find()) { str = ""; for (int k = 1; k <= lastnameMatcher.groupCount(); k++) { if (lastnameMatcher.group(k) != null) str = str + lastnameMatcher.group(k).trim() + " "; } lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if ("lastname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setLastName(lastname); } } } yield(); if (firstnamePattern != null) { firstnameMatcher = firstnamePattern.matcher(data[line]); if (firstnameMatcher.find()) { str = ""; for (int k = 1; k <= firstnameMatcher.groupCount(); k++) { if (firstnameMatcher.group(k) != null) str = str + firstnameMatcher.group(k).trim() + " "; } firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); firstname = firstname.trim(); firstname = firstname.replaceAll(",", ""); firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); if ("firstname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); } } } yield(); if (namePattern != null) { nameMatcher = namePattern.matcher(data[line]); if (nameMatcher.find()) { str = ""; for (int k = 1; k <= nameMatcher.groupCount(); k++) { if (nameMatcher.group(k) != null) str = str + nameMatcher.group(k).trim() + " "; } String[] split; split = str.split(" ", 2); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(split[0])); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if (split[1].length() > 0) { firstname = HTMLUtil.stripEntities(split[1]); if ((firstname.indexOf(" ") > -1) && (firstname.indexOf(" u.") == -1)) { company = JFritzUtils.removeLeadingSpaces(firstname.substring(firstname.indexOf(" ")).trim()); firstname = JFritzUtils.removeLeadingSpaces(firstname.substring(0, firstname.indexOf(" ")).trim()); } else { firstname = JFritzUtils.removeLeadingSpaces(firstname.replaceAll(" u. ", " und ")); } } firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); firstname = firstname.trim(); company = company.replaceAll("%20", " "); company = JFritzUtils.replaceSpecialCharsUTF(company); company = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(company)); company = JFritzUtils.removeDuplicateWhitespace(company); company = company.trim(); if ("name".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); if (company.length() > 0) { p.addNumber(number.getIntNumber(), "business"); } else { p.addNumber(number.getIntNumber(), "home"); } foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); p.setLastName(lastname); p.setCompany(company); } } } yield(); if (streetPattern != null) { streetMatcher = streetPattern.matcher(data[line]); if (streetMatcher.find()) { str = ""; for (int k = 1; k <= streetMatcher.groupCount(); k++) { if (streetMatcher.group(k) != null) str = str + streetMatcher.group(k).trim() + " "; } street = str.replaceAll("%20", " "); street = JFritzUtils.replaceSpecialCharsUTF(street); street = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(street)); street = JFritzUtils.removeDuplicateWhitespace(street); street = street.trim(); if ("street".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setStreet(street); } } } yield(); if (cityPattern != null) { cityMatcher = cityPattern.matcher(data[line]); if (cityMatcher.find()) { str = ""; for (int k = 1; k <= cityMatcher.groupCount(); k++) { if (cityMatcher.group(k) != null) str = str + cityMatcher.group(k).trim() + " "; } city = str.replaceAll("%20", " "); city = JFritzUtils.replaceSpecialCharsUTF(city); city = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(city)); city = JFritzUtils.removeDuplicateWhitespace(city); city = city.trim(); if ("city".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setCity(city); } } } yield(); if (zipcodePattern != null) { zipcodeMatcher = zipcodePattern.matcher(data[line]); if (zipcodeMatcher.find()) { str = ""; for (int k = 1; k <= zipcodeMatcher.groupCount(); k++) { if (zipcodeMatcher.group(k) != null) str = str + zipcodeMatcher.group(k).trim() + " "; } zipcode = str.replaceAll("%20", " "); zipcode = JFritzUtils.replaceSpecialCharsUTF(zipcode); zipcode = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(zipcode)); zipcode = JFritzUtils.removeDuplicateWhitespace(zipcode); zipcode = zipcode.trim(); if ("zipcode".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setPostalCode(zipcode); } } } } } if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) break; } yield(); if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) { if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } return foundPersons.get(0); } } catch (IOException e1) { Debug.error("Error while retrieving " + urlstr); } } } catch (MalformedURLException e) { Debug.error("URL invalid: " + urlstr); } } yield(); Debug.warning("No match for " + nummer + " found"); if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } Person p = new Person("", "", "", "", "", city, "", ""); p.addNumber(number.getAreaNumber(), "home"); return p; } else { Debug.warning("No reverse lookup sites for: " + number.getCountryCode()); Person p = new Person(); p.addNumber(number.getAreaNumber(), "home"); if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(number.getIntNumber()); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(number.getIntNumber()); p.setCity(city); return p; } return new Person("not found", "Person"); }
false
901,010
7,396,679
8,068,393
public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { LOG.debug("[sgkim] copy - start"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in = null; OutputStream out = null; try { LOG.debug("[sgkim] srcFS: " + srcFS + ", src: " + src); in = srcFS.open(src); LOG.debug("[sgkim] dstFS: " + dstFS + ", dst: " + dst); out = dstFS.create(dst, overwrite); LOG.debug("[sgkim] copyBytes - start"); IOUtils.copyBytes(in, out, conf, true); LOG.debug("[sgkim] copyBytes - end"); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } LOG.debug("[sgkim] copy - end"); if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }
public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; }
true
901,011
2,157,431
12,197,340
@Override public String doInBackground() { boolean skinsDownloaded = false; dao = DataAccessFactory.getUMCDataSourceAccessor(DataAccessFactory.DB_TYPE_SQLITE, Publisher.getInstance().getParamDBDriverconnect() + Publisher.getInstance().getParamDBName(), Publisher.getInstance().getParamDBDriver(), Publisher.getInstance().getParamDBUser(), Publisher.getInstance().getParamDBPwd()); File downloadDir = new File(UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads"); if (!downloadDir.exists()) { if (!downloadDir.mkdir()) { log.error("Could not create download folder '" + downloadDir.getAbsolutePath() + "' - create this directory and try again! "); } } if (downloadDir.exists()) { int[] i = tableOnline.getSelectedRows(); for (int a = 0; a < i.length; a++) { Update update = tableOnlineModel.getUpdate(i[a]); if (update.getType().equals(Update.TYPE_SKIN)) skinsDownloaded = true; if (UMCConstants.debug) log.debug("Starting to download UMC " + update.getType() + ": " + update.getDescription() + " - Version " + update.getVersionAvailable() + " from " + update.getDownloadURL()); try { int bytesRead = 0, bytesWrite = 0; double totalBytes = 0; URL url = new URL(update.getDownloadURL()); URLConnection urlC = url.openConnection(); urlC.setConnectTimeout(10000); totalBytes = urlC.getContentLength(); firePropertyChange("FILE", null, update.getName() + " " + sizeFormater.format(totalBytes / 1024)); InputStream is = url.openStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads" + UMCConstants.fileSeparator + update.getDownloadURL().substring(update.getDownloadURL().lastIndexOf("/"), update.getDownloadURL().length()))); byte[] buf = new byte[1024 * 8]; while ((bytesRead = is.read(buf)) != -1) { bos.write(buf, 0, bytesRead); bytesWrite += bytesRead; publish(new Double(bytesWrite / totalBytes * 100).intValue()); } is.close(); bos.close(); String zip = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads" + UMCConstants.fileSeparator + update.getDownloadURL().substring(update.getDownloadURL().lastIndexOf("/"), update.getDownloadURL().length()); String destDir = ""; if (update.getType().equals(Update.TYPE_SKIN)) { destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "resources" + UMCConstants.fileSeparator + "Skins" + UMCConstants.fileSeparator + update.getName(); } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIEDB)) { destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "moviedb" + UMCConstants.fileSeparator + update.getName(); } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_SERIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_MUSICSCANNER) || update.getType().equals(Update.TYPE_PLUGIN_PHOTOSCANNER)) { destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "scanner" + UMCConstants.fileSeparator + update.getName(); } else if (update.getType().equals(Update.TYPE_PLUGIN_GUI)) { destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "gui" + UMCConstants.fileSeparator + update.getName(); } else { return "Download type could not be identified -> disgarding package"; } File f = new File(destDir); if (!f.exists()) { f.mkdir(); } ZipFile zipFile = new ZipFile(zip); firePropertyChange("INSTALL", null, update.getName() + " - " + zipFile.size() + " files"); Enumeration entries = zipFile.entries(); int count = 0; int maxSize = zipFile.size(); byte[] buffer = new byte[16384]; int len; while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String entryFileName = entry.getName(); int lastIndex = entryFileName.lastIndexOf('/'); String internalPathToEntry = entryFileName.substring(0, lastIndex + 1); File dir = new File(destDir, internalPathToEntry); if (!dir.exists()) { dir.mkdirs(); } if (!entry.isDirectory()) { count++; publish(new Double((count / maxSize) * 100).intValue()); bos = new BufferedOutputStream(new FileOutputStream(new File(destDir, entryFileName))); BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); while ((len = bis.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.flush(); bos.close(); bis.close(); } } if (update.getType().equals(Update.TYPE_SKIN)) { dao.registerSkin(update.getName(), update.getVersionAvailable()); } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIEDB)) { dao.registerPlugin(update.getName(), update.getVersionAvailable()); } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_SERIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_MUSICSCANNER) || update.getType().equals(Update.TYPE_PLUGIN_PHOTOSCANNER)) { dao.registerPlugin(update.getName(), update.getVersionAvailable()); } else if (update.getType().equals(Update.TYPE_PLUGIN_GUI)) { dao.registerPlugin(update.getName(), update.getVersionAvailable()); } tableOnlineModel.removeUpdate(i[a]); tableOnline.updateUI(); } catch (MalformedURLException e) { log.error(e); return "MalformedURLException"; } catch (IOException e) { log.error(e); return "IO Error"; } catch (Exception e) { log.error(e); return "Installation Error"; } } } else { return "Error"; } if (skinsDownloaded) { Publisher.getInstance().findAllSkins(); Publisher.getInstance().refreshParams(); Publisher.getInstance().createFrontendDirectoryStructure(); } return "OK"; }
private void initBanner() { for (int k = 0; k < 3; k++) { if (bannerImg == null) { int i = getRandomId(); imageURL = NbBundle.getMessage(BottomContent.class, "URL_BannerImageLink", Integer.toString(i)); bannerURL = NbBundle.getMessage(BottomContent.class, "URL_BannerLink", Integer.toString(i)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(imageURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { bannerImg = new ImageIcon(ImageIO.read(entity.getContent())); EntityUtils.consume(entity); } } catch (IOException ex) { bannerImg = null; } finally { method.abort(); } } else { break; } } if (bannerImg == null) { NotifyUtil.error("Banner Error", "Application could not get banner image. Please check your internet connection.", false); } }
false
901,012
3,220,986
18,797,768
public static String calculateHash(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.reset(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(password.getBytes()); return byteToBase64(md.digest()); }
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; } }
true
901,013
22,165,218
8,862,015
private String readHtmlFile(String htmlFileName) { StringBuffer buffer = new StringBuffer(); java.net.URL url = getClass().getClassLoader().getResource("freestyleLearning/homeCore/help/" + htmlFileName); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String string = " "; while (string != null) { string = reader.readLine(); if (string != null) buffer.append(string); } } catch (Exception exc) { System.out.println(exc); } return new String(buffer); }
@Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { List<String> taxa = new Vector<String>(); String domain = m_domain.getStringValue(); String id = ""; if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota"; try { URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; String line = ""; while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]); ENADataHolder.instance().put(ena.desc, ena); taxa.add(ena.desc); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
true
901,014
16,105,484
6,613,739
private String callPage(String urlStr) throws IOException { URL url = new URL(urlStr); BufferedReader reader = null; StringBuilder result = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } } finally { if (reader != null) reader.close(); } return result.toString(); }
private static MappedObject sendHttpRequestToUrl(URL url, String method) throws Exception { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder buffer = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } System.out.println("Read: " + buffer.toString()); connection.disconnect(); JAXBContext context = JAXBContext.newInstance(MappedObject.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MappedObject mapped = (MappedObject) unmarshaller.unmarshal(new StringReader(buffer.toString())); return mapped; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Could not establish connection to " + url.toExternalForm()); }
true
901,015
20,913,493
4,249,821
public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } }
private String loadStatusResult() { try { URL url = new URL(getServerUrl()); InputStream input = url.openStream(); InputStreamReader is = new InputStreamReader(input, "utf-8"); BufferedReader reader = new BufferedReader(is); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (MalformedURLException e1) { e1.printStackTrace(); return null; } catch (IOException e2) { e2.printStackTrace(); return null; } }
false
901,016
308,643
19,685,311
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(); } }
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel srcChannel = new FileInputStream(inputFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outputFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
true
901,017
103,593
17,194,629
public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
public static InputStream openRemoteFile(URL urlParam) throws KExceptionClass { InputStream result = null; try { result = urlParam.openStream(); } catch (IOException error) { String message = new String(); message = "No se puede abrir el recurso ["; message += urlParam.toString(); message += "]["; message += error.toString(); message += "]"; throw new KExceptionClass(message, error); } ; return (result); }
false
901,018
4,697,215
14,093,045
public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
@Override public boolean delete(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasDelete = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("delete")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasDelete = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasDelete > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Delete"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } }
false
901,019
1,725,724
3,197,089
public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
true
901,020
20,870,396
7,976,872
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(); } }
public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
true
901,021
4,349,491
970,639
public void migrateTo(String newExt) throws IOException { DigitalObject input = new DigitalObject.Builder(Content.byReference(new File(AllJavaSEServiceTestsuite.TEST_FILE_LOCATION + "PlanetsLogo.png").toURI().toURL())).build(); System.out.println("Input: " + input); FormatRegistry format = FormatRegistryFactory.getFormatRegistry(); MigrateResult mr = dom.migrate(input, format.createExtensionUri("png"), format.createExtensionUri(newExt), null); ServiceReport sr = mr.getReport(); System.out.println("Got Report: " + sr); DigitalObject doOut = mr.getDigitalObject(); assertTrue("Resulting digital object is null.", doOut != null); System.out.println("Output: " + doOut); System.out.println("Output.content: " + doOut.getContent()); File out = new File("services/java-se/test/results/test." + newExt); FileOutputStream fo = new FileOutputStream(out); IOUtils.copyLarge(doOut.getContent().getInputStream(), fo); fo.close(); System.out.println("Recieved service report: " + mr.getReport()); System.out.println("Recieved service properties: "); ServiceProperties.printProperties(System.out, mr.getReport().getProperties()); }
public static String unsecureHashConstantSalt(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT3 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT4; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
false
901,022
7,926,874
934,048
public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } }
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!"); }
true
901,023
5,981,201
7,760,801
public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); }
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; }
true
901,024
7,396,680
12,980,227
public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString != null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } }
public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); }
true
901,025
18,101,018
7,655,679
public void write(HttpServletRequest req, HttpServletResponse res, Object bean) throws IntrospectionException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException { res.setContentType(contentType); final Object r; if (HttpRpcServer.HttpRpcOutput.class.isAssignableFrom(bean.getClass())) { HttpRpcServer.HttpRpcOutput output = (HttpRpcServer.HttpRpcOutput) bean; r = output.getResult(); } else r = bean; if (r != null) { final ServletOutputStream outputStream = res.getOutputStream(); if (File.class.isAssignableFrom(r.getClass())) { File file = (File) r; InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } else if (InputStream.class.isAssignableFrom(r.getClass())) { InputStream in = null; try { in = (InputStream) r; if (ByteArrayInputStream.class.isAssignableFrom(r.getClass())) res.addHeader("Content-Length", Integer.toString(in.available())); IOUtils.copy(in, outputStream); } finally { if (in != null) in.close(); } } outputStream.flush(); } }
public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
true
901,026
8,597,004
16,803,474
public String getHtmlSource(String url) { StringBuffer codeBuffer = null; BufferedReader in = null; URLConnection uc = null; try { uc = new URL(url).openConnection(); uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)"); in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8")); codeBuffer = new StringBuffer(); String tempCode = ""; while ((tempCode = in.readLine()) != null) { codeBuffer.append(tempCode).append("\n"); } in.close(); tempCode = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != in) in = null; if (null != uc) uc = null; } return codeBuffer.toString(); }
public static void copyFile(File source, File dest) throws Exception { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); try { int read = fis.read(); while (read != -1) { fos.write(read); read = fis.read(); } } finally { fos.close(); } } finally { fis.close(); } }
false
901,027
17,079,357
19,718,986
public static void copyFile(File file, String destDir) throws IOException { if (!isCanReadFile(file)) throw new RuntimeException("The File can't read:" + file.getPath()); if (!isCanWriteDirectory(destDir)) throw new RuntimeException("The Directory can't write:" + destDir); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(file).getChannel(); dstChannel = new FileOutputStream(destDir + "/" + file.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { throw e; } finally { if (srcChannel != null) try { srcChannel.close(); } catch (IOException e) { } if (dstChannel != null) try { dstChannel.close(); } catch (IOException e) { } } }
public static void concatenateToDestFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IllegalArgumentException("Could not create destination file:" + destFile.getName()); } } BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; byte[] buffer = new byte[1024]; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile, true)); bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile)); while (true) { int readByte = bufferedInputStream.read(buffer, 0, buffer.length); if (readByte == -1) { break; } bufferedOutputStream.write(buffer, 0, readByte); } } finally { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } }
true