{"func1": " private void copy(File source, File destinationDirectory) throws IOException {\n if (source.isDirectory()) {\n File newDir = new File(destinationDirectory, source.getName());\n newDir.mkdir();\n File[] children = source.listFiles();\n for (int i = 0; i < children.length; i++) {\n if (children[i].getName().equals(\".svn\")) {\n continue;\n }\n copy(children[i], newDir);\n }\n } else {\n File newFile = new File(destinationDirectory, source.getName());\n if (newFile.exists() && source.lastModified() == newFile.lastModified()) {\n return;\n }\n FileOutputStream output = new FileOutputStream(newFile);\n FileInputStream input = new FileInputStream(source);\n byte[] buff = new byte[2048];\n int read = 0;\n while ((read = input.read(buff)) > 0) {\n output.write(buff, 0, read);\n }\n output.flush();\n output.close();\n input.close();\n }\n }\n", "func2": " public static void main(String[] args) {\n try {\n URL url = new URL(args[0]);\n HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();\n httpCon.setDoOutput(true);\n httpCon.setRequestMethod(\"PUT\");\n OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());\n out.write(\"fatal error\");\n out.close();\n System.out.println(\"end\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public boolean resourceExists(String location) {\n if ((location == null) || (location.length() == 0)) {\n return false;\n }\n try {\n URL url = buildURL(location);\n URLConnection cxn = url.openConnection();\n InputStream is = null;\n try {\n byte[] byteBuffer = new byte[2048];\n is = cxn.getInputStream();\n while (is.read(byteBuffer, 0, 2048) >= 0) ;\n return true;\n } finally {\n if (is != null) {\n is.close();\n }\n }\n } catch (IOException ex) {\n return false;\n }\n }\n", "func2": " public static String doCrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"SHA-1\");\n byte[] sha1hash = new byte[40];\n md.update(text.getBytes(\"UTF-8\"), 0, text.length());\n sha1hash = md.digest();\n return convertToHex(sha1hash);\n }\n", "label": 0} {"func1": " public Object getContent(ContentProducerContext context, String ctxAttrName, Object ctxAttrValue) {\n try {\n URL url = (getURL() != null) ? new URL(getURL().toExternalForm()) : new URL(((URL) ctxAttrValue).toExternalForm());\n InputStream reader = url.openStream();\n int available = reader.available();\n byte contents[] = new byte[available];\n reader.read(contents, 0, available);\n reader.close();\n return new String(contents);\n } catch (Exception ex) {\n ex.printStackTrace();\n return ex.toString();\n }\n }\n", "func2": " private static void copyFile(String src, String target) throws IOException {\n FileChannel ic = new FileInputStream(src).getChannel();\n FileChannel oc = new FileOutputStream(target).getChannel();\n ic.transferTo(0, ic.size(), oc);\n ic.close();\n oc.close();\n }\n", "label": 0} {"func1": " private void CopyTo(File dest) throws IOException {\n FileReader in = null;\n FileWriter out = null;\n int c;\n try {\n in = new FileReader(image);\n out = new FileWriter(dest);\n while ((c = in.read()) != -1) out.write(c);\n } finally {\n if (in != null) try {\n in.close();\n } catch (Exception e) {\n }\n if (out != null) try {\n out.close();\n } catch (Exception e) {\n }\n }\n }\n", "func2": " private static String encodeMd5(String key) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(key.getBytes());\n byte[] bytes = md.digest();\n String result = toHexString(bytes);\n return result;\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n", "label": 0} {"func1": " public static void unzip(File file, ZipFile zipFile, File targetDirectory) throws BusinessException {\n LOG.info(\"Unzipping zip file '\" + file.getAbsolutePath() + \"' to directory '\" + targetDirectory.getAbsolutePath() + \"'.\");\n assert (file.exists() && file.isFile());\n if (targetDirectory.exists() == false) {\n LOG.debug(\"Creating target directory.\");\n if (targetDirectory.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + targetDirectory.getAbsolutePath() + \"'!\");\n }\n }\n ZipInputStream zipin = null;\n try {\n zipin = new ZipInputStream(new FileInputStream(file));\n ZipEntry entry = null;\n while ((entry = zipin.getNextEntry()) != null) {\n LOG.debug(\"Unzipping entry '\" + entry.getName() + \"'.\");\n if (entry.isDirectory()) {\n LOG.debug(\"Skipping directory.\");\n continue;\n }\n final File targetFile = new File(targetDirectory, entry.getName());\n final File parentTargetFile = targetFile.getParentFile();\n if (parentTargetFile.exists() == false) {\n LOG.debug(\"Creating directory '\" + parentTargetFile.getAbsolutePath() + \"'.\");\n if (parentTargetFile.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + parentTargetFile.getAbsolutePath() + \"'!\");\n }\n }\n InputStream input = null;\n FileOutputStream output = null;\n try {\n input = zipFile.getInputStream(entry);\n if (targetFile.createNewFile() == false) {\n throw new BusinessException(\"Could not create target file '\" + targetFile.getAbsolutePath() + \"'!\");\n }\n output = new FileOutputStream(targetFile);\n int readBytes = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n while ((readBytes = input.read(buffer, 0, buffer.length)) > 0) {\n output.write(buffer, 0, readBytes);\n }\n } finally {\n FileUtil.closeCloseable(input);\n FileUtil.closeCloseable(output);\n }\n }\n } catch (IOException e) {\n throw new BusinessException(\"Could not unzip file '\" + file.getAbsolutePath() + \"'!\", e);\n } finally {\n FileUtil.closeCloseable(zipin);\n }\n }\n", "func2": "\tpublic static void Sample1(String myField, String condition1, String condition2) throws SQLException {\n\t\tConnection connection = DriverManager.getConnection(\"jdbc:postgresql://localhost/test\", \"user\", \"password\");\n\t\tconnection.setAutoCommit(false);\n\t\t\n\t\tPreparedStatement ps = connection.prepareStatement(\"UPDATE myTable SET myField = ? WHERE myOtherField1 = ? AND myOtherField2 = ?\");\n\t\tps.setString(1, myField);\n\t\tps.setString(2, condition1);\n\t\tps.setString(3, condition2);\n\t\t\n\t\t// If more than 10 entries change, panic and rollback\n\t\tint numChanged = ps.executeUpdate();\n\t\tif(numChanged > 10) {\n\t\t\tconnection.rollback();\n\t\t} else {\n\t\t\tconnection.commit();\n\t\t}\n\t\t\n\t\tps.close();\n\t\tconnection.close();\n\t}\n", "label": 0} {"func1": " public void writeData(String name, int items, int mzmin, int mzmax, long tstart, long tdelta, int[] peaks) {\n PrintWriter file = getWriter(name + \".txt\");\n file.print(\"Filename\\t\");\n file.print(\"Date\\t\");\n file.print(\"Acquisition #\\t\");\n file.print(\"�m Diameter\\t\");\n for (int i = mzmin; i <= mzmax; i++) file.print(i + \"\\t\");\n file.println();\n int nothing = 0;\n String fileLoc = \"C:/abcd/\" + name + \".txt\\t\";\n Date tempDate;\n for (int i = 0; i < items; i++) {\n tempDate = new Date(tstart);\n tstart += tdelta;\n file.print(fileLoc);\n file.print(dateFormat.format(tempDate) + \"\\t\");\n file.print(i + 1 + \"\\t\");\n double t = (double) (i) / 10;\n file.print(t + \"\\t\");\n boolean peaked = false;\n for (int k = mzmin; k <= mzmax; k++) {\n for (int j = 0; j < peaks.length && !peaked; j++) {\n if (k == peaks[j]) {\n file.print(peakVals[j % peakVals.length] + \"\\t\");\n peaked = true;\n }\n }\n if (!peaked) {\n if (k == mzmax) file.print(nothing); else file.print(nothing + \"\\t\");\n }\n peaked = false;\n }\n file.println();\n }\n try {\n Scanner test = new Scanner(f);\n while (test.hasNext()) {\n System.out.println(test.nextLine());\n }\n System.out.println(\"test\");\n } catch (Exception e) {\n }\n file.close();\n }\n", "func2": " public String encrypt(String password) throws Exception {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(password.getBytes());\n BigInteger hash = new BigInteger(1, md5.digest());\n String hashword = hash.toString(16);\n return hashword;\n }\n", "label": 0} {"func1": " public static MessageService getMessageService(String fileId) {\n MessageService ms = null;\n if (serviceCache == null) init();\n if (serviceCache.containsKey(fileId)) return serviceCache.get(fileId);\n Properties p = new Properties();\n try {\n URL url = I18nPlugin.getFileURL(fileId);\n p.load(url.openStream());\n ms = new MessageService(p);\n } catch (Exception e) {\n ms = new MessageService();\n }\n serviceCache.put(fileId, ms);\n return ms;\n }\n", "func2": " private void startScript(wabclient.Attributes prop) throws SAXException {\n dialog.beginScript();\n String url = prop.getValue(\"src\");\n if (url.length() > 0) {\n try {\n BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream()));\n String buffer;\n while (true) {\n buffer = r.readLine();\n if (buffer == null) break;\n dialog.script += buffer + \"\\n\";\n }\n r.close();\n dialog.endScript();\n } catch (IOException ioe) {\n System.err.println(\"[IOError] \" + ioe.getMessage());\n System.exit(0);\n }\n }\n }\n", "label": 0} {"func1": " public static void copyFile(File source, File destination) throws IOException {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(source).getChannel();\n out = new FileOutputStream(destination).getChannel();\n in.transferTo(0, in.size(), out);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "func2": " public static void main(String[] args) {\n FTPClient client = new FTPClient();\n String sFTP = \"ftp.miservidor.com\";\n String sUser = \"usuario\";\n String sPassword = \"password\";\n try {\n System.out.println(\"Conectandose a \" + sFTP);\n client.connect(sFTP);\n boolean login = client.login(sUser, sPassword);\n if (login) {\n System.out.println(\"Login correcto\");\n boolean logout = client.logout();\n if (logout) {\n System.out.println(\"Logout del servidor FTP\");\n }\n } else {\n System.out.println(\"Error en el login.\");\n }\n System.out.println(\"Desconectando.\");\n client.disconnect();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public boolean clonarFichero(FileInputStream rutaFicheroOrigen, String rutaFicheroDestino) {\n System.out.println(\"\");\n boolean estado = false;\n try {\n FileOutputStream salida = new FileOutputStream(rutaFicheroDestino);\n FileChannel canalOrigen = rutaFicheroOrigen.getChannel();\n FileChannel canalDestino = salida.getChannel();\n canalOrigen.transferTo(0, canalOrigen.size(), canalDestino);\n rutaFicheroOrigen.close();\n salida.close();\n estado = true;\n } catch (IOException e) {\n System.out.println(\"No se encontro el archivo\");\n e.printStackTrace();\n estado = false;\n }\n return estado;\n }\n", "func2": " public FTPFile[] connect() {\n if (ftpe == null) {\n ftpe = new FTPEvent(this);\n }\n if (ftp == null) {\n ftp = new FTPClient();\n } else if (ftp.isConnected()) {\n path = \"\";\n try {\n ftp.disconnect();\n } catch (IOException e1) {\n log.error(\"could not disconnect -\" + e1.getMessage());\n }\n }\n currentDir = new FTPFile[0];\n log.debug(\"try to connect\");\n try {\n int reply;\n ftp.connect(ftpsite);\n reply = ftp.getReplyCode();\n if (!FTPReply.isPositiveCompletion(reply)) {\n ftp.disconnect();\n log.error(\"FTP server refused connection.\");\n }\n } catch (IOException e) {\n log.error(\"FTPConnection error: \" + e.getMessage());\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException f) {\n }\n }\n }\n try {\n if (!ftp.login(user, password)) {\n log.error(\"could not login with: \" + user);\n ftp.logout();\n }\n log.debug(\"Remote system is \" + ftp.getSystemName());\n ftp.enterLocalPassiveMode();\n currentDir = ftp.listFiles();\n } catch (FTPConnectionClosedException e) {\n log.error(\"FTPConnectionClosedException: \" + e.getMessage());\n } catch (IOException e) {\n log.error(\"IOException: \" + e.getMessage());\n }\n ftpe.setType(FTPEvent.CONNECT);\n fireFTPEvent(ftpe);\n return currentDir;\n }\n", "label": 0} {"func1": " @Override\n public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {\n if (query == null) {\n throw new NotConnectedException();\n }\n ArrayList recipients = query.getUserManager().getTecMail();\n Mail mail = new Mail(recipients);\n try {\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(\"log/ossobooklog.zip\"));\n FileInputStream fis = new FileInputStream(\"log/ossobook.log\");\n ZipEntry entry = new ZipEntry(\"ossobook.log\");\n zos.putNextEntry(entry);\n byte[] buffer = new byte[8192];\n int read = 0;\n while ((read = fis.read(buffer, 0, 1024)) != -1) {\n zos.write(buffer, 0, read);\n }\n zos.closeEntry();\n fis.close();\n zos.close();\n mail.sendErrorMessage(message, new File(\"log/ossobooklog.zip\"), getUserName());\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "func2": " private void Submit2URL(URL url) throws Exception {\n HttpURLConnection urlc = null;\n try {\n urlc = (HttpURLConnection) url.openConnection();\n urlc.setRequestMethod(\"GET\");\n urlc.setDoOutput(true);\n urlc.setDoInput(true);\n urlc.setUseCaches(false);\n urlc.setAllowUserInteraction(false);\n if (urlc.getResponseCode() != 200) {\n InputStream in = null;\n Reader reader = null;\n try {\n in = urlc.getInputStream();\n reader = new InputStreamReader(in, \"UTF-8\");\n int read = 0;\n char[] buf = new char[1024];\n String error = null;\n while ((read = reader.read(buf)) >= 0) {\n if (error == null) error = new String(buf, 0, read); else error += new String(buf, 0, read);\n }\n throw new NpsException(error, ErrorHelper.SYS_UNKOWN);\n } finally {\n if (reader != null) try {\n reader.close();\n } catch (Exception e1) {\n }\n if (in != null) try {\n in.close();\n } catch (Exception e1) {\n }\n }\n }\n } finally {\n if (urlc != null) try {\n urlc.disconnect();\n } catch (Exception e1) {\n }\n }\n }\n", "label": 0} {"func1": " private static InputStream openNamedResource(String name) throws java.io.IOException {\n InputStream in = null;\n boolean result = false;\n boolean httpURL = true;\n URL propsURL = null;\n try {\n propsURL = new URL(name);\n } catch (MalformedURLException ex) {\n httpURL = false;\n propsURL = null;\n }\n if (propsURL == null) {\n propsURL = UserProperties.class.getResource(name);\n }\n if (propsURL != null) {\n URLConnection urlConn = propsURL.openConnection();\n if (httpURL) {\n String hdrVal = urlConn.getHeaderField(0);\n if (hdrVal != null) {\n String code = HTTPUtilities.getResultCode(hdrVal);\n if (code != null) {\n if (!code.equals(\"200\")) {\n throw new java.io.IOException(\"status code = \" + code);\n }\n }\n }\n }\n in = urlConn.getInputStream();\n }\n return in;\n }\n", "func2": " public static void save(String packageName, ArrayList fileContents, ArrayList fileNames) throws Exception {\n String dirBase = Util.JAVA_DIR + File.separator + packageName;\n File packageDir = new File(dirBase);\n if (!packageDir.exists()) {\n boolean created = packageDir.mkdir();\n if (!created) {\n File currentPath = new File(\".\");\n throw new Exception(\"Directory \" + packageName + \" could not be created. Current directory: \" + currentPath.getAbsolutePath());\n }\n }\n for (int i = 0; i < fileContents.size(); i++) {\n File file = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(fileContents.get(i));\n fos.flush();\n fos.close();\n }\n for (int i = 0; i < fileNames.size(); i++) {\n File fileSrc = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n File fileDst = new File(dirBase + File.separator + fileNames.get(i));\n BufferedReader reader = new BufferedReader(new FileReader(fileSrc));\n BufferedWriter writer = new BufferedWriter(new FileWriter(fileDst));\n writer.append(\"package \" + packageName + \";\\n\");\n String line = \"\";\n while ((line = reader.readLine()) != null) writer.append(line + \"\\n\");\n writer.flush();\n writer.close();\n reader.close();\n }\n }\n", "label": 0} {"func1": " @Override\n protected String doInBackground(String... params) {\n try {\n final HttpParams param = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(param, 30000);\n HttpConnectionParams.setSoTimeout(param, 30000);\n DefaultHttpClient client = new DefaultHttpClient(param);\n HttpPost post = new HttpPost(\"http://www.google.com/loc/json\");\n post.setEntity(new StringEntity(params[0]));\n if (DEBUG) Log.d(\"Location\", params[0]);\n HttpResponse resp = client.execute(post);\n if (resp.getStatusLine().getStatusCode() == 200) {\n HttpEntity entity = resp.getEntity();\n String result = EntityUtils.toString(entity);\n return result;\n } else {\n if (isFirstLocation) {\n requestGearsLocation(1);\n isFirstLocation = false;\n return RESULT_FIRST_FAILE;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " public static String getSHADigest(String password) {\n String digest = null;\n MessageDigest sha = null;\n try {\n sha = MessageDigest.getInstance(\"SHA-1\");\n sha.reset();\n sha.update(password.getBytes());\n byte[] pwhash = sha.digest();\n digest = \"{SHA}\" + new String(Base64.encode(pwhash));\n } catch (NoSuchAlgorithmException nsae) {\n CofaxToolsUtil.log(\"Algorithme SHA-1 non supporte a la creation du hashage\" + nsae + id);\n }\n return digest;\n }\n", "label": 0} {"func1": " public static void init(Locale lng) {\n try {\n Locale toLoad = lng != null ? lng : DEFAULT_LOCALE;\n URL url = ClassLoader.getSystemResource(\"locales/\" + toLoad.getISO3Language() + \".properties\");\n if (url == null) {\n url = ClassLoader.getSystemResource(\"locales/\" + DEFAULT_LOCALE.getISO3Language() + \".properties\");\n }\n PROPS.clear();\n PROPS.load(url.openStream());\n } catch (IOException ioe) {\n try {\n URL url = ClassLoader.getSystemResource(\"locales/\" + DEFAULT_LOCALE.getISO3Language() + \".properties\");\n PROPS.clear();\n PROPS.load(url.openStream());\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(99);\n }\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(99);\n }\n }\n", "func2": " private String cookieString(String url, String ip) {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"SHA-1\");\n md.update((url + \"&&\" + ip + \"&&\" + salt.toString()).getBytes());\n java.math.BigInteger hash = new java.math.BigInteger(1, md.digest());\n return hash.toString(16);\n } catch (NoSuchAlgorithmException e) {\n filterConfig.getServletContext().log(this.getClass().getName() + \" error \" + e);\n return null;\n }\n }\n", "label": 0} {"func1": " public String readRemoteFile() throws IOException {\n String response = \"\";\n boolean eof = false;\n URL url = new URL(StaticData.remoteFile);\n InputStream is = url.openStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\n String s;\n s = br.readLine();\n response = s;\n while (!eof) {\n try {\n s = br.readLine();\n if (s == null) {\n eof = true;\n br.close();\n } else response += s;\n } catch (EOFException eo) {\n eof = true;\n } catch (IOException e) {\n System.out.println(\"IO Error : \" + e.getMessage());\n }\n }\n return response;\n }\n", "func2": " protected JSONObject doJSONRequest(JSONObject jsonRequest) throws JSONRPCException {\n HttpPost request = new HttpPost(serviceUri);\n HttpParams params = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());\n HttpConnectionParams.setSoTimeout(params, getSoTimeout());\n HttpProtocolParams.setVersion(params, PROTOCOL_VERSION);\n request.setParams(params);\n request.addHeader(\"Authorization\", \"Basic \" + Base64Coder.encodeString(serviceUser + \":\" + servicePass));\n HttpEntity entity;\n try {\n entity = new JSONEntity(jsonRequest);\n } catch (UnsupportedEncodingException e1) {\n throw new JSONRPCException(\"Unsupported encoding\", e1);\n }\n request.setEntity(entity);\n try {\n long t = System.currentTimeMillis();\n HttpResponse response = httpClient.execute(request);\n t = System.currentTimeMillis() - t;\n Log.d(\"json-rpc\", \"Request time :\" + t);\n String responseString = EntityUtils.toString(response.getEntity());\n responseString = responseString.trim();\n JSONObject jsonResponse = new JSONObject(responseString);\n if (jsonResponse.has(\"error\")) {\n Object jsonError = jsonResponse.get(\"error\");\n if (!jsonError.equals(null)) throw new JSONRPCException(jsonResponse.get(\"error\"));\n return jsonResponse;\n } else {\n return jsonResponse;\n }\n } catch (ClientProtocolException e) {\n throw new JSONRPCException(\"HTTP error\", e);\n } catch (IOException e) {\n throw new JSONRPCException(\"IO error\", e);\n } catch (JSONException e) {\n throw new JSONRPCException(\"Invalid JSON response\", e);\n }\n }\n", "label": 0} {"func1": " public void createFile(File src, String filename) throws IOException {\n try {\n FileInputStream fis = new FileInputStream(src);\n OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);\n IOUtils.copy(fis, fos);\n fos.close();\n fis.close();\n } catch (ResourceManagerException e) {\n LOGGER.error(e);\n }\n }\n", "func2": " private boolean authenticate(Module module) throws Exception {\n SecureRandom rand = SecureRandom.getInstance(\"SHA1PRNG\");\n rand.setSeed(System.currentTimeMillis());\n byte[] challenge = new byte[16];\n rand.nextBytes(challenge);\n String b64 = Util.base64(challenge);\n Util.writeASCII(out, RSYNCD_AUTHREQD + b64 + \"\\n\");\n String reply = Util.readLine(in);\n if (reply.indexOf(\" \") < 0) {\n Util.writeASCII(out, AT_ERROR + \": bad response\\n\");\n if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + \"\\n\");\n socket.close();\n throw new IOException(\"bad response\");\n }\n String user = reply.substring(0, reply.indexOf(\" \"));\n String response = reply.substring(reply.indexOf(\" \") + 1);\n if (!module.users.contains(user)) {\n Util.writeASCII(out, AT_ERROR + \": user \" + user + \" not allowed\\n\");\n if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + \"\\n\");\n socket.close();\n throw new IOException(\"user \" + user + \" not allowed\");\n }\n LineNumberReader secrets = new LineNumberReader(new FileReader(module.secretsFile));\n MessageDigest md4 = MessageDigest.getInstance(\"BrokenMD4\");\n String line;\n while ((line = secrets.readLine()) != null) {\n if (line.startsWith(user + \":\")) {\n String passwd = line.substring(line.lastIndexOf(\":\") + 1);\n md4.update(new byte[4]);\n md4.update(passwd.getBytes(\"US-ASCII\"));\n md4.update(b64.getBytes(\"US-ASCII\"));\n String hash = Util.base64(md4.digest());\n if (hash.equals(response)) {\n secrets.close();\n return true;\n } else {\n Util.writeASCII(out, AT_ERROR + \": auth failed on module \" + module.name + \"\\n\");\n if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + \"\\n\");\n socket.close();\n secrets.close();\n logger.error(\"auth failed on module \" + module.name);\n return false;\n }\n }\n }\n Util.writeASCII(out, AT_ERROR + \": auth failed on module \" + module.name + \"\\n\");\n if (remoteVersion < 25) Util.writeASCII(out, RSYNCD_EXIT + \"\\n\");\n socket.close();\n secrets.close();\n logger.error(\"auth failed on module \" + module.name);\n return false;\n }\n", "label": 0} {"func1": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "func2": " public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "label": 0} {"func1": " public static synchronized Document readRemoteDocument(URL url, boolean validate) throws IOException, SAXParseException {\n if (DEBUG) System.out.println(\"DocumentUtilities.readDocument( \" + url + \")\");\n Document document = null;\n try {\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setNamespaceAware(true);\n factory.setCoalescing(true);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setDefaultUseCaches(false);\n connection.setUseCaches(false);\n connection.setRequestProperty(\"User-Agent\", \"eXchaNGeR/\" + System.getProperty(\"xngr.version\") + \" (http://xngr.org/)\");\n connection.connect();\n InputStream stream = connection.getInputStream();\n document = factory.newDocumentBuilder().parse(stream);\n stream.close();\n connection.disconnect();\n } catch (SAXException e) {\n if (e instanceof SAXParseException) {\n throw (SAXParseException) e;\n }\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n }\n if (DEBUG) System.out.println(\"DocumentUtilities.readDocument( \" + url + \") [\" + document + \"]\");\n return document;\n }\n", "func2": " public void genDropSchema(DiagramModel diagramModel, boolean foreignKeys) {\n try {\n con.setAutoCommit(false);\n stmt = con.createStatement();\n Collection boxes = diagramModel.getBoxes();\n BoxModel box;\n String sqlQuery;\n if (foreignKeys) {\n for (Iterator x = boxes.iterator(); x.hasNext(); ) {\n box = (BoxModel) x.next();\n if (!box.isAbstractDef()) {\n dropForeignKeys(box);\n }\n }\n }\n int counter = 0;\n for (Iterator x = boxes.iterator(); x.hasNext(); ) {\n box = (BoxModel) x.next();\n if (!box.isAbstractDef()) {\n sqlQuery = sqlDropTable(box);\n System.out.println(sqlQuery);\n try {\n stmt.executeUpdate(sqlQuery);\n counter++;\n } catch (SQLException e) {\n String tableName = box.getName();\n System.out.println(\"// Problem while dropping table \" + tableName + \" : \" + e.getMessage());\n String msg = Para.getPara().getText(\"tableNotDropped\") + \" -- \" + tableName;\n this.informUser(msg);\n }\n }\n }\n con.commit();\n if (counter > 0) {\n String msg = Para.getPara().getText(\"schemaDropped\") + \" -- \" + counter + \" \" + Para.getPara().getText(\"tables\");\n this.informUser(msg);\n } else {\n this.informUser(Para.getPara().getText(\"schemaNotDropped\"));\n }\n } catch (SQLException e) {\n System.out.println(e.getMessage() + \" // Problem with the JDBC schema generation! \");\n try {\n con.rollback();\n this.informUser(Para.getPara().getText(\"schemaNotDropped\"));\n } catch (SQLException e1) {\n System.out.println(e1.getMessage() + \" // Problem with the connection rollback! \");\n }\n } finally {\n try {\n con.setAutoCommit(true);\n stmt.close();\n } catch (SQLException e1) {\n System.out.println(e1.getMessage() + \" // Problem with the connection disconnect! \");\n }\n }\n }\n", "label": 0} {"func1": " public static void main(String[] args) {\n File srcDir = new File(args[0]);\n File dstDir = new File(args[1]);\n File[] srcFiles = srcDir.listFiles();\n for (File f : srcFiles) {\n if (f.isDirectory()) continue;\n try {\n FileChannel srcChannel = new FileInputStream(f).getChannel();\n FileChannel dstChannel = new FileOutputStream(dstDir.getAbsolutePath() + System.getProperty(\"file.separator\") + f.getName()).getChannel();\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n int nr = 0;\n srcChannel.position(nr);\n nr += srcChannel.read(buffer);\n while (nr < f.length()) {\n buffer.flip();\n dstChannel.write(buffer);\n buffer.clear();\n nr += srcChannel.read(buffer);\n }\n srcChannel.close();\n dstChannel.close();\n } catch (IOException e) {\n }\n }\n }\n", "func2": " public void testPreparedStatement0009() throws Exception {\n Statement stmt = con.createStatement();\n stmt.executeUpdate(\"create table #t0009 \" + \" (i integer not null, \" + \" s char(10) not null) \");\n con.setAutoCommit(false);\n PreparedStatement pstmt = con.prepareStatement(\"insert into #t0009 values (?, ?)\");\n int rowsToAdd = 8;\n final String theString = \"abcdefghijklmnopqrstuvwxyz\";\n int count = 0;\n for (int i = 1; i <= rowsToAdd; i++) {\n pstmt.setInt(1, i);\n pstmt.setString(2, theString.substring(0, i));\n count += pstmt.executeUpdate();\n }\n pstmt.close();\n assertEquals(count, rowsToAdd);\n con.rollback();\n ResultSet rs = stmt.executeQuery(\"select s, i from #t0009\");\n assertNotNull(rs);\n count = 0;\n while (rs.next()) {\n count++;\n assertEquals(rs.getString(1).trim().length(), rs.getInt(2));\n }\n assertEquals(count, 0);\n con.commit();\n pstmt = con.prepareStatement(\"insert into #t0009 values (?, ?)\");\n rowsToAdd = 6;\n count = 0;\n for (int i = 1; i <= rowsToAdd; i++) {\n pstmt.setInt(1, i);\n pstmt.setString(2, theString.substring(0, i));\n count += pstmt.executeUpdate();\n }\n assertEquals(count, rowsToAdd);\n con.commit();\n pstmt.close();\n rs = stmt.executeQuery(\"select s, i from #t0009\");\n count = 0;\n while (rs.next()) {\n count++;\n assertEquals(rs.getString(1).trim().length(), rs.getInt(2));\n }\n assertEquals(count, rowsToAdd);\n con.commit();\n stmt.close();\n con.setAutoCommit(true);\n }\n", "label": 0} {"func1": " protected void doSetInput(IEditorInput input, IProgressMonitor monitor) throws CoreException {\n IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();\n IFileFormat format = null;\n Object source = null;\n InputStream in = null;\n try {\n IPath path;\n if (input instanceof IStorageEditorInput) {\n IStorage s = ((IStorageEditorInput) input).getStorage();\n in = s.getContents();\n if (s instanceof IFile) {\n IFile file = (IFile) s;\n path = file.getRawLocation();\n if (root.exists(path)) {\n path = root.getLocation().append(path);\n }\n source = path.toFile();\n }\n } else if (input instanceof IPathEditorInput) {\n path = ((IPathEditorInput) input).getPath();\n source = path.toFile();\n } else if (input instanceof IURIEditorInput) {\n URI uri = ((IURIEditorInput) input).getURI();\n if (URIUtil.isFileURI(uri)) {\n source = URIUtil.toFile(uri);\n } else {\n URL url = URIUtil.toURL(uri);\n in = url.openStream();\n }\n }\n if (source == null) {\n if (!in.markSupported()) {\n in = new BufferedInputStream(in);\n }\n in.mark(10);\n source = in;\n }\n IContentDescription cd = Platform.getContentTypeManager().getDescriptionFor(in, input.getName(), new QualifiedName[] { ImageCore.VALID_FORMATS });\n if (in != null) {\n in.reset();\n }\n Collection valid = (Collection) cd.getProperty(ImageCore.VALID_FORMATS);\n if (valid.isEmpty()) throw new CoreException(new Status(Status.ERROR, ImageUI.PLUGIN_ID, \"Unsupported file format.\"));\n ImageInputStream stream = ImageIO.createImageInputStream(source);\n format = (IFileFormat) valid.iterator().next();\n IDocument document = format.decode(stream, monitor);\n setDocument(document);\n } catch (IOException e) {\n Status status = new Status(Status.ERROR, ImageUI.PLUGIN_ID, \"IO Error\", e);\n throw new CoreException(status);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n }\n }\n }\n super.setInput(input);\n }\n", "func2": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "label": 0} {"func1": " private static long copy(InputStream source, OutputStream sink) {\n try {\n return IOUtils.copyLarge(source, sink);\n } catch (IOException e) {\n logger.error(e.toString(), e);\n throw new FaultException(\"System error copying stream\", e);\n } finally {\n IOUtils.closeQuietly(source);\n IOUtils.closeQuietly(sink);\n }\n }\n", "func2": " @Override\n public void run() {\n try {\n BufferedReader in = new BufferedReader(new InputStreamReader(new URL(urlInfo).openStream()));\n String ligneEnCours;\n int i = 0;\n informations = \"\";\n while ((ligneEnCours = in.readLine()) != null) {\n switch(i) {\n case 0:\n version = ligneEnCours;\n break;\n case 1:\n url = ligneEnCours;\n break;\n default:\n informations += ligneEnCours + '\\n';\n break;\n }\n i++;\n }\n in.close();\n erreur = false;\n } catch (IOException e) {\n erreur = true;\n texteErreur = e.getMessage();\n if (texteErreur.equals(\"Network is unreachable\")) {\n texteErreur = \"Pas de réseau\";\n numErreur = 1;\n }\n if (e instanceof FileNotFoundException) {\n texteErreur = \"Problème paramétrage\";\n numErreur = 2;\n }\n e.printStackTrace();\n } finally {\n for (ActionListener al : listeners) {\n al.actionPerformed(null);\n }\n }\n }\n", "label": 0} {"func1": " public String getServerHash(String passwordHash, String PasswordSalt) throws PasswordHashingException {\n byte[] hash;\n try {\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.reset();\n digest.update(PasswordSalt.getBytes(\"UTF-16\"));\n hash = digest.digest(passwordHash.getBytes(\"UTF-16\"));\n return bytesToHex(hash);\n } catch (NoSuchAlgorithmException ex) {\n throw new PasswordHashingException(\"Current environment does not supply needed security algorithms. Please update Java\");\n } catch (UnsupportedEncodingException ex) {\n throw new PasswordHashingException(\"Current environment does not supply needed character encoding. Please update Java\");\n }\n }\n", "func2": " public HttpResponseExchange execute() throws Exception {\n HttpResponseExchange forwardResponse = null;\n int fetchSizeLimit = Config.getInstance().getFetchLimitSize();\n while (null != lastContentRange) {\n forwardRequest.setBody(new byte[0]);\n ContentRangeHeaderValue old = lastContentRange;\n long sendSize = fetchSizeLimit;\n if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {\n sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);\n }\n if (sendSize <= 0) {\n break;\n }\n lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));\n forwardResponse = syncFetch(forwardRequest);\n if (sendSize < fetchSizeLimit) {\n lastContentRange = null;\n }\n }\n return forwardResponse;\n }\n", "label": 0} {"func1": " public static String getMD5(String source) {\n String s = null;\n char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n try {\n java.security.MessageDigest md = java.security.MessageDigest.getInstance(\"MD5\");\n md.update(source.getBytes());\n byte tmp[] = md.digest();\n char str[] = new char[16 * 2];\n int k = 0;\n for (int i = 0; i < 16; i++) {\n byte byte0 = tmp[i];\n str[k++] = hexDigits[byte0 >>> 4 & 0xf];\n str[k++] = hexDigits[byte0 & 0xf];\n }\n s = new String(str);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return s;\n }\n", "func2": " private boolean getWave(String url, String Word) {\n try {\n File FF = new File(f.getParent() + \"/\" + f.getName() + \"pron\");\n FF.mkdir();\n URL url2 = new URL(url);\n BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));\n File Fdel = new File(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n if (!Fdel.exists()) {\n FileOutputStream outstream = new FileOutputStream(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));\n char[] binput = new char[1024];\n int len = stream.read(binput, 0, 1024);\n while (len > 0) {\n bwriter.write(binput, 0, len);\n len = stream.read(binput, 0, 1024);\n }\n bwriter.close();\n outstream.close();\n }\n stream.close();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " public static void copyFile(File src, File dst) throws IOException {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[1024];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n }\n", "func2": " public static void insertDocumentToURL(String file, String target) throws IOException {\n InputStream is = null;\n OutputStream os = null;\n try {\n is = new FileInputStream(file);\n final URL url = new URL(target);\n final URLConnection connection = url.openConnection();\n os = connection.getOutputStream();\n TestTools.copyStream(is, os);\n } finally {\n if (is != null) {\n is.close();\n }\n if (os != null) {\n os.close();\n }\n }\n }\n", "label": 0} {"func1": " public Document index() throws CrawlingException {\n log.debug(\"BEGINIG indexing page [code=\" + getCode() + \"] ...\");\n URL url = null;\n InputStream in = null;\n String contentType = null;\n try {\n url = new URL(getServer().getProtocol() + \"://\" + getServer().getHost() + \":\" + getServer().getPort() + getPath());\n HttpURLConnection pageContent = (HttpURLConnection) url.openConnection();\n if (pageContent.getResponseCode() != HttpURLConnection.HTTP_OK) {\n log.debug(\"page pk[\" + getCode() + \",\" + url.toExternalForm() + \"] is invalid\");\n return null;\n }\n String redireccion = pageContent.getHeaderField(\"location\");\n if (redireccion != null) {\n log.debug(\"Page \" + url.toExternalForm() + \" redirected to \" + redireccion);\n recordLink(redireccion);\n return null;\n }\n contentType = pageContent.getContentType();\n in = new BufferedInputStream(pageContent.getInputStream(), 32768);\n } catch (MalformedURLException e) {\n log.error(\"Invalid page address\", e);\n } catch (ConnectException e) {\n if (getServer() != null) {\n log.error(\"Unable to connect to page: \" + getServer().getProtocol() + \"://\" + getServer().getHost() + \":\" + getServer().getPort() + getPath(), e);\n }\n } catch (UnknownHostException uhe) {\n log.warn(\"Unknow host indexing page \" + getURL(), uhe);\n } catch (IOException e) {\n log.warn(\"Unable to index page \" + getURL(), e);\n }\n Document doc = generateDocument(contentType, in);\n log.debug(\"END indexing page [code=\" + getCode() + \"]\");\n return doc;\n }\n", "func2": " public void run(String[] args) throws Throwable {\n FileInputStream input = new FileInputStream(args[0]);\n FileOutputStream output = new FileOutputStream(args[0] + \".out\");\n Reader reader = $(Reader.class, $declass(input));\n Writer writer = $(Writer.class, $declass(output));\n Pump pump;\n if (args.length > 1 && \"diag\".equals(args[1])) {\n pump = $(new Reader() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public int read(byte[] buffer, int off, int len) throws Exception {\n Integer rd = (Integer) $next();\n if (rd > 0) {\n counter += rd;\n }\n return 0;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Read from input \" + counter + \" bytes.\");\n }\n }, reader, writer, new Writer() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void write(byte[] buffer, int off, int len) throws Exception {\n counter += len;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Written to output \" + counter + \" bytes.\");\n }\n });\n } else {\n pump = $(reader, writer);\n }\n pump.pump();\n }\n", "label": 0} {"func1": " private VelocityEngine newVelocityEngine() {\n VelocityEngine velocityEngine = null;\n InputStream is = null;\n try {\n URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);\n is = url.openStream();\n Properties props = new Properties();\n props.load(is);\n velocityEngine = new VelocityEngine(props);\n velocityEngine.init();\n } catch (Exception e) {\n throw new RuntimeException(\"can not find velocity props file, file=\" + VELOCITY_PROPS_FILE, e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return velocityEngine;\n }\n", "func2": " private static void copyFiles(String strPath, String dstPath) throws Exception {\n File src = new File(strPath);\n File dest = new File(dstPath);\n if (src.isDirectory()) {\n dest.mkdirs();\n String list[] = src.list();\n for (int i = 0; i < list.length; i++) {\n String dest1 = dest.getAbsolutePath() + \"\\\\\" + list[i];\n String src1 = src.getAbsolutePath() + \"\\\\\" + list[i];\n copyFiles(src1, dest1);\n }\n } else {\n FileChannel sourceChannel = new FileInputStream(src).getChannel();\n FileChannel targetChannel = new FileOutputStream(dest).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);\n sourceChannel.close();\n targetChannel.close();\n }\n }\n", "label": 0} {"func1": " public void actionPerformed(ActionEvent e) {\n if (\"register\".equals(e.getActionCommand())) {\n buttonClicked = \"register\";\n try {\n String data = URLEncoder.encode(\"ver\", \"UTF-8\") + \"=\" + URLEncoder.encode(Double.toString(questVer), \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"name\", \"UTF-8\") + \"=\" + URLEncoder.encode(name.getText(), \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"os\", \"UTF-8\") + \"=\" + URLEncoder.encode(os.getText(), \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"jre\", \"UTF-8\") + \"=\" + URLEncoder.encode(jre.getText(), \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"email\", \"UTF-8\") + \"=\" + URLEncoder.encode(email.getText(), \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"key\", \"UTF-8\") + \"=\" + URLEncoder.encode(\"Qr7SchF\", \"UTF-8\");\n data += \"&\" + URLEncoder.encode(\"answers\", \"UTF-8\") + \"=\" + URLEncoder.encode(Integer.toString(getAnswers()), \"UTF-8\");\n URL url = new URL(\"http://ubcdcreator.sourceforge.net/register.php\");\n URLConnection conn = url.openConnection();\n conn.setDoInput(true);\n conn.setDoOutput(true);\n OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\n wr.write(data);\n wr.flush();\n BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n String line;\n while ((line = rd.readLine()) != null) {\n }\n rd.close();\n wr.close();\n } catch (Exception ex) {\n }\n setVisible(false);\n } else if (\"cancel\".equals(e.getActionCommand())) {\n buttonClicked = \"cancel\";\n setVisible(false);\n } else if (\"never\".equals(e.getActionCommand())) {\n buttonClicked = \"never\";\n setVisible(false);\n }\n }\n", "func2": " public static void extractFile(String input, String output) throws ZipException, IOException {\n FileReader reader = new FileReader(input);\n InputStream in = reader.getInputStream();\n OutputStream out = new FileOutputStream(new File(output));\n byte[] buf = new byte[512];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n reader.close();\n out.close();\n }\n", "label": 0} {"func1": " public void actionPerformed(ActionEvent ae) {\n if (ae.getSource() == jbutton) {\n try {\n String toservlet = \"http://localhost:8080/direto-project/arquivos/teste.odt\";\n URL servleturl = new URL(toservlet);\n URLConnection servletconnection = servleturl.openConnection();\n servletconnection.setDoInput(true);\n servletconnection.setDoOutput(true);\n servletconnection.setUseCaches(false);\n servletconnection.setDefaultUseCaches(false);\n DataInputStream inputFromClient = new DataInputStream(servletconnection.getInputStream());\n inputFromClient.readByte();\n OutputStream fos = new FileOutputStream(\"/home/danillo/arquivo_carregado.odt\");\n byte[] buf = new byte[1024];\n int bytesread;\n while ((bytesread = inputFromClient.read(buf)) > -1) {\n fos.write(buf, 0, bytesread);\n }\n inputFromClient.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n", "func2": " public static boolean copyFile(final File src, final File dst) {\n boolean result = false;\n FileChannel inChannel = null;\n FileChannel outChannel = null;\n synchronized (FileUtil.DATA_LOCK) {\n try {\n inChannel = new FileInputStream(src).getChannel();\n outChannel = new FileOutputStream(dst).getChannel();\n inChannel.transferTo(0, inChannel.size(), outChannel);\n result = true;\n } catch (IOException e) {\n } finally {\n if (inChannel != null && inChannel.isOpen()) {\n try {\n inChannel.close();\n } catch (IOException e) {\n }\n }\n if (outChannel != null && outChannel.isOpen()) {\n try {\n outChannel.close();\n } catch (IOException e) {\n }\n }\n }\n }\n return result;\n }\n", "label": 0} {"func1": " public static String createPseudoUUID() {\n try {\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(new UID().toString().getBytes());\n try {\n String localHost = InetAddress.getLocalHost().toString();\n messageDigest.update(localHost.getBytes());\n } catch (UnknownHostException e) {\n throw new OXFException(e);\n }\n byte[] digestBytes = messageDigest.digest();\n StringBuffer sb = new StringBuffer();\n sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 0)));\n sb.append('-');\n sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 4)));\n sb.append('-');\n sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 6)));\n sb.append('-');\n sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 8)));\n sb.append('-');\n sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 10)));\n sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 12)));\n return sb.toString();\n } catch (NoSuchAlgorithmException e) {\n throw new OXFException(e);\n }\n }\n", "func2": " public Processing getProcess(long processId) throws BookKeeprCommunicationException {\n try {\n synchronized (httpClient) {\n HttpGet req = new HttpGet(remoteHost.getUrl() + \"/id/\" + Long.toHexString(processId));\n HttpResponse resp = httpClient.execute(req);\n if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {\n try {\n XMLAble xmlable = XMLReader.read(resp.getEntity().getContent());\n if (xmlable instanceof Processing) {\n Processing p = (Processing) xmlable;\n return p;\n } else {\n throw new BookKeeprCommunicationException(\"BookKeepr returned the wrong thing for pointingID\");\n }\n } catch (SAXException ex) {\n Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, \"Got a malformed message from the bookkeepr\", ex);\n throw new BookKeeprCommunicationException(ex);\n }\n } else {\n resp.getEntity().consumeContent();\n throw new BookKeeprCommunicationException(\"Got a \" + resp.getStatusLine().getStatusCode() + \" from the BookKeepr\");\n }\n }\n } catch (HttpException ex) {\n throw new BookKeeprCommunicationException(ex);\n } catch (IOException ex) {\n throw new BookKeeprCommunicationException(ex);\n } catch (URISyntaxException ex) {\n throw new BookKeeprCommunicationException(ex);\n }\n }\n", "label": 0} {"func1": " @Test(expected = GadgetException.class)\n public void malformedGadgetSpecIsCachedAndThrows() throws Exception {\n HttpRequest request = createCacheableRequest();\n expect(pipeline.execute(request)).andReturn(new HttpResponse(\"malformed junk\")).once();\n replay(pipeline);\n try {\n specFactory.getGadgetSpec(createContext(SPEC_URL, false));\n fail(\"No exception thrown on bad parse\");\n } catch (GadgetException e) {\n }\n specFactory.getGadgetSpec(createContext(SPEC_URL, false));\n }\n", "func2": " @ActionMethod\n public void upload() throws IOException {\n final int fileResult = fileChooser.showOpenDialog(frame);\n if (fileResult != JFileChooser.APPROVE_OPTION) {\n return;\n }\n final InputStream in = new FileInputStream(fileChooser.getSelectedFile());\n try {\n final URL url = new URL(\"http://127.0.0.1:\" + testPort + \"/databases/\" + fileChooser.getSelectedFile().getName());\n final HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setRequestMethod(\"PUT\");\n con.setDoOutput(true);\n con.setRequestProperty(Http11Header.AUTHORIZATION, \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\");\n con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, \"Basic realm=\\\"karatasi\\\"\");\n con.setRequestProperty(Http11Header.CONTENT_LENGTH, Long.toString(fileChooser.getSelectedFile().length()));\n con.setRequestProperty(Http11Header.CONTENT_TYPE, \"application/octet-stream\");\n final OutputStream out = con.getOutputStream();\n try {\n Util.copy(in, out);\n con.connect();\n final InputStream in2 = con.getInputStream();\n try {\n textArea.setText(\"\");\n final byte[] buf = new byte[4096];\n for (int bytesRead; (bytesRead = in2.read(buf)) != -1; ) {\n textArea.append(new String(buf, 0, bytesRead));\n }\n } finally {\n in2.close();\n }\n } finally {\n out.close();\n }\n } finally {\n in.close();\n }\n }\n", "label": 0} {"func1": " public void testTransactions() throws Exception {\n con = TestUtil.openDB();\n Statement st;\n ResultSet rs;\n con.setAutoCommit(false);\n assertTrue(!con.getAutoCommit());\n con.setAutoCommit(true);\n assertTrue(con.getAutoCommit());\n st = con.createStatement();\n st.executeUpdate(\"insert into test_a (imagename,image,id) values ('comttest',1234,5678)\");\n con.setAutoCommit(false);\n st.executeUpdate(\"update test_a set image=9876 where id=5678\");\n con.commit();\n rs = st.executeQuery(\"select image from test_a where id=5678\");\n assertTrue(rs.next());\n assertEquals(9876, rs.getInt(1));\n rs.close();\n st.executeUpdate(\"update test_a set image=1111 where id=5678\");\n con.rollback();\n rs = st.executeQuery(\"select image from test_a where id=5678\");\n assertTrue(rs.next());\n assertEquals(9876, rs.getInt(1));\n rs.close();\n TestUtil.closeDB(con);\n }\n", "func2": " public boolean referredFilesChanged() throws MalformedURLException, IOException {\n for (String file : referredFiles) {\n if (FileUtils.isURI(file)) {\n URLConnection url = new URL(file).openConnection();\n if (url.getLastModified() > created) return true;\n } else if (FileUtils.isFile(file)) {\n File f = new File(file);\n if (f.lastModified() > created) return true;\n }\n }\n return false;\n }\n", "label": 0} {"func1": " public boolean deleteRoleType(int id, int namespaceId, boolean removeReferencesInRoleTypes, DTSPermission permit) throws SQLException, PermissionException, DTSValidationException {\n checkPermission(permit, String.valueOf(namespaceId));\n boolean exist = isRoleTypeUsed(namespaceId, id);\n if (exist) {\n throw new DTSValidationException(ApelMsgHandler.getInstance().getMsg(\"DTS-0034\"));\n }\n if (!removeReferencesInRoleTypes) {\n StringBuffer msgBuf = new StringBuffer();\n DTSTransferObject[] objects = fetchRightIdentityReferences(namespaceId, id);\n if (objects.length > 0) {\n msgBuf.append(\"Role Type is Right Identity in one or more Role Types.\");\n }\n objects = fetchParentReferences(namespaceId, id);\n if (objects.length > 0) {\n if (msgBuf.length() > 0) {\n msgBuf.append(\"\\n\");\n }\n msgBuf.append(\"Role Type is Parent of one or more Role Types.\");\n }\n if (msgBuf.length() > 0) {\n throw new DTSValidationException(msgBuf.toString());\n }\n }\n String sqlRightId = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE_RIGHT_IDENTITY_REF\");\n String sqlParent = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE_PARENT_REF\");\n String sql = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE\");\n PreparedStatement pstmt = null;\n boolean success = false;\n long typeGid = getGID(namespaceId, id);\n conn.setAutoCommit(false);\n int defaultLevel = conn.getTransactionIsolation();\n conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n try {\n pstmt = conn.prepareStatement(sqlRightId);\n pstmt.setLong(1, typeGid);\n pstmt.executeUpdate();\n pstmt.close();\n pstmt = conn.prepareStatement(sqlParent);\n pstmt.setLong(1, typeGid);\n pstmt.executeUpdate();\n pstmt.close();\n pstmt = conn.prepareStatement(sql);\n pstmt.setLong(1, typeGid);\n int count = pstmt.executeUpdate();\n success = (count == 1);\n conn.commit();\n } catch (SQLException e) {\n conn.rollback();\n throw e;\n } finally {\n conn.setTransactionIsolation(defaultLevel);\n conn.setAutoCommit(true);\n closeStatement(pstmt);\n }\n return success;\n }\n", "func2": " public static boolean copyFile(String sourceName, String destName) {\n FileChannel sourceChannel = null;\n FileChannel destChannel = null;\n boolean wasOk = false;\n try {\n sourceChannel = new FileInputStream(sourceName).getChannel();\n destChannel = new FileOutputStream(destName).getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n wasOk = true;\n } catch (Throwable exception) {\n logger.log(Level.SEVERE, \"Exception in copyFile\", exception);\n } finally {\n try {\n if (sourceChannel != null) sourceChannel.close();\n } catch (Throwable tt) {\n }\n try {\n if (destChannel != null) destChannel.close();\n } catch (Throwable tt) {\n }\n }\n return wasOk;\n }\n", "label": 0} {"func1": " static File copy(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n return out;\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " private void update(String statement, SyrupConnection con, boolean do_log) throws Exception {\n Statement s = null;\n try {\n s = con.createStatement();\n s.executeUpdate(statement);\n con.commit();\n } catch (Throwable e) {\n if (do_log) {\n logger.log(Level.INFO, \"Update failed. Transaction is rolled back\", e);\n }\n con.rollback();\n }\n }\n", "label": 0} {"func1": " private static String lastModified(URL url) {\n try {\n URLConnection conn = url.openConnection();\n return long2date(conn.getLastModified());\n } catch (Exception e) {\n SWGAide.printDebug(\"cach\", 1, \"SWGCraftCache:lastModified: \" + e.getMessage());\n }\n return \"0\";\n }\n", "func2": " public static String getMessageDigest(String[] inputs) {\n if (inputs.length == 0) return null;\n try {\n MessageDigest sha = MessageDigest.getInstance(\"SHA-1\");\n for (String input : inputs) sha.update(input.getBytes());\n byte[] hash = sha.digest();\n String CPass = \"\";\n int h = 0;\n String s = \"\";\n for (int i = 0; i < 20; i++) {\n h = hash[i];\n if (h < 0) h += 256;\n s = Integer.toHexString(h);\n if (s.length() < 2) CPass = CPass.concat(\"0\");\n CPass = CPass.concat(s);\n }\n CPass = CPass.toUpperCase();\n return CPass;\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(e.getMessage());\n }\n }\n", "label": 0} {"func1": " public void uncaughtException(final Thread t, final Throwable e) {\n final Display display = Display.getCurrent();\n final Shell shell = new Shell(display);\n final MessageBox message = new MessageBox(shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR);\n message.setText(\"Hawkscope Error\");\n message.setMessage(e.getMessage() + \"\\nSubmit Hawkscope Error Report to Issue Tracker?\");\n log.error(\"Uncaught exception\", e);\n if (message.open() == SWT.OK) {\n IOUtils.copyToClipboard(Version.getBugReport(e));\n try {\n Program.launch(Constants.HAWKSCOPE_URL_ROOT + \"issues/entry?comment=\" + URLEncoder.encode(\"Please paste the Hawkscope Error \" + \"Report here. It's currently copied to your \" + \"clipboard. Thank you for your support!\", Constants.ENCODING));\n } catch (final Exception e1) {\n Program.launch(Constants.HAWKSCOPE_URL_ROOT + \"issues/entry\");\n }\n }\n shell.dispose();\n }\n", "func2": " public static InputStream getResourceAsStreamIfAny(String resPath) {\n URL url = findResource(resPath);\n try {\n return url == null ? null : url.openStream();\n } catch (IOException e) {\n ZMLog.warn(e, \" URL open Connection got an exception!\");\n return null;\n }\n }\n", "label": 0} {"func1": " public PageLoader(String pageAddress) throws Exception {\n URL url = new URL(pageAddress);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n inputLine = \"\";\n while (in.ready()) {\n inputLine = inputLine + in.readLine();\n }\n in.close();\n }\n", "func2": " public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException {\n int k_blockSize = 1024;\n int byteCount;\n char[] buf = new char[k_blockSize];\n File ofp = new File(outFile);\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp));\n zos.setMethod(ZipOutputStream.DEFLATED);\n OutputStreamWriter osw = new OutputStreamWriter(zos, \"ISO-8859-1\");\n BufferedWriter bw = new BufferedWriter(osw);\n ZipEntry zot = null;\n File ifp = new File(inFile);\n ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp));\n InputStreamReader isr = new InputStreamReader(zis, \"ISO-8859-1\");\n BufferedReader br = new BufferedReader(isr);\n ZipEntry zit = null;\n while ((zit = zis.getNextEntry()) != null) {\n if (zit.getName().equals(\"content.xml\")) {\n continue;\n }\n zot = new ZipEntry(zit.getName());\n zos.putNextEntry(zot);\n while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount);\n bw.flush();\n zos.closeEntry();\n }\n zos.putNextEntry(new ZipEntry(\"content.xml\"));\n bw.flush();\n osw = new OutputStreamWriter(zos, \"UTF8\");\n bw = new BufferedWriter(osw);\n return bw;\n }\n", "label": 0} {"func1": " private void parse() throws Exception {\n BufferedReader br = null;\n InputStream httpStream = null;\n URL fileURL = new URL(url);\n URLConnection urlConnection = fileURL.openConnection();\n httpStream = urlConnection.getInputStream();\n br = new BufferedReader(new InputStreamReader(httpStream, \"UTF-8\"));\n String ligne;\n String post;\n String date;\n String titre;\n String resume;\n String url2DL;\n while ((ligne = br.readLine()) != null) {\n if (ligne.indexOf(\"div class=\\\"post\\\" id=\\\"post\") != -1) {\n post = null;\n date = null;\n titre = null;\n try {\n post = ligne.substring(ligne.indexOf(\"post-\") + 5, ligne.indexOf(\"\\\"\", ligne.indexOf(\"post-\")));\n ligne = br.readLine();\n date = ligne.substring(ligne.indexOf(\"
\") + 24);\n date = date.replaceAll(\"\", \"\").replaceAll(\"
\", \"\").trim();\n log.info(\"Post : \" + post + \" du \" + date);\n ligne = br.readLine();\n ligne = br.readLine();\n titre = ligne.substring(ligne.indexOf(\">\", ligne.indexOf(\"title\")) + 1, ligne.indexOf(\"\"));\n titre = titre.replaceAll(\"’\", \"'\").replaceAll(\"“\", \"\\\"\").replaceAll(\"”\", \"\\\"\");\n url2DL = ligne.substring(ligne.indexOf(\"\") + 4, ligne.indexOf(\"\"));\n resume = resume.replaceAll(\"’\", \"'\").replaceAll(\"“\", \"\\\"\").replaceAll(\"”\", \"\\\"\");\n log.info(\"Resume : \" + resume);\n } catch (Exception e) {\n log.error(\"ERREUR : Le film n'a pas pu etre parse...\");\n }\n log.info(\"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\");\n }\n }\n }\n", "func2": " public Converter(String input, String output) {\n try {\n FileInputStream fis = new FileInputStream(new File(input));\n BufferedReader in = new BufferedReader(new InputStreamReader(fis, \"SJIS\"));\n FileOutputStream fos = new FileOutputStream(new File(output));\n BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, \"UTF8\"));\n int len = 80;\n char buf[] = new char[len];\n int numRead;\n while ((numRead = in.read(buf, 0, len)) != -1) out.write(buf, 0, numRead);\n out.close();\n in.close();\n } catch (IOException e) {\n System.out.println(\"An I/O Exception Occurred: \" + e);\n }\n }\n", "label": 0} {"func1": " private String executePost(String targetURL, String urlParameters) {\n URL url;\n HttpURLConnection connection = null;\n try {\n url = new URL(targetURL);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n connection.setRequestProperty(\"Content-Length\", \"\" + Integer.toString(urlParameters.getBytes().length));\n connection.setRequestProperty(\"Content-Language\", \"en-US\");\n connection.setUseCaches(false);\n connection.setDoInput(true);\n connection.setDoOutput(true);\n DataOutputStream wr = new DataOutputStream(connection.getOutputStream());\n wr.writeBytes(urlParameters);\n wr.flush();\n wr.close();\n InputStream is = connection.getInputStream();\n BufferedReader rd = new BufferedReader(new InputStreamReader(is));\n String line;\n StringBuffer response = new StringBuffer();\n while ((line = rd.readLine()) != null) {\n response.append(line);\n response.append('\\r');\n }\n rd.close();\n return response.toString();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }\n", "func2": " public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException {\n FileChannel inputChannel = new FileInputStream(inputFile).getChannel();\n FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();\n try {\n inputChannel.transferTo(0, inputChannel.size(), outputChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inputChannel != null) inputChannel.close();\n if (outputChannel != null) outputChannel.close();\n }\n }\n", "label": 0} {"func1": " public static void fileUpload() throws IOException {\n HttpClient httpclient = new DefaultHttpClient();\n httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);\n HttpPost httppost = new HttpPost(postURL);\n File file = new File(\"d:/hai.html\");\n System.out.println(ukeycookie);\n httppost.setHeader(\"Cookie\", ukeycookie + \";\" + skeycookie + \";\" + usercookie);\n MultipartEntity mpEntity = new MultipartEntity();\n ContentBody cbFile = new FileBody(file);\n mpEntity.addPart(\"\", cbFile);\n httppost.setEntity(mpEntity);\n System.out.println(\"Now uploading your file into mediafire...........................\");\n HttpResponse response = httpclient.execute(httppost);\n HttpEntity resEntity = response.getEntity();\n System.out.println(response.getStatusLine());\n if (resEntity != null) {\n System.out.println(\"Getting upload response key value..........\");\n uploadresponsekey = EntityUtils.toString(resEntity);\n getUploadResponseKey();\n System.out.println(\"upload resoponse key \" + uploadresponsekey);\n }\n }\n", "func2": " public Wget2(URL url, File f) throws IOException {\n System.out.println(\"bajando: \" + url);\n if (f == null) {\n by = new ByteArrayOutputStream();\n } else {\n by = new FileOutputStream(f);\n }\n URLConnection uc = url.openConnection();\n if (uc instanceof HttpURLConnection) {\n leerHttp((HttpURLConnection) uc);\n } else {\n throw new IOException(\"solo se pueden descargar url http\");\n }\n }\n", "label": 0} {"func1": " static Matrix readMatrix(String filename, int nrow, int ncol) {\n Matrix cij = new Matrix(nrow, ncol);\n try {\n URL url = filename.getClass().getResource(filename);\n LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));\n for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));\n } catch (Exception xc) {\n xc.printStackTrace();\n }\n return cij;\n }\n", "func2": " public static void copyFile(File in, File out) throws Exception {\n FileChannel sourceChannel = null;\n FileChannel destinationChannel = null;\n try {\n sourceChannel = new FileInputStream(in).getChannel();\n destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n } finally {\n if (sourceChannel != null) sourceChannel.close();\n if (destinationChannel != null) destinationChannel.close();\n }\n }\n", "label": 0} {"func1": " private static List runITQLQuery(String itqlQuery) throws Exception {\n String escapedItqlQuery = URLEncoder.encode(itqlQuery, \"UTF-8\");\n String url = \"http://\" + Config.getProperty(\"FEDORA_SOAP_HOST\") + \":\" + Config.getProperty(\"FEDORA_SOAP_ACCESS_PORT\") + \"/fedora/risearch?type=tuples\" + \"&lang=iTQL\" + \"&format=CSV\" + \"&distinct=on\" + \"&stream=on\" + \"&query=\" + escapedItqlQuery;\n logger.debug(\"url for risearch query: \" + url);\n URL urlObject = new URL(url);\n HttpURLConnection con = (HttpURLConnection) urlObject.openConnection();\n BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));\n logger.debug(\"response code: \" + con.getResponseCode());\n if (con.getResponseCode() != 200 && con.getResponseCode() != 302) {\n throw new FedoraAccessException(\"Could not access the risearch service at url: \" + url);\n }\n ArrayList arrayList = new ArrayList();\n String inputLine;\n int counter = 0;\n while ((inputLine = br.readLine()) != null) {\n logger.debug(\"reading line:\" + inputLine);\n if (inputLine.indexOf(\"\") >= 0) {\n logger.error(\"problem quering the relationship\");\n throw new Exception(\"Problem querying relationships; probably a bad ITQL query:\" + itqlQuery);\n }\n if (counter >= 1 && inputLine.indexOf(\"/\") >= 0 && inputLine.trim().length() > 0) {\n logger.debug(\"adding line:\" + inputLine);\n inputLine = inputLine.substring(inputLine.indexOf(\"/\") + 1);\n arrayList.add(inputLine);\n logger.debug(\"found relationship to item: \" + inputLine);\n }\n counter++;\n }\n br.close();\n logger.debug(\"num relationships found: \" + arrayList.size());\n return arrayList;\n }\n", "func2": " public void transport(File file) throws TransportException {\n if (file.exists()) {\n if (file.isDirectory()) {\n File[] files = file.listFiles();\n for (int i = 0; i < files.length; i++) {\n transport(file);\n }\n } else if (file.isFile()) {\n try {\n FileChannel inChannel = new FileInputStream(file).getChannel();\n FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n log.error(\"File transfer failed\", e);\n }\n }\n }\n }\n", "label": 0} {"func1": " public static String encrypt(String plainText) {\n if (TextUtils.isEmpty(plainText)) {\n plainText = \"\";\n }\n StringBuilder text = new StringBuilder();\n for (int i = plainText.length() - 1; i >= 0; i--) {\n text.append(plainText.charAt(i));\n }\n plainText = text.toString();\n MessageDigest mDigest;\n try {\n mDigest = MessageDigest.getInstance(\"SHA-256\");\n } catch (NoSuchAlgorithmException e) {\n return plainText;\n }\n mDigest.update(plainText.getBytes());\n byte d[] = mDigest.digest();\n StringBuffer hash = new StringBuffer();\n for (int i = 0; i < d.length; i++) {\n hash.append(Integer.toHexString(0xFF & d[i]));\n }\n return hash.toString();\n }\n", "func2": " public static void fileUpload() throws IOException {\n HttpClient httpclient = new DefaultHttpClient();\n httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);\n HttpPost httppost = new HttpPost(postURL);\n File file = new File(\"d:/hai.html\");\n System.out.println(ukeycookie);\n httppost.setHeader(\"Cookie\", ukeycookie + \";\" + skeycookie + \";\" + usercookie);\n MultipartEntity mpEntity = new MultipartEntity();\n ContentBody cbFile = new FileBody(file);\n mpEntity.addPart(\"\", cbFile);\n httppost.setEntity(mpEntity);\n System.out.println(\"Now uploading your file into mediafire...........................\");\n HttpResponse response = httpclient.execute(httppost);\n HttpEntity resEntity = response.getEntity();\n System.out.println(response.getStatusLine());\n if (resEntity != null) {\n System.out.println(\"Getting upload response key value..........\");\n uploadresponsekey = EntityUtils.toString(resEntity);\n getUploadResponseKey();\n System.out.println(\"upload resoponse key \" + uploadresponsekey);\n }\n }\n", "label": 0} {"func1": " private synchronized void loadDDL() throws IOException {\n try {\n conn.createStatement().executeQuery(\"SELECT * FROM non_generic_favs\").close();\n } catch (SQLException e) {\n Statement stmt = null;\n if (!e.getMessage().matches(ERR_MISSING_TABLE)) {\n e.printStackTrace(System.out);\n throw new IOException(\"Error on initial data store read\");\n }\n String[] qry = { \"CREATE TABLE non_generic_favs (id INT NOT NULL PRIMARY KEY)\", \"CREATE TABLE ignore_chan_favs (id INT NOT NULL PRIMARY KEY, chanlist LONG VARCHAR)\", \"CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))\", \"INSERT INTO settings (var, val) VALUES ('schema', '1')\" };\n try {\n conn.setAutoCommit(false);\n stmt = conn.createStatement();\n for (String q : qry) stmt.executeUpdate(q);\n conn.commit();\n } catch (SQLException e2) {\n try {\n conn.rollback();\n } catch (SQLException e3) {\n e3.printStackTrace(System.out);\n }\n e2.printStackTrace(new PrintWriter(System.out));\n throw new IOException(\"Error initializing data store\");\n } finally {\n if (stmt != null) {\n try {\n stmt.close();\n } catch (SQLException e4) {\n e4.printStackTrace(System.out);\n throw new IOException(\"Unable to cleanup data store resources\");\n }\n }\n try {\n conn.setAutoCommit(true);\n } catch (SQLException e3) {\n e3.printStackTrace(System.out);\n throw new IOException(\"Unable to reset data store auto commit\");\n }\n }\n }\n return;\n }\n", "func2": " private void compress(String outputFile, ArrayList inputFiles, PrintWriter log, boolean compress) throws Exception {\n String absPath = getAppConfig().getPathConfig().getAbsoluteServerPath();\n log.println(\"Concat files into: \" + outputFile);\n OutputStream out = new FileOutputStream(absPath + outputFile);\n byte[] buffer = new byte[4096];\n int readBytes;\n for (String file : inputFiles) {\n log.println(\" Read: \" + file);\n InputStream in = new FileInputStream(absPath + file);\n while ((readBytes = in.read(buffer)) != -1) {\n out.write(buffer, 0, readBytes);\n }\n in.close();\n }\n out.close();\n if (compress) {\n long normalSize = new File(absPath + outputFile).length();\n ProcessBuilder builder = new ProcessBuilder(\"java\", \"-jar\", \"WEB-INF/yuicompressor.jar\", outputFile, \"-o\", outputFile, \"--line-break\", \"4000\");\n builder.directory(new File(absPath));\n Process process = builder.start();\n process.waitFor();\n long minSize = new File(absPath + outputFile).length();\n long diff = normalSize - minSize;\n double percentage = Math.floor((double) diff / normalSize * 1000.0) / 10.0;\n double diffSize = (Math.floor(diff / 1024.0 * 10.0) / 10.0);\n log.println(\"Result: \" + percentage + \" % (\" + diffSize + \" KB)\");\n }\n }\n", "label": 0} {"func1": " @Override\n public InputStream getInputStream() {\n try {\n String url = webBrowserObject.resourcePath;\n File file = Utils.getLocalFile(url);\n if (file != null) {\n url = webBrowserObject.getLocalFileURL(file);\n }\n url = url.substring(0, url.lastIndexOf('/')) + \"/\" + resource;\n return new URL(url).openStream();\n } catch (Exception e) {\n }\n return null;\n }\n", "func2": " private boolean getWave(String url, String Word) {\n try {\n File FF = new File(f.getParent() + \"/\" + f.getName() + \"pron\");\n FF.mkdir();\n URL url2 = new URL(url);\n BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));\n File Fdel = new File(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n if (!Fdel.exists()) {\n FileOutputStream outstream = new FileOutputStream(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));\n char[] binput = new char[1024];\n int len = stream.read(binput, 0, 1024);\n while (len > 0) {\n bwriter.write(binput, 0, len);\n len = stream.read(binput, 0, 1024);\n }\n bwriter.close();\n outstream.close();\n }\n stream.close();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " public void actualizar() throws SQLException, ClassNotFoundException, Exception {\n Connection conn = null;\n PreparedStatement ms = null;\n registroActualizado = false;\n try {\n conn = ToolsBD.getConn();\n conn.setAutoCommit(false);\n Date fechaSystem = new Date();\n DateFormat aaaammdd = new SimpleDateFormat(\"yyyyMMdd\");\n int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));\n DateFormat hhmmss = new SimpleDateFormat(\"HHmmss\");\n DateFormat sss = new SimpleDateFormat(\"S\");\n String ss = sss.format(fechaSystem);\n if (ss.length() > 2) {\n ss = ss.substring(0, 2);\n }\n int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);\n ms = conn.prepareStatement(SENTENCIA_UPDATE);\n ms.setString(1, descartadoEntrada);\n ms.setString(2, usuarioEntrada);\n ms.setString(3, motivosDescarteEntrada);\n ms.setInt(4, Integer.parseInt(anoOficio));\n ms.setInt(5, Integer.parseInt(oficinaOficio));\n ms.setInt(6, Integer.parseInt(numeroOficio));\n ms.setInt(7, anoEntrada != null ? Integer.parseInt(anoEntrada) : 0);\n ms.setInt(8, oficinaEntrada != null ? Integer.parseInt(oficinaEntrada) : 0);\n ms.setInt(9, numeroEntrada != null ? Integer.parseInt(numeroEntrada) : 0);\n int afectados = ms.executeUpdate();\n if (afectados > 0) {\n registroActualizado = true;\n } else {\n registroActualizado = false;\n }\n conn.commit();\n } catch (Exception ex) {\n System.out.println(\"Error inesperat, no s'ha desat el registre: \" + ex.getMessage());\n ex.printStackTrace();\n registroActualizado = false;\n errores.put(\"\", \"Error inesperat, no s'ha desat el registre\" + \": \" + ex.getClass() + \"->\" + ex.getMessage());\n try {\n if (conn != null) conn.rollback();\n } catch (SQLException sqle) {\n throw new RemoteException(\"S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats\", sqle);\n }\n throw new RemoteException(\"Error inesperat, no s'ha modifcat el registre\", ex);\n } finally {\n ToolsBD.closeConn(conn, ms, null);\n }\n }\n", "func2": " @Override\n public File call() throws IOException {\n HttpURLConnection conn = null;\n ReadableByteChannel fileDownloading = null;\n FileChannel fileWriting = null;\n try {\n conn = (HttpURLConnection) url.openConnection();\n if (size == -1) {\n size = conn.getContentLength();\n }\n fileDownloading = Channels.newChannel(conn.getInputStream());\n fileWriting = new FileOutputStream(file).getChannel();\n long left = size;\n long chunkSize = BLOCK_SIZE;\n for (long downloaded = 0; downloaded < size; left = size - downloaded) {\n if (left < BLOCK_SIZE) {\n chunkSize = left;\n }\n fileWriting.transferFrom(fileDownloading, downloaded, chunkSize);\n downloaded += chunkSize;\n setProgress(downloaded);\n }\n } finally {\n if (file != null) {\n file.deleteOnExit();\n }\n if (conn != null) {\n conn.disconnect();\n }\n if (fileDownloading != null) {\n try {\n fileDownloading.close();\n } catch (IOException ioe) {\n Helper.logger.log(Level.SEVERE, \"Не удалось закрыть поток скачивания\", ioe);\n }\n }\n if (fileWriting != null) {\n try {\n fileWriting.close();\n } catch (IOException ioe) {\n Helper.logger.log(Level.SEVERE, \"Не удалось закрыть поток записи в файл\", ioe);\n }\n }\n }\n return file;\n }\n", "label": 0} {"func1": " public boolean actEstadoEnBD(int idRonda) {\n int intResult = 0;\n String sql = \"UPDATE ronda \" + \" SET estado = 1\" + \" WHERE numeroRonda = \" + idRonda;\n try {\n connection = conexionBD.getConnection();\n connection.setAutoCommit(false);\n ps = connection.prepareStatement(sql);\n intResult = ps.executeUpdate();\n connection.commit();\n } catch (SQLException ex) {\n ex.printStackTrace();\n try {\n connection.rollback();\n } catch (SQLException exe) {\n exe.printStackTrace();\n }\n } finally {\n conexionBD.close(ps);\n conexionBD.close(connection);\n }\n return (intResult > 0);\n }\n", "func2": " public String digest(String message) throws NoSuchAlgorithmException, EncoderException {\n MessageDigest messageDigest = MessageDigest.getInstance(\"SHA-256\");\n messageDigest.update(message.getBytes());\n byte[] raw = messageDigest.digest();\n byte[] chars = new Base64().encode(raw);\n return new String(chars);\n }\n", "label": 0} {"func1": " @Test\n public void testLoadHttpGzipped() throws Exception {\n String url = HTTP_GZIPPED;\n LoadingInfo loadingInfo = Utils.openFileObject(fsManager.resolveFile(url));\n InputStream contentInputStream = loadingInfo.getContentInputStream();\n byte[] actual = IOUtils.toByteArray(contentInputStream);\n byte[] expected = IOUtils.toByteArray(new GZIPInputStream(new URL(url).openStream()));\n assertEquals(expected.length, actual.length);\n }\n", "func2": " private boolean saveNodeMeta(NodeInfo info, int properties) {\n boolean rCode = false;\n String query = mServer + \"save.php\" + (\"?id=\" + info.getId());\n try {\n URL url = new URL(query);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n byte[] body = Helpers.EncodeString(Helpers.ASCII, createURLEncodedPropertyString(info, properties));\n conn.setAllowUserInteraction(false);\n conn.setRequestMethod(\"POST\");\n conn.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n setCredentials(conn);\n conn.setDoOutput(true);\n conn.getOutputStream().write(body);\n rCode = saveNode(info, conn);\n } catch (Exception ex) {\n System.out.println(\"Exception: \" + ex.toString());\n }\n return rCode;\n }\n", "label": 0} {"func1": " public static void main(String[] args) {\n FTPClient client = new FTPClient();\n FileOutputStream fos = null;\n try {\n client.connect(\"192.168.1.10\");\n client.login(\"a\", \"123456\");\n String filename = \"i.exe\";\n fos = new FileOutputStream(filename);\n client.retrieveFile(\"/\" + filename, fos);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (fos != null) {\n fos.close();\n }\n client.disconnect();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n", "func2": " @Test\n public void testSpeedyShareUpload() throws Exception {\n request.setUrl(\"http://www.speedyshare.com/upload.php\");\n request.setFile(\"fileup0\", file);\n HttpResponse response = httpClient.execute(request);\n assertTrue(response.is2xxSuccess());\n assertTrue(response.getResponseHeaders().size() > 0);\n String body = IOUtils.toString(response.getResponseBody());\n assertTrue(body.contains(\"Download link\"));\n assertTrue(body.contains(\"Delete password\"));\n response.close();\n }\n", "label": 0} {"func1": " public static void copyFile(File in, File out) throws Exception {\n FileChannel sourceChannel = new FileInputStream(in).getChannel();\n FileChannel destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n }\n", "func2": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "label": 0} {"func1": " static Matrix readMatrix(String filename, int nrow, int ncol) {\n Matrix cij = new Matrix(nrow, ncol);\n try {\n URL url = filename.getClass().getResource(filename);\n LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));\n for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));\n } catch (Exception xc) {\n xc.printStackTrace();\n }\n return cij;\n }\n", "func2": " public void patch() throws IOException {\n if (mods.isEmpty()) {\n return;\n }\n IOUtils.copy(new FileInputStream(Paths.getMinecraftJarPath()), new FileOutputStream(new File(Paths.getMinecraftBackupPath())));\n JarFile mcjar = new JarFile(Paths.getMinecraftJarPath());\n }\n", "label": 0} {"func1": " public boolean referredFilesChanged() throws MalformedURLException, IOException {\n for (String file : referredFiles) {\n if (FileUtils.isURI(file)) {\n URLConnection url = new URL(file).openConnection();\n if (url.getLastModified() > created) return true;\n } else if (FileUtils.isFile(file)) {\n File f = new File(file);\n if (f.lastModified() > created) return true;\n }\n }\n return false;\n }\n", "func2": "\tpublic FTPClient sample3a(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {\n\t\tFTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);\n\t\tftpClient.connect(ftpserver, ftpport);\n\t\tftpClient.login(username, password);\n\t\treturn ftpClient;\n\t}\n", "label": 0} {"func1": " protected void truncate(final File file) {\n LogLog.debug(\"Compression of file: \" + file.getAbsolutePath() + \" started.\");\n if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {\n final File backupRoot = new File(this.getBackupDir());\n if (!backupRoot.exists() && !backupRoot.mkdirs()) {\n throw new AppenderInitializationError(\"Can't create backup dir for backup storage\");\n }\n SimpleDateFormat df;\n try {\n df = new SimpleDateFormat(this.getBackupDateFormat());\n } catch (final Exception e) {\n throw new AppenderInitializationError(\"Invalid date formate for backup files: \" + this.getBackupDateFormat(), e);\n }\n final String date = df.format(new Date(file.lastModified()));\n final File zipFile = new File(backupRoot, file.getName() + \".\" + date + \".zip\");\n ZipOutputStream zos = null;\n FileInputStream fis = null;\n try {\n zos = new ZipOutputStream(new FileOutputStream(zipFile));\n final ZipEntry entry = new ZipEntry(file.getName());\n entry.setMethod(ZipEntry.DEFLATED);\n entry.setCrc(FileUtils.checksumCRC32(file));\n zos.putNextEntry(entry);\n fis = FileUtils.openInputStream(file);\n final byte[] buffer = new byte[1024];\n int readed;\n while ((readed = fis.read(buffer)) != -1) {\n zos.write(buffer, 0, readed);\n }\n } catch (final Exception e) {\n throw new AppenderInitializationError(\"Can't create zip file\", e);\n } finally {\n if (zos != null) {\n try {\n zos.close();\n } catch (final IOException e) {\n LogLog.warn(\"Can't close zip file\", e);\n }\n }\n if (fis != null) {\n try {\n fis.close();\n } catch (final IOException e) {\n LogLog.warn(\"Can't close zipped file\", e);\n }\n }\n }\n if (!file.delete()) {\n throw new AppenderInitializationError(\"Can't delete old log file \" + file.getAbsolutePath());\n }\n }\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 0} {"func1": " public void writeConfiguration(Writer out) throws IOException {\n if (myResource == null) {\n out.append(\"# Unable to print configuration resource\\n\");\n } else {\n URL url = myResource.getUrl();\n InputStream in = url.openStream();\n if (in != null) {\n try {\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(in);\n }\n } else {\n out.append(\"# Unable to print configuration resource\\n\");\n }\n }\n }\n", "func2": " private static String scramble(String text) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n md.update(text.getBytes(\"UTF-8\"));\n StringBuffer sb = new StringBuffer();\n for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16));\n return sb.toString();\n } catch (UnsupportedEncodingException e) {\n return null;\n } catch (NoSuchAlgorithmException e) {\n return null;\n }\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " @Test\n public void test30_passwordAging() throws Exception {\n Db db = DbConnection.defaultCieDbRW();\n try {\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"5\", 1);\n PreparedStatement pst = db.prepareStatement(\"UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?\");\n pst.setString(1, \"esis\");\n db.executeUpdate(pst);\n db.commit();\n p_logout();\n t30login1();\n assertTrue(isPasswordExpired());\n PeopleInfoLine me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));\n t30chgpasswd();\n assertFalse(isPasswordExpired());\n me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));\n p_logout();\n t30login2();\n assertFalse(isPasswordExpired());\n t30chgpasswd2();\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"0\", 1);\n db.commit();\n } catch (Exception e) {\n e.printStackTrace();\n db.rollback();\n } finally {\n db.safeClose();\n }\n }\n", "label": 0} {"func1": " public boolean crear() {\n int result = 0;\n String sql = \"insert into jugador\" + \"(apellidoPaterno, apellidoMaterno, nombres, fechaNacimiento, pais, rating, sexo)\" + \"values (?, ?, ?, ?, ?, ?, ?)\";\n try {\n connection = conexionBD.getConnection();\n connection.setAutoCommit(false);\n ps = connection.prepareStatement(sql);\n populatePreparedStatement(elJugador);\n result = ps.executeUpdate();\n connection.commit();\n } catch (SQLException ex) {\n ex.printStackTrace();\n try {\n connection.rollback();\n } catch (SQLException exe) {\n exe.printStackTrace();\n }\n } finally {\n conexionBD.close(ps);\n conexionBD.close(connection);\n }\n return (result > 0);\n }\n", "func2": " private static final String hash(String input, String algorithm) {\n try {\n MessageDigest dig = MessageDigest.getInstance(algorithm);\n dig.update(input.getBytes());\n StringBuffer result = new StringBuffer();\n byte[] digest = dig.digest();\n String[] hex = { \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\" };\n for (int i = 0; i < digest.length; i++) {\n int u = digest[i];\n u &= 0x000000FF;\n int highCount = u / 16;\n int lowCount = u - (highCount * 16);\n result.append(hex[highCount]);\n result.append(hex[lowCount]);\n }\n return result.toString();\n } catch (NoSuchAlgorithmException e) {\n return null;\n }\n }\n", "label": 0} {"func1": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error: \" + e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n System.out.println(\"Error:\" + e);\n }\n }\n", "func2": " public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {\n HttpURLConnection con = null;\n InputStream is = null;\n try {\n URL u = new URL(url);\n if (url.startsWith(\"file://\")) {\n is = new BufferedInputStream(u.openStream());\n } else {\n Proxy proxy;\n if (proxyHost != null) {\n proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));\n } else {\n proxy = Proxy.NO_PROXY;\n }\n con = (HttpURLConnection) u.openConnection(proxy);\n con.addRequestProperty(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\");\n con.addRequestProperty(\"Accept-Charset\", \"UTF-8\");\n con.addRequestProperty(\"Accept-Language\", \"en-US,en\");\n con.addRequestProperty(\"Accept\", \"text/html,image/*\");\n con.setDoInput(true);\n con.setDoOutput(false);\n con.connect();\n is = new BufferedInputStream(con.getInputStream());\n }\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(is, baos);\n return baos.toByteArray();\n } finally {\n IOUtils.closeQuietly(is);\n if (con != null) {\n con.disconnect();\n }\n }\n }\n", "label": 0} {"func1": " public static void copy(String fileFrom, String fileTo) throws IOException {\n FileInputStream inputStream = null;\n FileOutputStream outputStream = null;\n FileChannel inputChannel = null;\n FileChannel outputChannel = null;\n try {\n inputStream = new FileInputStream(fileFrom);\n outputStream = new FileOutputStream(fileTo);\n inputChannel = inputStream.getChannel();\n outputChannel = outputStream.getChannel();\n inputChannel.transferTo(0, inputChannel.size(), outputChannel);\n } finally {\n try {\n inputChannel.close();\n } finally {\n try {\n outputChannel.close();\n } finally {\n try {\n inputStream.close();\n } finally {\n outputStream.close();\n }\n }\n }\n }\n }\n", "func2": " public String encrypt(String password) throws Exception {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(password.getBytes());\n BigInteger hash = new BigInteger(1, md5.digest());\n String hashword = hash.toString(16);\n return hashword;\n }\n", "label": 0} {"func1": " @SuppressWarnings(\"unchecked\")\n private ReaderFeed processEntrys(String urlStr, String currentFlag) throws UnsupportedEncodingException, IOException, JDOMException {\n String key = \"processEntrys@\" + urlStr + \"_\" + currentFlag;\n if (cache.containsKey(key)) {\n return (ReaderFeed) cache.get(key);\n }\n List postList = new ArrayList();\n URL url = new URL(urlStr);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Cookie\", \"SID=\" + sid);\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), \"UTF-8\"));\n SAXBuilder builder = new SAXBuilder(false);\n Document doc = builder.build(reader);\n Element root = doc.getRootElement();\n Namespace grNamespace = root.getNamespace(\"gr\");\n Namespace namespace = root.getNamespace();\n String newflag = root.getChildText(\"continuation\", grNamespace);\n String title = root.getChildText(\"title\", namespace);\n String subTitle = root.getChildText(\"subtitle\", namespace);\n List entryList = root.getChildren(\"entry\", namespace);\n DateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n for (Element e : entryList) {\n Post post = new Post();\n post.setTitle(e.getChildText(\"title\", namespace));\n try {\n post.setDate(sdf.parse(e.getChildText(\"published\", namespace)));\n } catch (ParseException e1) {\n }\n post.setUrl(e.getChild(\"link\", namespace).getAttributeValue(\"href\"));\n post.setSauthor(e.getChild(\"author\", namespace).getChildText(\"name\", namespace));\n String content = e.getChildText(\"content\", namespace);\n if (StringUtils.isEmpty(content)) {\n content = e.getChildText(\"description\", namespace);\n }\n if (StringUtils.isEmpty(content)) {\n content = e.getChildText(\"summary\", namespace);\n }\n post.setContent(content);\n postList.add(post);\n }\n ReaderFeed readerFeed = new ReaderFeed();\n readerFeed.setTitle(title);\n readerFeed.setSubTitle(subTitle);\n readerFeed.setFlag(newflag);\n readerFeed.setPostList(postList);\n cache.put(key, readerFeed);\n return readerFeed;\n }\n", "func2": " public void test() throws Exception {\n StorageStringWriter s = new StorageStringWriter(2048, \"UTF-8\");\n s.addText(\"Test\");\n try {\n s.getOutputStream();\n fail(\"Should throw IOException as method not supported.\");\n } catch (IOException e) {\n }\n s.getWriter().write(\"ing is important\");\n s.close(ResponseStateOk.getInstance());\n assertEquals(\"Testing is important\", s.getText());\n InputStream input = s.getInputStream();\n StringWriter writer = new StringWriter();\n IOUtils.copy(input, writer, \"UTF-8\");\n assertEquals(\"Testing is important\", writer.toString());\n try {\n s.getWriter();\n fail(\"Should throw IOException as storage is closed.\");\n } catch (IOException e) {\n }\n }\n", "label": 0} {"func1": " protected String getRequestContent(String urlText) throws Exception {\n URL url = new URL(urlText);\n HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();\n urlcon.connect();\n BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));\n String line = reader.readLine();\n reader.close();\n urlcon.disconnect();\n return line;\n }\n", "func2": " public void copyLogic() {\n if (getState() == States.Idle) {\n setState(States.Synchronizing);\n try {\n FileChannel sourceChannel = new FileInputStream(new File(_properties.getProperty(\"binPath\") + name + \".class\")).getChannel();\n FileChannel destinationChannel = new FileOutputStream(new File(_properties.getProperty(\"agentFileLocation\") + name + \".class\")).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n setState(States.Idle);\n }\n }\n", "label": 0} {"func1": " public Configuration(URL url) {\n InputStream in = null;\n try {\n load(in = url.openStream());\n } catch (Exception e) {\n throw new RuntimeException(\"Could not load configuration from \" + url, e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException ignore) {\n }\n }\n }\n }\n", "func2": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n System.err.println(\"Failed to load the MD5 MessageDigest. \" + \"unable to function normally.\");\n nsae.printStackTrace();\n }\n }\n digest.update(data.getBytes());\n return encodeHex(digest.digest());\n }\n", "label": 0} {"func1": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "func2": " private String copyImageFile(String urlString, String filePath) {\n FileOutputStream destination = null;\n File destination_file = null;\n String inLine;\n String dest_name = \"\";\n byte[] buffer;\n int bytes_read;\n int last_offset = 0;\n int offset = 0;\n InputStream imageFile = null;\n try {\n URL url = new URL(urlString);\n imageFile = url.openStream();\n dest_name = url.getFile();\n offset = 0;\n last_offset = 0;\n offset = dest_name.indexOf('/', offset + 1);\n while (offset > -1) {\n last_offset = offset + 1;\n offset = dest_name.indexOf('/', offset + 1);\n }\n dest_name = filePath + File.separator + dest_name.substring(last_offset);\n destination_file = new File(dest_name);\n if (destination_file.exists()) {\n if (destination_file.isFile()) {\n if (!destination_file.canWrite()) {\n System.out.println(\"FileCopy: destination \" + \"file is unwriteable: \" + dest_name);\n }\n System.out.println(\"File \" + dest_name + \" already exists. File will be overwritten.\");\n } else {\n System.out.println(\"FileCopy: destination \" + \"is not a file: \" + dest_name);\n }\n } else {\n File parentdir = parent(destination_file);\n if (!parentdir.exists()) {\n System.out.println(\"FileCopy: destination \" + \"directory doesn't exist: \" + dest_name);\n }\n if (!parentdir.canWrite()) {\n System.out.println(\"FileCopy: destination \" + \"directory is unwriteable: \" + dest_name);\n }\n }\n destination = new FileOutputStream(dest_name);\n buffer = new byte[1024];\n while (true) {\n bytes_read = imageFile.read(buffer);\n if (bytes_read == -1) break;\n destination.write(buffer, 0, bytes_read);\n }\n } catch (MalformedURLException ex) {\n System.out.println(\"Bad URL \" + urlString);\n } catch (IOException ex) {\n System.out.println(\" IO error: \" + ex.getMessage());\n } finally {\n if (imageFile != null) {\n try {\n imageFile.close();\n } catch (IOException e) {\n }\n }\n if (destination != null) {\n try {\n destination.close();\n } catch (IOException e) {\n }\n }\n }\n return (dest_name);\n }\n", "label": 0} {"func1": " public static String encrypt(String text) {\n char[] toEncrypt = text.toCharArray();\n StringBuffer hexString = new StringBuffer();\n try {\n MessageDigest dig = MessageDigest.getInstance(\"MD5\");\n dig.reset();\n String pw = \"\";\n for (int i = 0; i < toEncrypt.length; i++) {\n pw += toEncrypt[i];\n }\n dig.update(pw.getBytes());\n byte[] digest = dig.digest();\n int digestLength = digest.length;\n for (int i = 0; i < digestLength; i++) {\n hexString.append(hexDigit(digest[i]));\n }\n } catch (java.security.NoSuchAlgorithmException ae) {\n ae.printStackTrace();\n }\n return hexString.toString();\n }\n", "func2": " public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {\n File dest = new File(this.getRealFile(), name);\n LOGGER.debug(\"PUT?? - real file: \" + this.getRealFile() + \",name: \" + name);\n if (isOwner) {\n if (!\".request\".equals(name) && !\".tokens\".equals(name)) {\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n } else {\n if (ServerConfiguration.isDynamicSEL()) {\n } else {\n }\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n }\n return factory.resolveFile(this.host, dest);\n } else {\n LOGGER.error(\"User isn't owner of this folder\");\n return null;\n }\n }\n", "label": 0} {"func1": " @Override\n public InputStream getResourceByClassName(String className) {\n URL url = resourceFetcher.getResource(\"/fisce_scripts/\" + className + \".class\");\n if (url == null) {\n return null;\n } else {\n try {\n return url.openStream();\n } catch (IOException e) {\n return null;\n }\n }\n }\n", "func2": " protected BufferedImage handleFCLAException() {\n if (params.uri.startsWith(\"http://image11.fcla.edu/cgi\")) try {\n params.uri = params.uri.substring(params.uri.indexOf(\"q1=\") + 3);\n params.uri = params.uri.substring(0, params.uri.indexOf(\"&\"));\n params.uri = \"http://image11.fcla.edu/m/map/thumb/\" + params.uri.substring(params.uri.length() - 3, params.uri.length() - 2) + \"/\" + params.uri.substring(params.uri.length() - 2, params.uri.length() - 1) + \"/\" + params.uri.substring(params.uri.length() - 1, params.uri.length()) + \"/\" + params.uri + \".jpg\";\n URL url = new URL(params.uri);\n URLConnection connection = url.openConnection();\n return processNewUri(connection);\n } catch (Exception e) {\n }\n return null;\n }\n", "label": 0} {"func1": " public static void copyFile(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " private boolean getWave(String url, String Word) {\n try {\n File FF = new File(f.getParent() + \"/\" + f.getName() + \"pron\");\n FF.mkdir();\n URL url2 = new URL(url);\n BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));\n File Fdel = new File(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n if (!Fdel.exists()) {\n FileOutputStream outstream = new FileOutputStream(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));\n char[] binput = new char[1024];\n int len = stream.read(binput, 0, 1024);\n while (len > 0) {\n bwriter.write(binput, 0, len);\n len = stream.read(binput, 0, 1024);\n }\n bwriter.close();\n outstream.close();\n }\n stream.close();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " public static String hashPasswordForOldMD5(String password) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(password.getBytes(\"UTF-8\"));\n byte messageDigest[] = md.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n String hex = Integer.toHexString(0xFF & messageDigest[i]);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException nsae) {\n throw new IllegalStateException(nsae.getMessage());\n } catch (UnsupportedEncodingException uee) {\n throw new IllegalStateException(uee.getMessage());\n }\n }\n", "func2": " public void testCodingEmptyFile() throws Exception {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n WritableByteChannel channel = newChannel(baos);\n HttpParams params = new BasicHttpParams();\n SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);\n HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();\n LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);\n encoder.write(wrap(\"stuff;\"));\n File tmpFile = File.createTempFile(\"testFile\", \"txt\");\n FileOutputStream fout = new FileOutputStream(tmpFile);\n OutputStreamWriter wrtout = new OutputStreamWriter(fout);\n wrtout.flush();\n wrtout.close();\n FileChannel fchannel = new FileInputStream(tmpFile).getChannel();\n encoder.transfer(fchannel, 0, 20);\n encoder.write(wrap(\"more stuff\"));\n String s = baos.toString(\"US-ASCII\");\n assertTrue(encoder.isCompleted());\n assertEquals(\"stuff;more stuff\", s);\n tmpFile.delete();\n }\n", "label": 0} {"func1": " public static GameRecord[] get(String url, float lat, float lon, int count) {\n try {\n HttpURLConnection req = (HttpURLConnection) new URL(url).openConnection();\n req.setRequestMethod(\"GET\");\n req.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat));\n req.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon));\n req.setRequestProperty(\"X-GameQueryCount\", String.valueOf(count));\n req.connect();\n if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {\n List gl = new ArrayList();\n BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));\n String line;\n while ((line = br.readLine()) != null) {\n if (!line.startsWith(\"#\")) {\n gl.add(GameRecord.decode(line));\n }\n }\n return gl.toArray(new GameRecord[gl.size()]);\n } else {\n System.out.println(req.getResponseMessage());\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 0} {"func1": " public boolean connect() {\n boolean isConnected = false;\n try {\n try {\n this.ftpClient.connect(this.server, this.port);\n } catch (SocketException e) {\n status = ErrorResult.CONNECTNOTPOSSIBLE.code;\n return false;\n } catch (IOException e) {\n status = ErrorResult.CONNECTNOTPOSSIBLE.code;\n return false;\n }\n int reply = this.ftpClient.getReplyCode();\n if (!FTPReply.isPositiveCompletion(reply)) {\n this.disconnect();\n status = ErrorResult.CONNECTNOTCORRECT.code;\n return false;\n }\n try {\n if (this.account == null) {\n if (!this.ftpClient.login(this.username, this.passwd)) {\n status = ErrorResult.LOGINNOTCORRECT.code;\n this.ftpClient.logout();\n return false;\n }\n } else if (!this.ftpClient.login(this.username, this.passwd, this.account)) {\n status = ErrorResult.LOGINACCTNOTCORRECT.code;\n this.ftpClient.logout();\n return false;\n }\n } catch (IOException e) {\n status = ErrorResult.ERRORWHILECONNECT.code;\n try {\n this.ftpClient.logout();\n } catch (IOException e1) {\n }\n return false;\n }\n isConnected = true;\n return true;\n } finally {\n if ((!isConnected) && this.ftpClient.isConnected()) {\n this.disconnect();\n }\n }\n }\n", "func2": " private void redirect(TargetApp app, HttpServletRequest request, HttpServletResponse response) throws IOException {\n URL url = new URL(app.getUrl() + request.getRequestURI());\n s_log.debug(\"Redirecting to \" + url);\n URLConnection urlConnection = url.openConnection();\n Map> fields = urlConnection.getHeaderFields();\n for (String key : fields.keySet()) {\n StringBuffer values = new StringBuffer();\n boolean comma = false;\n for (String value : fields.get(key)) {\n if (comma) {\n values.append(\", \");\n }\n values.append(value);\n comma = true;\n }\n if (key != null) {\n response.setHeader(key, values.toString());\n } else {\n response.setStatus(Integer.parseInt(values.toString().split(\" \")[1]));\n }\n }\n InputStream in = urlConnection.getInputStream();\n try {\n ServletOutputStream out = response.getOutputStream();\n byte[] buff = new byte[1024];\n int len;\n while ((len = in.read(buff)) != -1) {\n out.write(buff, 0, len);\n }\n } finally {\n in.close();\n }\n }\n", "label": 0} {"func1": " protected static void copyDeleting(File source, File dest) throws IOException {\n byte[] buf = new byte[8 * 1024];\n FileInputStream in = new FileInputStream(source);\n try {\n FileOutputStream out = new FileOutputStream(dest);\n try {\n int count;\n while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);\n } finally {\n out.close();\n }\n } finally {\n in.close();\n }\n }\n", "func2": " public static byte[] encrypt(String x) throws Exception {\n java.security.MessageDigest d = null;\n d = java.security.MessageDigest.getInstance(\"SHA-1\");\n d.reset();\n d.update(x.getBytes());\n return d.digest();\n }\n", "label": 0} {"func1": " ClassFile getClassFile(String name) throws IOException, ConstantPoolException {\n URL url = getClass().getResource(name);\n InputStream in = url.openStream();\n try {\n return ClassFile.read(in);\n } finally {\n in.close();\n }\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 0} {"func1": " private InputStream openRemoteStream(String remoteURL, String pathSuffix) {\n URL url;\n InputStream in = null;\n try {\n url = new URL(remoteURL + pathSuffix);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n in = connection.getInputStream();\n } catch (Exception e) {\n }\n return in;\n }\n", "func2": " public synchronized String encryptPassword(String passwordString) throws Exception {\n MessageDigest digest = null;\n digest = MessageDigest.getInstance(\"SHA\");\n digest.update(passwordString.getBytes(\"UTF-8\"));\n byte raw[] = digest.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "label": 0} {"func1": " @Override\n public void respondGet(HttpServletResponse resp) throws IOException {\n setHeaders(resp);\n final OutputStream os;\n if (willDeflate()) {\n resp.setHeader(\"Content-Encoding\", \"gzip\");\n os = new GZIPOutputStream(resp.getOutputStream(), bufferSize);\n } else os = resp.getOutputStream();\n transferStreams(url.openStream(), os);\n }\n", "func2": " @Override\n public Cal3dModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {\n boolean baseURLWasNull = setBaseURLFromModelURL(url);\n Cal3dModel model = new Cal3dModel(getFlags());\n loadCal3dModel(getBaseURL(), url.toExternalForm(), new InputStreamReader(url.openStream()), model);\n if (baseURLWasNull) {\n popBaseURL();\n }\n return (model);\n }\n", "label": 0} {"func1": " @Override\n public void makeRead(final String user, final long databaseID, final long time) throws SQLException {\n final String query = \"insert into fs.read_post (post, user, read_date) values (?, ?, ?)\";\n ensureConnection();\n final PreparedStatement statement = m_connection.prepareStatement(query);\n try {\n statement.setLong(1, databaseID);\n statement.setString(2, user);\n statement.setTimestamp(3, new Timestamp(time));\n final int count = statement.executeUpdate();\n if (0 == count) {\n throw new SQLException(\"Nothing updated.\");\n }\n m_connection.commit();\n } catch (final SQLException e) {\n m_connection.rollback();\n throw e;\n } finally {\n statement.close();\n }\n }\n", "func2": " private void displayDiffResults() throws IOException {\n File outFile = File.createTempFile(\"diff\", \".htm\");\n outFile.deleteOnExit();\n FileOutputStream outStream = new FileOutputStream(outFile);\n BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream));\n out.write(\"LOC Differences\\n\" + SCRIPT + \"\\n\" + \"\\n\" + \"
\\n\");\n if (addedTable.length() > 0) {\n out.write(\"\" + \"\");\n out.write(addedTable.toString());\n out.write(\"
Files Added:AddType


\");\n }\n if (modifiedTable.length() > 0) {\n out.write(\"\" + \"\" + \"\");\n out.write(modifiedTable.toString());\n out.write(\"
Files Modified:BaseDelModAddTotalType


\");\n }\n if (deletedTable.length() > 0) {\n out.write(\"\" + \"\");\n out.write(deletedTable.toString());\n out.write(\"
Files Deleted:DelType


\");\n }\n out.write(\"\\n\");\n if (modifiedTable.length() > 0 || deletedTable.length() > 0) {\n out.write(\"\\n\\n\\n\\n\\n\");\n }\n out.write(\"\\n
Base: \");\n out.write(Long.toString(base));\n out.write(\"
Deleted: \");\n out.write(Long.toString(deleted));\n out.write(\"
Modified: \");\n out.write(Long.toString(modified));\n out.write(\"
Added: \");\n out.write(Long.toString(added));\n out.write(\"
New & Changed: \");\n out.write(Long.toString(added + modified));\n out.write(\"
Total: \");\n out.write(Long.toString(total));\n out.write(\"
\");\n redlinesOut.close();\n out.flush();\n InputStream redlines = new FileInputStream(redlinesTempFile);\n byte[] buffer = new byte[4096];\n int bytesRead;\n while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);\n outStream.write(\"\".getBytes());\n outStream.close();\n Browser.launch(outFile.toURL().toString());\n }\n", "label": 0} {"func1": " private String getEncoding() throws IOException {\n BufferedReader reader = null;\n String encoding = null;\n try {\n URLConnection connection = url.openConnection();\n Map> header = connection.getHeaderFields();\n for (Map.Entry> entry : header.entrySet()) {\n if (entry.getKey().toLowerCase().equals(\"content-type\")) {\n String item = entry.getValue().toString().toLowerCase();\n if (item.contains(\"charset\")) {\n encoding = extractEncoding(item);\n if (encoding != null && !encoding.isEmpty()) return encoding;\n }\n }\n }\n reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.toLowerCase();\n if (line.contains(\"charset\") || line.contains(\"encoding\")) {\n encoding = extractEncoding(line);\n if (encoding != null && !encoding.isEmpty()) return encoding;\n }\n }\n return STANDARDENCODING;\n } finally {\n if (reader != null) reader.close();\n }\n }\n", "func2": " public static String md5(String message, boolean base64) {\n MessageDigest md5 = null;\n String digest = message;\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(message.getBytes());\n byte[] digestData = md5.digest();\n if (base64) {\n Base64Encoder enc = new Base64Encoder();\n enc.translate(digestData);\n digest = new String(enc.getCharArray());\n } else {\n digest = byteArrayToHex(digestData);\n }\n } catch (NoSuchAlgorithmException e) {\n LOG.warn(\"MD5 not supported. Using plain string as password!\");\n } catch (Exception e) {\n LOG.warn(\"Digest creation failed. Using plain string as password!\");\n }\n return digest;\n }\n", "label": 0} {"func1": " public static void copyOverWarFile() {\n System.out.println(\"Copy Over War File:\");\n File dir = new File(theAppsDataDir);\n FileFilter ff = new WildcardFileFilter(\"*.war\");\n if (dir.listFiles(ff).length == 0) {\n dir = new File(System.getProperty(\"user.dir\") + \"/war\");\n if (dir.exists()) {\n File[] files = dir.listFiles(ff);\n for (File f : files) {\n try {\n File newFile = new File(\"\" + theAppsDataDir + \"/\" + f.getName());\n System.out.println(\"Creating new file \\\"\" + f.getAbsolutePath() + \"\\\"\");\n newFile.createNewFile();\n InputStream fi = new FileInputStream(f);\n OutputStream fo = new FileOutputStream(newFile);\n IOUtils.copy(fi, fo);\n moveUnzipAndExtract(newFile);\n } catch (Exception ex) {\n Logger.getLogger(AppDataDir.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }\n } else {\n System.out.println(\"Found a war in the apps data dir, ignoring a fresh copy\");\n }\n new JFileChooser().setCurrentDirectory(new File(theAppsDataDir));\n System.setProperty(\"user.dir\", theAppsDataDir);\n System.out.println(\"User.dir : \" + System.getProperty(\"user.dir\"));\n }\n", "func2": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "label": 0} {"func1": " String runScript(String scriptName) {\n String data = \"\";\n try {\n URL url = new URL(getCodeBase().toString() + scriptName);\n InputStream in = url.openStream();\n BufferedInputStream buffIn = new BufferedInputStream(in);\n do {\n int temp = buffIn.read();\n if (temp == -1) break;\n data = data + (char) temp;\n } while (true);\n } catch (Exception e) {\n data = \"error!\";\n }\n return data;\n }\n", "func2": " private boolean getWave(String url, String Word) {\n try {\n File FF = new File(f.getParent() + \"/\" + f.getName() + \"pron\");\n FF.mkdir();\n URL url2 = new URL(url);\n BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));\n File Fdel = new File(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n if (!Fdel.exists()) {\n FileOutputStream outstream = new FileOutputStream(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));\n char[] binput = new char[1024];\n int len = stream.read(binput, 0, 1024);\n while (len > 0) {\n bwriter.write(binput, 0, len);\n len = stream.read(binput, 0, 1024);\n }\n bwriter.close();\n outstream.close();\n }\n stream.close();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " @Before\n public void setUp() throws Exception {\n connectionDigestHandler = new ConnectionDigestHandlerDefaultImpl();\n URL url = null;\n try {\n url = new URL(\"http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/64104-35000-204984-2890/webwork2guide.pdf\");\n } catch (MalformedURLException e) {\n e.printStackTrace();\n }\n try {\n uc = url.openConnection();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n", "func2": " @Test\n public void test02_ok() throws Exception {\n DefaultHttpClient client = new DefaultHttpClient();\n try {\n HttpPost post = new HttpPost(chartURL);\n List nameValuePairs = new ArrayList(1);\n nameValuePairs.add(new BasicNameValuePair(\"ws\", \"getDomainEvolution\"));\n nameValuePairs.add(new BasicNameValuePair(\"chartTitle\", \"test\"));\n nameValuePairs.add(new BasicNameValuePair(\"type\", \"chart\"));\n nameValuePairs.add(new BasicNameValuePair(\"firstDate\", \"20111124\"));\n nameValuePairs.add(new BasicNameValuePair(\"lastDate\", \"20111125\"));\n nameValuePairs.add(new BasicNameValuePair(\"wsParams\", \"type,counting,protocol,unit,proxy,domain,timeScale,period\"));\n nameValuePairs.add(new BasicNameValuePair(\"wsParamsValues\", \"chart,volume,all,hits,all,google.com,day,360\"));\n nameValuePairs.add(new BasicNameValuePair(\"serieTitle\", \"serie\"));\n post.setEntity(new UrlEncodedFormEntity(nameValuePairs));\n HttpResponse response = client.execute(post);\n HttpEntity entity = response.getEntity();\n assertNotNull(entity);\n InputStream instream = entity.getContent();\n BufferedReader reader = new BufferedReader(new InputStreamReader(instream));\n System.out.println(reader.readLine());\n instream.close();\n assertEquals(\"error :\" + response.getStatusLine(), 200, response.getStatusLine().getStatusCode());\n } finally {\n client.getConnectionManager().shutdown();\n }\n }\n", "label": 0} {"func1": " private String unJar(String jarPath, String jarEntry) {\n String path;\n if (jarPath.lastIndexOf(\"lib/\") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf(\"lib/\")); else path = jarPath.substring(0, jarPath.lastIndexOf(\"/\"));\n String relPath = jarEntry.substring(0, jarEntry.lastIndexOf(\"/\"));\n try {\n new File(path + \"/\" + relPath).mkdirs();\n JarFile jar = new JarFile(jarPath);\n ZipEntry ze = jar.getEntry(jarEntry);\n File bin = new File(path + \"/\" + jarEntry);\n IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return path + \"/\" + jarEntry;\n }\n", "func2": " public void run() {\n URL url;\n try {\n url = new URL(\"http://localhost:8080/glowaxes/dailytrend.jsp\");\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n while ((str = in.readLine()) != null) {\n }\n in.close();\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n }\n }\n", "label": 0} {"func1": " public static void copyFile(File srcFile, File destFile) throws IOException {\n if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException(\"Source file doesn't exist: \" + srcFile.getAbsolutePath());\n if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException(\"Destination file is directory: \" + destFile.getAbsolutePath());\n FileInputStream in = new FileInputStream(srcFile);\n FileOutputStream out = new FileOutputStream(destFile);\n byte[] buffer = new byte[4096];\n int no = 0;\n try {\n while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no);\n } finally {\n in.close();\n out.close();\n }\n }\n", "func2": " public static boolean loadContentFromURL(String fromURL, String toFile) {\n try {\n URL url = new URL(\"http://bible-desktop.com/xml\" + fromURL);\n File file = new File(toFile);\n URLConnection ucon = url.openConnection();\n InputStream is = ucon.getInputStream();\n BufferedInputStream bis = new BufferedInputStream(is);\n ByteArrayBuffer baf = new ByteArrayBuffer(50);\n int current = 0;\n while ((current = bis.read()) != -1) {\n baf.append((byte) current);\n }\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(baf.toByteArray());\n fos.close();\n } catch (IOException e) {\n Log.e(TAG, e);\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " public String readRemoteFile() throws IOException {\n String response = \"\";\n boolean eof = false;\n URL url = new URL(StaticData.remoteFile);\n InputStream is = url.openStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\n String s;\n s = br.readLine();\n response = s;\n while (!eof) {\n try {\n s = br.readLine();\n if (s == null) {\n eof = true;\n br.close();\n } else response += s;\n } catch (EOFException eo) {\n eof = true;\n } catch (IOException e) {\n System.out.println(\"IO Error : \" + e.getMessage());\n }\n }\n return response;\n }\n", "func2": " public static String encrypt(String text) throws NoSuchAlgorithmException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n try {\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "label": 0} {"func1": " protected int deleteBitstreamInfo(int id, Connection conn) {\n PreparedStatement stmt = null;\n int numDeleted = 0;\n try {\n stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO);\n stmt.setInt(1, id);\n numDeleted = stmt.executeUpdate();\n if (numDeleted > 1) {\n conn.rollback();\n throw new IllegalStateException(\"Too many rows deleted! Number of rows deleted: \" + numDeleted + \" only one row should be deleted for bitstream id \" + id);\n }\n } catch (SQLException e) {\n LOG.error(\"Problem deleting bitstream. \" + e.getMessage(), e);\n throw new RuntimeException(\"Problem deleting bitstream. \" + e.getMessage(), e);\n } finally {\n cleanup(stmt);\n }\n return numDeleted;\n }\n", "func2": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 0} {"func1": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "func2": " @Override\n public Content getContent(Object principal, ContentPath path, Version version, Map properties) throws ContentException {\n String uniqueName = path.getBaseName();\n URL url = buildURL(uniqueName);\n URLContent content = new URLContent(url, this.getName(), uniqueName);\n content.setUniqueName(uniqueName);\n content.setReadable(true);\n content.setWritable(writable);\n content.setExists(true);\n try {\n URLConnection connection = url.openConnection();\n String mimeType = connection.getContentType();\n content.setMimeType(mimeType);\n content.setWritable(true);\n } catch (IOException ex) {\n throw new ContentException(\"unable to obtain mime type of \" + url, ex);\n }\n return content;\n }\n", "label": 0} {"func1": " public static void fileDownload(String fAddress, String destinationDir) {\n int slashIndex = fAddress.lastIndexOf('/');\n int periodIndex = fAddress.lastIndexOf('.');\n String fileName = fAddress.substring(slashIndex + 1);\n URL url;\n try {\n url = new URL(fAddress);\n URLConnection uc = url.openConnection();\n BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));\n File file = new File(destinationDir + \"/download.pdf\");\n FileOutputStream fos = new FileOutputStream(file);\n BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));\n int inputLine;\n while ((inputLine = in.read()) != -1) out.write(inputLine);\n in.close();\n } catch (Exception ex) {\n Logger.getLogger(UrlDownload.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n", "func2": " public void testHttpsConnection_Not_Found_Response() throws Throwable {\n setUpStoreProperties();\n try {\n SSLContext ctx = getContext();\n ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);\n TestHostnameVerifier hnv = new TestHostnameVerifier();\n HttpsURLConnection.setDefaultHostnameVerifier(hnv);\n URL url = new URL(\"https://localhost:\" + ss.getLocalPort());\n HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\n try {\n doInteraction(connection, ss, NOT_FOUND_CODE);\n fail(\"Expected exception was not thrown.\");\n } catch (FileNotFoundException e) {\n if (DO_LOG) {\n System.out.println(\"Expected exception was thrown: \" + e.getMessage());\n }\n }\n connection.connect();\n } finally {\n tearDownStoreProperties();\n }\n }\n", "label": 0} {"func1": " public static int[] sortAscending(float input[]) {\n int[] order = new int[input.length];\n for (int i = 0; i < order.length; i++) order[i] = i;\n for (int i = input.length; --i >= 0; ) {\n for (int j = 0; j < i; j++) {\n if (input[j] > input[j + 1]) {\n float mem = input[j];\n input[j] = input[j + 1];\n input[j + 1] = mem;\n int id = order[j];\n order[j] = order[j + 1];\n order[j + 1] = id;\n }\n }\n }\n return order;\n }\n", "func2": " public void write() throws IOException {\n JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);\n if (includeJars != null) {\n HashSet allEntries = new HashSet(includeJars);\n if (!ignoreDependencies) expandSet(allEntries);\n for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {\n JarFile jar = getJarFile(iterator.next());\n Enumeration jarEntries = jar.entries();\n while (jarEntries.hasMoreElements()) {\n ZipEntry o1 = (ZipEntry) jarEntries.nextElement();\n if (o1.getName().equalsIgnoreCase(\"META-INF/MANIFEST.MF\") || o1.getSize() <= 0) continue;\n jarOut.putNextEntry(o1);\n InputStream entryStream = jar.getInputStream(o1);\n IOUtils.copy(entryStream, jarOut);\n jarOut.closeEntry();\n }\n }\n }\n jarOut.finish();\n jarOut.close();\n }\n", "label": 0} {"func1": " public static String fetchUrl(String urlString) {\n try {\n URL url = new URL(urlString);\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n String line = null;\n StringBuilder builder = new StringBuilder();\n while ((line = reader.readLine()) != null) {\n builder.append(line);\n }\n reader.close();\n return builder.toString();\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n }\n return \"\";\n }\n", "func2": " private String digest(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[64];\n md.update(input.getBytes(\"iso-8859-1\"), 0, input.length());\n md5hash = md.digest();\n return this.convertToHex(md5hash);\n }\n", "label": 0} {"func1": " private void doFinishLoadAttachment(long attachmentId) {\n if (attachmentId != mLoadAttachmentId) {\n return;\n }\n Attachment attachment = Attachment.restoreAttachmentWithId(MessageView.this, attachmentId);\n Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);\n Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(getContentResolver(), attachmentUri);\n if (mLoadAttachmentSave) {\n try {\n File file = createUniqueFile(Environment.getExternalStorageDirectory(), attachment.mFileName);\n InputStream in = getContentResolver().openInputStream(contentUri);\n OutputStream out = new FileOutputStream(file);\n IOUtils.copy(in, out);\n out.flush();\n out.close();\n in.close();\n Toast.makeText(MessageView.this, String.format(getString(R.string.message_view_status_attachment_saved), file.getName()), Toast.LENGTH_LONG).show();\n new MediaScannerNotifier(this, file, mHandler);\n } catch (IOException ioe) {\n Toast.makeText(MessageView.this, getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show();\n }\n } else {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(contentUri);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n startActivity(intent);\n } catch (ActivityNotFoundException e) {\n mHandler.attachmentViewError();\n }\n }\n }\n", "func2": " public static String getHashedPassword(String password) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n digest.update(password.getBytes());\n BigInteger hashedInt = new BigInteger(1, digest.digest());\n return String.format(\"%1$032X\", hashedInt);\n } catch (NoSuchAlgorithmException nsae) {\n System.err.println(nsae.getMessage());\n }\n return \"\";\n }\n", "label": 0} {"func1": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String senha = \"\";\n String email = request.getParameter(\"EmailLogin\");\n try {\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(request.getParameter(\"SenhaLogin\").getBytes(), 0, request.getParameter(\"SenhaLogin\").length());\n senha = new BigInteger(1, messageDigest.digest()).toString(16);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);\n String redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"?&msg=3\";\n if (request.getHeader(\"REFERER\").indexOf(\"?\") != -1) {\n redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"&msg=3\";\n }\n if (usuario.getNome() != null) {\n HttpSession session = request.getSession();\n session.setAttribute(\"usuario\", usuario);\n redirect = \"index.jsp\";\n }\n response.sendRedirect(redirect);\n }\n", "func2": " public void run(String[] args) throws Throwable {\n FileInputStream input = new FileInputStream(args[0]);\n FileOutputStream output = new FileOutputStream(args[0] + \".out\");\n Reader reader = $(Reader.class, $declass(input));\n Writer writer = $(Writer.class, $declass(output));\n Pump pump;\n if (args.length > 1 && \"diag\".equals(args[1])) {\n pump = $(new Reader() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public int read(byte[] buffer, int off, int len) throws Exception {\n Integer rd = (Integer) $next();\n if (rd > 0) {\n counter += rd;\n }\n return 0;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Read from input \" + counter + \" bytes.\");\n }\n }, reader, writer, new Writer() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void write(byte[] buffer, int off, int len) throws Exception {\n counter += len;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Written to output \" + counter + \" bytes.\");\n }\n });\n } else {\n pump = $(reader, writer);\n }\n pump.pump();\n }\n", "label": 0} {"func1": " public static void main(String args[]) {\n int temp;\n int[] a1 = { 6, 2, -3, 7, -1, 8, 9, 0 };\n for (int j = 0; j < (a1.length * a1.length); j++) {\n for (int i = 0; i < a1.length - 1; i++) {\n if (a1[i] > a1[i + 1]) {\n temp = a1[i];\n a1[i] = a1[i + 1];\n a1[i + 1] = temp;\n }\n }\n }\n for (int i = 0; i < a1.length; i++) {\n System.out.print(\" \" + a1[i]);\n }\n }\n", "func2": " private String getFullScreenUrl() {\n progressDown.setIndeterminate(true);\n System.out.println(\"Har: \" + ytUrl);\n String u = ytUrl;\n URLConnection conn = null;\n String line = null;\n String data = \"\";\n String fullUrl = \"\";\n try {\n URL url = new URL(u);\n conn = url.openConnection();\n conn.setDoOutput(true);\n BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n while ((line = rd.readLine()) != null) {\n if (line.contains(\"fullscreenUrl\")) {\n data = line.trim();\n }\n }\n rd.close();\n System.out.println(data);\n int start = 0;\n String[] lines = data.split(\"&\");\n String[] tmp = null;\n String video_id = null;\n String t = null;\n String title = null;\n for (int i = 0; i < lines.length; i++) {\n if (lines[i].startsWith(\"video_id=\")) {\n tmp = lines[i].split(\"=\");\n video_id = tmp[1];\n }\n if (lines[i].startsWith(\"t=\")) {\n tmp = lines[i].split(\"=\");\n t = tmp[1];\n }\n if (lines[i].startsWith(\"title=\")) {\n tmp = lines[i].split(\"=\");\n title = tmp[1].substring(0, (tmp[1].length() - 2));\n }\n System.out.println(lines[i]);\n }\n System.out.println(\"So we got...\");\n System.out.println(\"video_id: \" + video_id);\n System.out.println(\"t: \" + t);\n System.out.println(\"title: \" + title);\n ytTitle = title;\n fullUrl = \"http://www.youtube.com/get_video.php?video_id=\" + video_id + \"&t=\" + t;\n } catch (Exception e) {\n System.err.println(\"Error: \" + e.getLocalizedMessage());\n }\n progressDown.setIndeterminate(false);\n return fullUrl;\n }\n", "label": 0} {"func1": " public static final void main(String[] args) throws Exception {\n HttpClient httpclient = new DefaultHttpClient();\n HttpGet httpget = new HttpGet(\"http://www.apache.org/\");\n System.out.println(\"executing request \" + httpget.getURI());\n HttpResponse response = httpclient.execute(httpget);\n HttpEntity entity = response.getEntity();\n System.out.println(\"----------------------------------------\");\n System.out.println(response.getStatusLine());\n if (entity != null) {\n System.out.println(\"Response content length: \" + entity.getContentLength());\n }\n System.out.println(\"----------------------------------------\");\n httpget.abort();\n }\n", "func2": " public void run() {\n BufferedReader reader = null;\n String message = null;\n int messageStyle = SWT.ICON_WARNING;\n try {\n URL url = new URL(Version.LATEST_VERSION_URL);\n URLConnection conn = url.openConnection();\n reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n String latestVersion = reader.readLine();\n latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);\n if (!Version.getVersion().equals(latestVersion)) {\n message = Labels.getLabel(\"text.version.old\");\n message = message.replaceFirst(\"%LATEST\", latestVersion);\n message = message.replaceFirst(\"%VERSION\", Version.getVersion());\n messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;\n } else {\n message = Labels.getLabel(\"text.version.latest\");\n messageStyle = SWT.ICON_INFORMATION;\n }\n } catch (Exception e) {\n message = Labels.getLabel(\"exception.UserErrorException.version.latestFailed\");\n Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);\n } finally {\n try {\n if (reader != null) reader.close();\n } catch (IOException e) {\n }\n final String messageToShow = message;\n final int messageStyleToShow = messageStyle;\n Display.getDefault().asyncExec(new Runnable() {\n\n public void run() {\n statusBar.setStatusText(null);\n MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);\n messageBox.setText(Version.getFullName());\n messageBox.setMessage(messageToShow);\n if (messageBox.open() == SWT.YES) {\n BrowserLauncher.openURL(Version.DOWNLOAD_URL);\n }\n }\n });\n }\n }\n", "label": 0} {"func1": " public String readPage(boolean ignoreComments) throws Exception {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n String inputLine;\n String html = \"\";\n if (ignoreComments) {\n while ((inputLine = in.readLine()) != null) {\n if (inputLine.length() > 0) {\n if (inputLine.substring(0, 1).compareTo(\"#\") != 0) {\n html = html + inputLine + \"\\n\";\n }\n }\n }\n } else {\n while ((inputLine = in.readLine()) != null) {\n html = html + inputLine + \"\\n\";\n }\n }\n in.close();\n return html;\n }\n", "func2": " private String encode(String plaintext) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA\");\n md.update(plaintext.getBytes(\"UTF-8\"));\n byte raw[] = md.digest();\n return (new BASE64Encoder()).encode(raw);\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(\"Error encoding: \" + e);\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"Error encoding: \" + e);\n }\n }\n", "label": 0} {"func1": " public static Body decodeBody(InputStream in, String contentTransferEncoding) throws IOException {\n if (contentTransferEncoding != null) {\n contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null);\n if (\"quoted-printable\".equalsIgnoreCase(contentTransferEncoding)) {\n in = new QuotedPrintableInputStream(in);\n } else if (\"base64\".equalsIgnoreCase(contentTransferEncoding)) {\n in = new Base64InputStream(in);\n }\n }\n BinaryTempFileBody tempBody = new BinaryTempFileBody();\n OutputStream out = tempBody.getOutputStream();\n IOUtils.copy(in, out);\n out.close();\n return tempBody;\n }\n", "func2": " public void googleImageSearch(String search, String start) {\n try {\n String u = \"http://images.google.com/images?q=\" + search + start;\n if (u.contains(\" \")) {\n u = u.replace(\" \", \"+\");\n }\n URL url = new URL(u);\n HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();\n httpcon.addRequestProperty(\"User-Agent\", \"Mozilla/4.76\");\n BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));\n googleImages.clear();\n String text = \"\";\n String lin = \"\";\n while ((lin = readIn.readLine()) != null) {\n text += lin;\n }\n readIn.close();\n if (text.contains(\"\\n\")) {\n text = text.replace(\"\\n\", \"\");\n }\n String[] array = text.split(\"\\\\Qhref=\\\"/imgres?imgurl=\\\\E\");\n for (String s : array) {\n if (s.startsWith(\"http://\") || s.startsWith(\"https://\") && s.contains(\"&\")) {\n String s1 = s.substring(0, s.indexOf(\"&\"));\n googleImages.add(s1);\n }\n }\n } catch (Exception ex4) {\n MusicBoxView.showErrorDialog(ex4);\n }\n MusicBoxView.jButton7.setEnabled(true);\n ImageIcon icon;\n try {\n icon = new ImageIcon(new URL(googleImages.elementAt(MusicBoxView.googleImageLocation)));\n ImageIcon ico = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH));\n MusicBoxView.albumArtLabel.setIcon(ico);\n } catch (MalformedURLException ex1) {\n MusicBoxView.showErrorDialog(ex1);\n }\n }\n", "label": 0} {"func1": " public static void fileUpload() throws IOException {\n HttpClient httpclient = new DefaultHttpClient();\n httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);\n HttpPost httppost = new HttpPost(postURL);\n File file = new File(\"d:/hai.html\");\n System.out.println(ukeycookie);\n httppost.setHeader(\"Cookie\", ukeycookie + \";\" + skeycookie + \";\" + usercookie);\n MultipartEntity mpEntity = new MultipartEntity();\n ContentBody cbFile = new FileBody(file);\n mpEntity.addPart(\"\", cbFile);\n httppost.setEntity(mpEntity);\n System.out.println(\"Now uploading your file into mediafire...........................\");\n HttpResponse response = httpclient.execute(httppost);\n HttpEntity resEntity = response.getEntity();\n System.out.println(response.getStatusLine());\n if (resEntity != null) {\n System.out.println(\"Getting upload response key value..........\");\n uploadresponsekey = EntityUtils.toString(resEntity);\n getUploadResponseKey();\n System.out.println(\"upload resoponse key \" + uploadresponsekey);\n }\n }\n", "func2": " private void unzip(File filename) throws ZipException, IOException {\n ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(filename)));\n ZipEntry entry = null;\n boolean first_entry = true;\n while ((entry = in.getNextEntry()) != null) {\n if (first_entry) {\n if (!entry.isDirectory()) {\n File subdir = new File(dir + File.separator + filename.getName().substring(0, filename.getName().length() - SUFFIX_ZIP.length()));\n if (!subdir.exists()) {\n subdir.mkdir();\n dir = subdir;\n }\n }\n first_entry = false;\n }\n if (entry.isDirectory()) {\n FileUtils.forceMkdir(new File(dir + File.separator + entry.getName()));\n } else {\n File outfile = new File(dir + File.separator + entry.getName());\n File outdir = new File(outfile.getAbsolutePath().substring(0, outfile.getAbsolutePath().length() - outfile.getName().length()));\n if (!outdir.exists()) FileUtils.forceMkdir(outdir);\n FileOutputStream fo = new FileOutputStream(outfile);\n BufferedOutputStream bos = new BufferedOutputStream(fo, BUFFER);\n int read;\n byte data[] = new byte[BUFFER];\n while ((read = in.read(data, 0, BUFFER)) != -1) {\n read_position++;\n bos.write(data, 0, read);\n }\n bos.flush();\n bos.close();\n }\n }\n in.close();\n }\n", "label": 0} {"func1": " public void testPost() throws Exception {\n HttpPost request = new HttpPost(baseUri + \"/echo\");\n request.setEntity(new StringEntity(\"test\"));\n HttpResponse response = client.execute(request);\n assertEquals(200, response.getStatusLine().getStatusCode());\n assertEquals(\"test\", TestUtil.getResponseAsString(response));\n }\n", "func2": " public void metodo1() {\n int temp;\n boolean flagDesordenado = true;\n while (flagDesordenado) {\n flagDesordenado = false;\n for (int i = 0; i < this.tamanoTabla - 1; i++) {\n if (tabla[i] > tabla[i + 1]) {\n flagDesordenado = true;\n temp = tabla[i];\n tabla[i] = tabla[i + 1];\n tabla[i + 1] = temp;\n }\n }\n }\n }\n", "label": 0} {"func1": " public static DigitalObjectContent byReference(final InputStream inputStream) {\n try {\n File tempFile = File.createTempFile(\"tempContent\", \"tmp\");\n tempFile.deleteOnExit();\n FileOutputStream out = new FileOutputStream(tempFile);\n IOUtils.copyLarge(inputStream, out);\n out.close();\n return new ImmutableContent(tempFile);\n } catch (IOException e) {\n e.printStackTrace();\n }\n throw new IllegalStateException(\"Could not create content for input stream: \" + inputStream);\n }\n", "func2": " public static SVNConfiguracion load(URL urlConfiguracion) {\n SVNConfiguracion configuracion = null;\n try {\n XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());\n configuracion = (SVNConfiguracion) xenc.readObject();\n configuracion.setFicheroConfiguracion(urlConfiguracion);\n xenc.close();\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n return configuracion;\n }\n", "label": 0} {"func1": " protected void innerProcess(CrawlURI curi) throws InterruptedException {\n if (!curi.isHttpTransaction()) {\n return;\n }\n if (!TextUtils.matches(\"^text.*$\", curi.getContentType())) {\n return;\n }\n long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue();\n try {\n maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue();\n } catch (AttributeNotFoundException e) {\n logger.severe(\"Missing max-size-bytes attribute when processing \" + curi.getURIString());\n }\n if (maxsize < curi.getContentSize() && maxsize > -1) {\n return;\n }\n String regexpr = \"\";\n try {\n regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR);\n } catch (AttributeNotFoundException e2) {\n logger.severe(\"Missing strip-reg-exp when processing \" + curi.getURIString());\n return;\n }\n ReplayCharSequence cs = null;\n try {\n cs = curi.getHttpRecorder().getReplayCharSequence();\n } catch (Exception e) {\n curi.addLocalizedError(this.getName(), e, \"Failed get of replay char sequence \" + curi.toString() + \" \" + e.getMessage());\n logger.warning(\"Failed get of replay char sequence \" + curi.toString() + \" \" + e.getMessage() + \" \" + Thread.currentThread().getName());\n return;\n }\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(\"SHA1\");\n } catch (NoSuchAlgorithmException e1) {\n e1.printStackTrace();\n return;\n }\n digest.reset();\n String s = null;\n if (regexpr.length() == 0) {\n s = cs.toString();\n } else {\n Matcher m = TextUtils.getMatcher(regexpr, cs);\n s = m.replaceAll(\" \");\n }\n digest.update(s.getBytes());\n byte[] newDigestValue = digest.digest();\n if (logger.isLoggable(Level.FINEST)) {\n logger.finest(\"Recalculated content digest for \" + curi.getURIString() + \" old: \" + Base32.encode((byte[]) curi.getContentDigest()) + \", new: \" + Base32.encode(newDigestValue));\n }\n curi.setContentDigest(newDigestValue);\n }\n", "func2": " void addDataFromURL(URL theurl) {\n String line;\n InputStream in = null;\n try {\n in = theurl.openStream();\n BufferedReader data = new BufferedReader(new InputStreamReader(in));\n while ((line = data.readLine()) != null) {\n thetext.append(line + \"\\n\");\n }\n } catch (Exception e) {\n System.out.println(e.toString());\n thetext.append(theurl.toString());\n }\n try {\n in.close();\n } catch (Exception e) {\n }\n }\n", "label": 0} {"func1": " public static String md5String(String str) {\n try {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] hash = md.digest();\n final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n StringBuffer res = new StringBuffer();\n for (int i = 0; i < hash.length; i++) {\n res.append(hexChars[(0xF0 & hash[i]) >> 4]);\n res.append(hexChars[0x0F & hash[i]]);\n }\n return res.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n }\n", "func2": " public static void copyFile(File src, File dst) throws IOException {\n try {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[TEMP_FILE_BUFFER_SIZE];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n } catch (FileNotFoundException e1) {\n MLUtil.runtimeError(e1, src.toString());\n } catch (IOException e2) {\n MLUtil.runtimeError(e2, src.toString());\n }\n }\n", "label": 0} {"func1": " public static boolean downloadFile(String from, String to, ProgressMonitor pm) {\n try {\n FileOutputStream out = new FileOutputStream(to);\n URL url = new URL(from);\n URLConnection conn = url.openConnection();\n InputStream in = conn.getInputStream();\n byte[] buffer = new byte[1024];\n int read = 0;\n while ((read = in.read(buffer)) != -1) {\n out.write(buffer, 0, read);\n if (pm != null) pm.addToProgress(read);\n }\n out.close();\n in.close();\n } catch (Exception e) {\n Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e));\n return false;\n }\n return true;\n }\n", "func2": " private static void copyFile(String src, String target) throws IOException {\n FileChannel ic = new FileInputStream(src).getChannel();\n FileChannel oc = new FileOutputStream(target).getChannel();\n ic.transferTo(0, ic.size(), oc);\n ic.close();\n oc.close();\n }\n", "label": 0} {"func1": " public static void main(String[] args) {\n try {\n URL url = new URL(args[0]);\n HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();\n httpCon.setDoOutput(true);\n httpCon.setRequestMethod(\"PUT\");\n OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());\n out.write(\"fatal error\");\n out.close();\n System.out.println(\"end\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "func2": "\tpublic static void Sample1(String myField, String condition1, String condition2) throws SQLException {\n\t\tConnection connection = DriverManager.getConnection(\"jdbc:postgresql://localhost/test\", \"user\", \"password\");\n\t\tconnection.setAutoCommit(false);\n\t\t\n\t\tPreparedStatement ps = connection.prepareStatement(\"UPDATE myTable SET myField = ? WHERE myOtherField1 = ? AND myOtherField2 = ?\");\n\t\tps.setString(1, myField);\n\t\tps.setString(2, condition1);\n\t\tps.setString(3, condition2);\n\t\t\n\t\t// If more than 10 entries change, panic and rollback\n\t\tint numChanged = ps.executeUpdate();\n\t\tif(numChanged > 10) {\n\t\t\tconnection.rollback();\n\t\t} else {\n\t\t\tconnection.commit();\n\t\t}\n\t\t\n\t\tps.close();\n\t\tconnection.close();\n\t}\n", "label": 0} {"func1": " public static InputStream getConfigIs(String path, String name) throws ProgrammerException, DesignerException, UserException {\n InputStream is = null;\n try {\n URL url = getConfigResource(new MonadUri(path).append(name));\n if (url != null) {\n is = url.openStream();\n }\n } catch (IOException e) {\n throw new ProgrammerException(e);\n }\n return is;\n }\n", "func2": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "label": 0} {"func1": " public static String uncompress(String readPath, boolean mkdir) throws Exception {\n ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));\n BufferedInputStream bis = new BufferedInputStream(arcInputStream);\n File baseDir = new File(readPath).getParentFile();\n String basePath = baseDir.getPath() + \"/\";\n if (mkdir) {\n String[] schema = readPath.split(\"/\");\n String baseName = schema[schema.length - 1].replaceAll(\".zip\", \"\");\n FileUtils.forceMkdir(new File(basePath + baseName));\n basePath = basePath + baseName + \"/\";\n }\n ArchiveEntry entry;\n while ((entry = arcInputStream.getNextEntry()) != null) {\n if (entry.isDirectory()) {\n FileUtils.forceMkdir(new File(basePath + entry.getName()));\n } else {\n String writePath = basePath + entry.getName();\n String dirName = FilenameUtils.getPath(writePath);\n FileUtils.forceMkdir(new File(dirName));\n BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));\n int i = 0;\n while ((i = bis.read()) != -1) {\n bos.write(i);\n }\n IOUtils.closeQuietly(bos);\n }\n }\n IOUtils.closeQuietly(bis);\n return basePath;\n }\n", "func2": " public static void copyFile(File source, File target) throws IOException {\n FileChannel in = (new FileInputStream(source)).getChannel();\n FileChannel out = (new FileOutputStream(target)).getChannel();\n in.transferTo(0, source.length(), out);\n in.close();\n out.close();\n }\n", "label": 0} {"func1": " private Reader getReader() throws IOException {\n if (data != null) {\n if (url != null) throw new IllegalArgumentException(\"URL for source data and the data itself must never be specified together.\");\n if (charset != null) throw new IllegalArgumentException(\"Charset has sense only for URL-based data\");\n return new StringReader(data);\n } else if (url != null) {\n InputStream stream = url.openStream();\n if (charset == null) return new InputStreamReader(stream); else return new InputStreamReader(stream, charset);\n }\n return null;\n }\n", "func2": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error: \" + e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) {\n sb.append('0');\n }\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n System.out.println(\"Error:\" + e);\n }\n }\n", "label": 0} {"func1": " public InputStream getInputStream() throws TGBrowserException {\n try {\n if (!this.isFolder()) {\n URL url = new URL(this.url);\n InputStream stream = url.openStream();\n return stream;\n }\n } catch (Throwable throwable) {\n throw new TGBrowserException(throwable);\n }\n return null;\n }\n", "func2": " void copyFile(File src, File dst) throws IOException {\n FileChannel inChannel = new FileInputStream(src).getChannel();\n FileChannel outChannel = new FileOutputStream(dst).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "label": 0} {"func1": " public static void main(String[] args) throws IOException {\n PostParameter a1 = new PostParameter(\"v\", Utils.encode(\"1.0\"));\n PostParameter a2 = new PostParameter(\"api_key\", Utils.encode(RenRenConstant.apiKey));\n PostParameter a3 = new PostParameter(\"method\", Utils.encode(\"feed.publishTemplatizedAction\"));\n PostParameter a4 = new PostParameter(\"call_id\", System.nanoTime());\n PostParameter a5 = new PostParameter(\"session_key\", Utils.encode(\"5.b2ca405eef80b4da1f68d0df64e471be.86400.1298372400-350727914\"));\n PostParameter a8 = new PostParameter(\"format\", Utils.encode(\"JSON\"));\n PostParameter a9 = new PostParameter(\"template_id\", Utils.encode(\"1\"));\n PostParameter a10 = new PostParameter(\"title_data\", Utils.encode(\"\\\"conteng\\\":\\\"xkt\\\"\"));\n PostParameter a11 = new PostParameter(\"body_data\", Utils.encode(\"\\\"conteng\\\":\\\"xkt\\\"\"));\n RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret));\n ps.addParameter(a1);\n ps.addParameter(a2);\n ps.addParameter(a3);\n ps.addParameter(a4);\n ps.addParameter(a5);\n ps.addParameter(a8);\n ps.addParameter(a9);\n ps.addParameter(a10);\n ps.addParameter(a11);\n System.out.println(RenRenConstant.apiUrl + \"?\" + ps.generateUrl());\n URL url = new URL(RenRenConstant.apiUrl + \"?\" + ps.generateUrl());\n HttpURLConnection request = (HttpURLConnection) url.openConnection();\n request.setDoOutput(true);\n request.setRequestMethod(\"POST\");\n System.out.println(\"Sending request...\");\n request.connect();\n System.out.println(\"Response: \" + request.getResponseCode() + \" \" + request.getResponseMessage());\n BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));\n String b = null;\n while ((b = reader.readLine()) != null) {\n System.out.println(b);\n }\n }\n", "func2": " public Wget2(URL url, File f) throws IOException {\n System.out.println(\"bajando: \" + url);\n if (f == null) {\n by = new ByteArrayOutputStream();\n } else {\n by = new FileOutputStream(f);\n }\n URLConnection uc = url.openConnection();\n if (uc instanceof HttpURLConnection) {\n leerHttp((HttpURLConnection) uc);\n } else {\n throw new IOException(\"solo se pueden descargar url http\");\n }\n }\n", "label": 0} {"func1": " @Override\n public Content getContent(Object principal, ContentPath path, Version version, Map properties) throws ContentException {\n String uniqueName = path.getBaseName();\n URL url = buildURL(uniqueName);\n URLContent content = new URLContent(url, this.getName(), uniqueName);\n content.setUniqueName(uniqueName);\n content.setReadable(true);\n content.setWritable(writable);\n content.setExists(true);\n try {\n URLConnection connection = url.openConnection();\n String mimeType = connection.getContentType();\n content.setMimeType(mimeType);\n content.setWritable(true);\n } catch (IOException ex) {\n throw new ContentException(\"unable to obtain mime type of \" + url, ex);\n }\n return content;\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 0} {"func1": " public static String uncompress(String readPath, boolean mkdir) throws Exception {\n ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));\n BufferedInputStream bis = new BufferedInputStream(arcInputStream);\n File baseDir = new File(readPath).getParentFile();\n String basePath = baseDir.getPath() + \"/\";\n if (mkdir) {\n String[] schema = readPath.split(\"/\");\n String baseName = schema[schema.length - 1].replaceAll(\".zip\", \"\");\n FileUtils.forceMkdir(new File(basePath + baseName));\n basePath = basePath + baseName + \"/\";\n }\n ArchiveEntry entry;\n while ((entry = arcInputStream.getNextEntry()) != null) {\n if (entry.isDirectory()) {\n FileUtils.forceMkdir(new File(basePath + entry.getName()));\n } else {\n String writePath = basePath + entry.getName();\n String dirName = FilenameUtils.getPath(writePath);\n FileUtils.forceMkdir(new File(dirName));\n BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));\n int i = 0;\n while ((i = bis.read()) != -1) {\n bos.write(i);\n }\n IOUtils.closeQuietly(bos);\n }\n }\n IOUtils.closeQuietly(bis);\n return basePath;\n }\n", "func2": " public static MessageService getMessageService(String fileId) {\n MessageService ms = null;\n if (serviceCache == null) init();\n if (serviceCache.containsKey(fileId)) return serviceCache.get(fileId);\n Properties p = new Properties();\n try {\n URL url = I18nPlugin.getFileURL(fileId);\n p.load(url.openStream());\n ms = new MessageService(p);\n } catch (Exception e) {\n ms = new MessageService();\n }\n serviceCache.put(fileId, ms);\n return ms;\n }\n", "label": 0} {"func1": " public static ArrayList importRoles(String urlString) {\n ArrayList results = new ArrayList();\n try {\n URL url = new URL(urlString);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer buff = new StringBuffer();\n String line;\n while ((line = in.readLine()) != null) {\n buff.append(line);\n if (line.equals(\"\")) {\n RoleName name = ProfileParser.parseRoleName(buff.toString());\n results.add(name);\n buff = new StringBuffer();\n } else {\n buff.append(NL);\n }\n }\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n } catch (ParsingException e) {\n }\n return results;\n }\n", "func2": " public static void copyTo(File source, File dest) {\n if (source.isHidden()) ; else if (source.isDirectory()) {\n File temp = new File(dest.getPath() + \"/\" + source.getName());\n temp.mkdir();\n for (File sel : source.listFiles()) copyTo(sel, temp);\n } else {\n try {\n File tempDest = new File(dest.getPath() + \"/\" + source.getName());\n tempDest.createNewFile();\n FileChannel sourceCh = new FileInputStream(source).getChannel();\n FileChannel destCh = new FileOutputStream(tempDest).getChannel();\n sourceCh.transferTo(0, sourceCh.size(), destCh);\n sourceCh.close();\n destCh.close();\n } catch (IOException ex) {\n Logger.getLogger(EditorUtil.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }\n", "label": 0} {"func1": " private static Properties loadPropertiesFromClasspath(String path) {\n Enumeration locations;\n Properties props = new Properties();\n try {\n locations = Thread.currentThread().getContextClassLoader().getResources(path);\n while (locations.hasMoreElements()) {\n URL url = locations.nextElement();\n InputStream in = url.openStream();\n props.load(in);\n in.close();\n logger.config(\"Load properties from \" + url);\n }\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"load properties from classpath \\\"\" + path + \"\\\" failed\", e);\n }\n return props;\n }\n", "func2": " static String calculateProfileDiffDigest(String profileDiff, boolean normaliseWhitespace) throws Exception {\n if (normaliseWhitespace) {\n profileDiff = removeWhitespaces(profileDiff);\n }\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(profileDiff.getBytes());\n return new BASE64Encoder().encode(md.digest());\n }\n", "label": 0} {"func1": " public final void navigate(final URL url) {\n try {\n EncogLogging.log(EncogLogging.LEVEL_INFO, \"Navigating to page:\" + url);\n final URLConnection connection = url.openConnection();\n final InputStream is = connection.getInputStream();\n navigate(url, is);\n is.close();\n } catch (final IOException e) {\n EncogLogging.log(EncogLogging.LEVEL_ERROR, e);\n throw new BrowseError(e);\n }\n }\n", "func2": " public static String retrieveData(URL url) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setRequestProperty(\"User-agent\", \"MZmine 2\");\n InputStream is = connection.getInputStream();\n if (is == null) {\n throw new IOException(\"Could not establish a connection to \" + url);\n }\n StringBuffer buffer = new StringBuffer();\n try {\n InputStreamReader reader = new InputStreamReader(is, \"UTF-8\");\n char[] cb = new char[1024];\n int amtRead = reader.read(cb);\n while (amtRead > 0) {\n buffer.append(cb, 0, amtRead);\n amtRead = reader.read(cb);\n }\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n is.close();\n return buffer.toString();\n }\n", "label": 0} {"func1": " public void insertJobLog(String userId, String[] checkId, String checkType, String objType) throws Exception {\n DBOperation dbo = null;\n Connection connection = null;\n PreparedStatement preStm = null;\n String sql = \"insert into COFFICE_JOBLOG_CHECKAUTH (USER_ID,CHECK_ID,CHECK_TYPE,OBJ_TYPE) values (?,?,?,?)\";\n String cleanSql = \"delete from COFFICE_JOBLOG_CHECKAUTH where \" + \"user_id = '\" + userId + \"' and check_type = '\" + checkType + \"' and obj_type = '\" + objType + \"'\";\n try {\n dbo = createDBOperation();\n connection = dbo.getConnection();\n connection.setAutoCommit(false);\n preStm = connection.prepareStatement(cleanSql);\n int dCount = preStm.executeUpdate();\n String sHaveIns = \",\";\n preStm = connection.prepareStatement(sql);\n for (int j = 0; j < checkId.length; j++) {\n if (sHaveIns.indexOf(\",\" + checkId[j] + \",\") < 0) {\n preStm.setInt(1, Integer.parseInt(userId));\n preStm.setInt(2, Integer.parseInt(checkId[j]));\n preStm.setInt(3, Integer.parseInt(checkType));\n preStm.setInt(4, Integer.parseInt(objType));\n preStm.executeUpdate();\n sHaveIns += checkId[j] + \",\";\n }\n }\n connection.commit();\n } catch (Exception ex) {\n log.debug((new Date().toString()) + \" ������Ȩ��ʧ��! \");\n try {\n connection.rollback();\n } catch (SQLException e) {\n throw e;\n }\n throw ex;\n } finally {\n close(null, null, preStm, connection, dbo);\n }\n }\n", "func2": " static HttpURLConnection connect(String url, String method, String contentType, String content, int timeoutMillis) throws ProtocolException, IOException, MalformedURLException, UnsupportedEncodingException {\n HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());\n conn.setRequestMethod(method);\n conn.setConnectTimeout(timeoutMillis);\n byte[] bContent = null;\n if (content != null && content.length() > 0) {\n conn.setDoOutput(true);\n conn.setRequestProperty(\"Content-Type\", contentType);\n bContent = content.getBytes(\"UTF-8\");\n conn.setFixedLengthStreamingMode(bContent.length);\n }\n conn.connect();\n if (bContent != null) {\n OutputStream os = conn.getOutputStream();\n os.write(bContent);\n os.flush();\n os.close();\n }\n return conn;\n }\n", "label": 0} {"func1": " public static String fromHtml(URL url, String defaultEncoding, boolean overrideEncoding) throws IOException, BadDocumentException {\n URLConnection conn = url.openConnection();\n String contentType = conn.getContentType();\n String encoding = conn.getContentEncoding();\n if (encoding == null) {\n int i = contentType.indexOf(\"charset\");\n if (i >= 0) {\n String s = contentType.substring(i);\n i = s.indexOf('=');\n if (i >= 0) {\n s = contentType.substring(i + 1).trim();\n encoding = s.replace(\"\\'\", \"\").replace(\"\\\"\", \"\").trim();\n if (encoding.equals(\"\")) {\n encoding = defaultEncoding;\n }\n }\n } else {\n encoding = defaultEncoding;\n }\n }\n String expected = \"text/html\";\n if (contentType == null) {\n DefaultXMLNoteErrorHandler.warning(null, 90190, \"Returned content type for url.openConnection() is null\");\n contentType = expected;\n }\n int index = contentType.indexOf(';');\n if (index >= 0) {\n contentType = contentType.substring(0, index).trim();\n }\n if (!contentType.equals(expected)) {\n String msg = translator.translate(\"The content type of url '%s' is not '%s', it is '%s'\");\n throw new BadDocumentException(String.format(msg, url.toString(), expected, contentType));\n }\n BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));\n return fromHtml(in, encoding);\n }\n", "func2": " public static ArrayList importRoles(String urlString) {\n ArrayList results = new ArrayList();\n try {\n URL url = new URL(urlString);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer buff = new StringBuffer();\n String line;\n while ((line = in.readLine()) != null) {\n buff.append(line);\n if (line.equals(\"\")) {\n RoleName name = ProfileParser.parseRoleName(buff.toString());\n results.add(name);\n buff = new StringBuffer();\n } else {\n buff.append(NL);\n }\n }\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n } catch (ParsingException e) {\n }\n return results;\n }\n", "label": 0} {"func1": " private String encode(String plaintext) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA\");\n md.update(plaintext.getBytes(\"UTF-8\"));\n byte raw[] = md.digest();\n return (new BASE64Encoder()).encode(raw);\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(\"Error encoding: \" + e);\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"Error encoding: \" + e);\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 0} {"func1": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "func2": " public void testHttpsConnection() throws Throwable {\n setUpStoreProperties();\n try {\n SSLContext ctx = getContext();\n ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);\n TestHostnameVerifier hnv = new TestHostnameVerifier();\n HttpsURLConnection.setDefaultHostnameVerifier(hnv);\n URL url = new URL(\"https://localhost:\" + ss.getLocalPort());\n HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\n SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);\n checkConnectionStateParameters(connection, peerSocket);\n connection.connect();\n } finally {\n tearDownStoreProperties();\n }\n }\n", "label": 0} {"func1": " private JButton getButtonSonido() {\n if (buttonSonido == null) {\n buttonSonido = new JButton();\n buttonSonido.setText(Messages.getString(\"gui.AdministracionResorces.15\"));\n buttonSonido.setIcon(new ImageIcon(getClass().getResource(\"/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png\")));\n buttonSonido.addActionListener(new java.awt.event.ActionListener() {\n\n public void actionPerformed(java.awt.event.ActionEvent e) {\n JFileChooser fc = new JFileChooser();\n fc.addChoosableFileFilter(new SoundFilter());\n int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString(\"gui.AdministracionResorces.17\"));\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n String rutaGlobal = System.getProperty(\"user.dir\") + \"/\" + rutaDatos + \"sonidos/\" + file.getName();\n String rutaRelativa = rutaDatos + \"sonidos/\" + file.getName();\n try {\n FileInputStream fis = new FileInputStream(file);\n FileOutputStream fos = new FileOutputStream(rutaGlobal, true);\n FileChannel canalFuente = fis.getChannel();\n FileChannel canalDestino = fos.getChannel();\n canalFuente.transferTo(0, canalFuente.size(), canalDestino);\n fis.close();\n fos.close();\n imagen.setSonidoURL(rutaRelativa);\n System.out.println(rutaGlobal + \" \" + rutaRelativa);\n buttonSonido.setIcon(new ImageIcon(getClass().getResource(\"/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png\")));\n gui.getAudio().reproduceAudio(imagen);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n } else {\n }\n }\n });\n }\n return buttonSonido;\n }\n", "func2": " @Override\n public void export(final Library lib) throws PluginException {\n try {\n new Thread(new Runnable() {\n\n public void run() {\n formatter.format(lib, writer);\n writer.flush();\n writer.close();\n }\n }).start();\n ftp.connect(host);\n if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {\n ftp.disconnect();\n throw new PluginException(\"Unable to connect to FTP\");\n }\n ftp.login(user, pass);\n ftp.pasv();\n ftp.changeWorkingDirectory(dir);\n ftp.storeFile(file, inStream);\n ftp.logout();\n } catch (SocketException e) {\n throw new PluginException(e);\n } catch (IOException e) {\n throw new PluginException(e);\n } finally {\n if (ftp.isConnected()) {\n try {\n ftp.disconnect();\n } catch (IOException e) {\n }\n }\n }\n }\n", "label": 0} {"func1": " public AsciiParser(String systemID) throws GridBagException {\n String id = systemID;\n if (id.endsWith(\".xml\")) {\n id = StringUtils.replace(id, \".xml\", \".gbc\");\n }\n ClassLoader loader = this.getClass().getClassLoader();\n URL url = loader.getResource(id);\n if (url == null) {\n throw new GridBagException(\"Cannot located resource : \\\"\" + systemID + \"\\\".\");\n }\n try {\n InputStream inStream = url.openStream();\n constraints = getLines(inStream);\n inStream.close();\n } catch (IOException ie1) {\n throw new GridBagException(\"Cannot read from resource \" + id);\n }\n }\n", "func2": " public static String getFileContentFromPlugin(String path) {\n URL url = getURLFromPlugin(path);\n StringBuffer sb = new StringBuffer();\n try {\n Scanner scanner = new Scanner(url.openStream());\n while (scanner.hasNextLine()) {\n String line = scanner.nextLine();\n sb.append(line + \"\\n\");\n }\n scanner.close();\n } catch (Exception e) {\n e.printStackTrace();\n return \"\";\n }\n return sb.toString();\n }\n", "label": 0} {"func1": " public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {\n String name = metadata.get(Metadata.RESOURCE_NAME_KEY);\n if (name != null && wanted.containsKey(name)) {\n FileOutputStream out = new FileOutputStream(wanted.get(name));\n IOUtils.copy(stream, out);\n out.close();\n } else {\n if (downstreamParser != null) {\n downstreamParser.parse(stream, handler, metadata, context);\n }\n }\n }\n", "func2": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error: \" + e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) {\n sb.append('0');\n }\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n System.out.println(\"Error:\" + e);\n }\n }\n", "label": 0} {"func1": " public boolean actualizarDatosFinal(int idJugadorDiv, int idRonda, jugadorxDivxRonda unjxdxr) {\n int intResult = 0;\n String sql = \"UPDATE jugadorxdivxronda \" + \" SET resultado = ?, puntajeRonda = ? \" + \" WHERE jugadorxDivision_idJugadorxDivision = \" + idJugadorDiv + \" AND ronda_numeroRonda = \" + idRonda;\n try {\n connection = conexionBD.getConnection();\n connection.setAutoCommit(false);\n ps = connection.prepareStatement(sql);\n populatePreparedStatementActFinal(unjxdxr);\n intResult = ps.executeUpdate();\n connection.commit();\n } catch (SQLException ex) {\n ex.printStackTrace();\n try {\n connection.rollback();\n } catch (SQLException exe) {\n exe.printStackTrace();\n }\n } finally {\n conexionBD.close(ps);\n conexionBD.close(connection);\n }\n return (intResult > 0);\n }\n", "func2": " public boolean register(Object o) {\n String passwordAsText;\n if (o == null) throw new IllegalArgumentException(\"object cannot be null\");\n if (!(o instanceof User)) {\n throw new IllegalArgumentException(\"passed argument is not an instance of the User class\");\n }\n User newUser = (User) o;\n passwordAsText = newUser.getPassword();\n newUser.setPassword(passwordEncoder.encodePassword(passwordAsText, null));\n newUser.setRegDate(new Date());\n logger.debug(\"Setting default Authority {} to new user!\", Authority.DEFAULT_NAME);\n newUser.getAuthorities().add(super.find(Authority.class, 1));\n logger.debug(\"Creating hash from email address! using Base64\");\n newUser.setHash(new String(Base64.encodeBase64(newUser.getEmail().getBytes())));\n logger.debug(\"Creating phpBB forum User, by calling URL: {}\", forumUrl);\n try {\n StringBuilder urlString = new StringBuilder(forumUrl);\n urlString.append(\"phpBB.php?action=register\").append(\"&login=\").append(newUser.getLogin()).append(\"&password=\").append(passwordAsText).append(\"&email=\").append(newUser.getEmail());\n sqlInjectionPreventer(urlString.toString());\n logger.debug(\"Connecting to URL: {}\", urlString.toString());\n URL url = new URL(urlString.toString());\n URLConnection urlCon = url.openConnection();\n BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));\n String inputLine;\n while ((inputLine = in.readLine()) != null) newUser.setForumID(Integer.valueOf(inputLine));\n in.close();\n } catch (IOException io) {\n logger.error(\"Connecting failed! Msg: {}\", io.getMessage());\n throw new RuntimeException(\"Couldn't conntect to phpBB\");\n } catch (NumberFormatException e) {\n logger.error(\"phpBB user generation failed! Msg: {}\", e.getMessage());\n throw new RuntimeException(\"phpBB user generation failed!\");\n }\n entityManager.persist(newUser);\n try {\n sendConfirmationEmail(newUser);\n return true;\n } catch (MailException ex) {\n return false;\n }\n }\n", "label": 0} {"func1": " private static InputStream getCMSResultAsStream(String rqlQuery) throws RQLException {\n OutputStreamWriter osr = null;\n try {\n URL url = new URL(\"http\", HOST, FILE);\n URLConnection conn = url.openConnection();\n conn.setDoOutput(true);\n osr = new OutputStreamWriter(conn.getOutputStream());\n osr.write(rqlQuery);\n osr.flush();\n return conn.getInputStream();\n } catch (IOException ioe) {\n throw new RQLException(\"IO Exception reading result from server\", ioe);\n } finally {\n if (osr != null) {\n try {\n osr.close();\n } catch (IOException ioe) {\n }\n }\n }\n }\n", "func2": " public APIResponse delete(String id) throws Exception {\n APIResponse response = new APIResponse();\n connection = (HttpURLConnection) new URL(url + \"/api/variable/delete/\" + id).openConnection();\n connection.setRequestMethod(\"DELETE\");\n connection.setConnectTimeout(TIMEOUT);\n connection.connect();\n if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {\n response.setDone(true);\n response.setMessage(\"Variable Deleted!\");\n } else {\n response.setDone(false);\n response.setMessage(\"Delete Variable Error Code: Http (\" + connection.getResponseCode() + \")\");\n }\n connection.disconnect();\n return response;\n }\n", "label": 0} {"func1": " public void run() {\n try {\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setRequestMethod(\"GET\");\n con.setDoInput(true);\n byte[] encodedPassword = (username + \":\" + password).getBytes();\n BASE64Encoder encoder = new BASE64Encoder();\n con.setRequestProperty(\"Authorization\", \"Basic \" + encoder.encode(encodedPassword));\n BufferedInputStream in = new BufferedInputStream(con.getInputStream());\n FileOutputStream fos = new FileOutputStream(toFile);\n BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);\n byte[] data = new byte[1024];\n int x = 0;\n while ((x = in.read(data, 0, 1024)) >= 0) {\n bout.write(data, 0, x);\n lastIteraction = System.currentTimeMillis();\n }\n bout.flush();\n bout.close();\n fos.flush();\n fos.close();\n in.close();\n con.disconnect();\n finish = true;\n } catch (Exception e) {\n this.e = e;\n }\n }\n", "func2": " public static void copyFile(File in, File out) {\n try {\n FileChannel inChannel = null, outChannel = null;\n try {\n out.getParentFile().mkdirs();\n inChannel = new FileInputStream(in).getChannel();\n outChannel = new FileOutputStream(out).getChannel();\n outChannel.transferFrom(inChannel, 0, inChannel.size());\n } finally {\n if (inChannel != null) {\n inChannel.close();\n }\n if (outChannel != null) {\n outChannel.close();\n }\n }\n } catch (Exception e) {\n ObjectUtils.throwAsError(e);\n }\n }\n", "label": 0} {"func1": " public static boolean copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf) throws IOException {\n if (srcFS.getFileStatus(src).isDir()) {\n if (!dst.mkdirs()) {\n return false;\n }\n FileStatus contents[] = srcFS.listStatus(src);\n for (int i = 0; i < contents.length; i++) {\n copy(srcFS, contents[i].getPath(), new File(dst, contents[i].getPath().getName()), deleteSource, conf);\n }\n } else if (srcFS.isFile(src)) {\n InputStream in = srcFS.open(src);\n IOUtils.copyBytes(in, new FileOutputStream(dst), conf);\n } else {\n throw new IOException(src.toString() + \": No such file or directory\");\n }\n if (deleteSource) {\n return srcFS.delete(src, true);\n } else {\n return true;\n }\n }\n", "func2": " public void sendTextFile(String filename) throws IOException {\n Checker.checkEmpty(filename, \"filename\");\n URL url = _getFile(filename);\n PrintWriter out = getWriter();\n Streams.copy(new InputStreamReader(url.openStream()), out);\n out.close();\n }\n", "label": 0} {"func1": " public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {\n String name = metadata.get(Metadata.RESOURCE_NAME_KEY);\n if (name != null && wanted.containsKey(name)) {\n FileOutputStream out = new FileOutputStream(wanted.get(name));\n IOUtils.copy(stream, out);\n out.close();\n } else {\n if (downstreamParser != null) {\n downstreamParser.parse(stream, handler, metadata, context);\n }\n }\n }\n", "func2": " public int create(BusinessObject o) throws DAOException {\n int insert = 0;\n int id = 0;\n Item item = (Item) o;\n try {\n PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery(\"INSERT_ITEM\"));\n pst.setString(1, item.getDescription());\n pst.setDouble(2, item.getUnit_price());\n pst.setInt(3, item.getQuantity());\n pst.setDouble(4, item.getVat());\n pst.setInt(5, item.getIdProject());\n pst.setInt(6, item.getIdCurrency());\n insert = pst.executeUpdate();\n if (insert <= 0) {\n connection.rollback();\n throw new DAOException(\"Number of rows <= 0\");\n } else if (insert > 1) {\n connection.rollback();\n throw new DAOException(\"Number of rows > 1\");\n }\n Statement st = connection.createStatement();\n ResultSet rs = st.executeQuery(\"select max(id_item) from item\");\n rs.next();\n id = rs.getInt(1);\n connection.commit();\n } catch (SQLException e) {\n Log.write(e.getMessage());\n throw new DAOException(\"A SQLException has occured\");\n } catch (NullPointerException npe) {\n Log.write(npe.getMessage());\n throw new DAOException(\"Connection null\");\n }\n return id;\n }\n", "label": 0} {"func1": " public void get() {\n try {\n int cnt;\n URL url = new URL(urlStr);\n URLConnection conn = url.openConnection();\n conn.setDoInput(true);\n conn.setDoOutput(false);\n InputStream is = conn.getInputStream();\n String filename = new File(url.getFile()).getName();\n FileOutputStream fos = new FileOutputStream(dstDir + File.separator + filename);\n byte[] buffer = new byte[4096];\n while ((cnt = is.read(buffer, 0, buffer.length)) != -1) fos.write(buffer, 0, cnt);\n fos.close();\n is.close();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "func2": " public static void main(String[] args) {\n if (args.length != 1) {\n System.out.println(\"Usage: GZip source\");\n return;\n }\n String zipname = args[0] + \".gz\";\n GZIPOutputStream zipout;\n try {\n FileOutputStream out = new FileOutputStream(zipname);\n zipout = new GZIPOutputStream(out);\n } catch (IOException e) {\n System.out.println(\"Couldn't create \" + zipname + \".\");\n return;\n }\n byte[] buffer = new byte[sChunk];\n try {\n FileInputStream in = new FileInputStream(args[0]);\n int length;\n while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length);\n in.close();\n } catch (IOException e) {\n System.out.println(\"Couldn't compress \" + args[0] + \".\");\n }\n try {\n zipout.close();\n } catch (IOException e) {\n }\n }\n", "label": 0} {"func1": " protected static final byte[] digest(String s) {\n byte[] ret = null;\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(s.getBytes());\n ret = md.digest();\n } catch (NoSuchAlgorithmException e) {\n System.err.println(\"no message digest algorithm available!\");\n System.exit(1);\n }\n return ret;\n }\n", "func2": " public FileParse(String fileStr, String type) throws MalformedURLException, IOException {\n this.inFile = fileStr;\n this.type = type;\n System.out.println(\"File str \" + fileStr);\n if (fileStr.indexOf(\"http://\") == 0) {\n URL url = new URL(fileStr);\n urlconn = url.openConnection();\n inStream = urlconn.getInputStream();\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"File\")) {\n File inFile = new File(fileStr);\n size = inFile.length();\n inStream = new FileInputStream(inFile);\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"URL\")) {\n URL url = new URL(fileStr);\n urlconn = url.openConnection();\n inStream = urlconn.getInputStream();\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"URLZip\")) {\n URL url = new URL(fileStr);\n inStream = new GZIPInputStream(url.openStream(), 16384);\n InputStreamReader zis = new InputStreamReader(inStream);\n bufReader = new BufferedReader(zis, 16384);\n } else {\n System.out.println(\"Unknown FileParse inType \" + type);\n }\n }\n", "label": 0} {"func1": " protected Document getRawResults(String urlString, Map args) throws Exception {\n int count = 0;\n Iterator keys = args.keySet().iterator();\n while (keys.hasNext()) {\n String sep = count++ == 0 ? \"?\" : \"&\";\n String name = (String) keys.next();\n if (args.get(name) != null) {\n urlString += sep + name + \"=\" + args.get(name);\n }\n }\n URL url = new URL(urlString);\n URLConnection conn = url.openConnection();\n conn.connect();\n SAXBuilder builder = new SAXBuilder();\n return builder.build(conn.getInputStream());\n }\n", "func2": " public static String md5(String str) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - start\");\n }\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] b = md.digest();\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < b.length; i++) {\n int v = (int) b[i];\n v = v < 0 ? 0x100 + v : v;\n String cc = Integer.toHexString(v);\n if (cc.length() == 1) sb.append('0');\n sb.append(cc);\n }\n String returnString = sb.toString();\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - end\");\n }\n return returnString;\n } catch (Exception e) {\n logger.warn(\"md5(String) - exception ignored\", e);\n }\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - end\");\n }\n return \"\";\n }\n", "label": 0} {"func1": " public boolean submit(String uri) throws java.io.IOException, Exception {\n if (getUserInfo()) {\n String encodedrdf = URLEncoder.encode(rdfpayload, \"UTF-8\");\n URL url = new URL(uri);\n URLConnection connection = url.openConnection();\n connection.setDoOutput(true);\n setDescription(mDescription.getText());\n addCreator(mUser.getText());\n lastUser = mUser.getText();\n PrintWriter out = new PrintWriter(connection.getOutputStream());\n out.println(\"rdfblob=\" + encodedrdf);\n writeCreators(out);\n writeCategories(out);\n writeName(out);\n writeDescription(out);\n writeDate(out);\n out.println(\"&inputtype=1\");\n out.println(\"&op=Submit\");\n out.close();\n return doSubmit(connection, rdfpayload);\n } else {\n JOptionPane.showMessageDialog(null, \"Submit cannot be completed without user information, please try again.\", \"User Info Error\", JOptionPane.ERROR_MESSAGE);\n return false;\n }\n }\n", "func2": " public static void saveFileData(File file, File destination, java.io.File newDataFile) throws Exception {\n String fileName = file.getFileName();\n String assetsPath = FileFactory.getRealAssetsRootPath();\n new java.io.File(assetsPath).mkdir();\n java.io.File workingFile = getAssetIOFile(file);\n DotResourceCache vc = CacheLocator.getVeloctyResourceCache();\n vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingFile.getPath());\n if (destination != null && destination.getInode() > 0) {\n FileInputStream is = new FileInputStream(workingFile);\n FileChannel channelFrom = is.getChannel();\n java.io.File newVersionFile = getAssetIOFile(destination);\n FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();\n channelFrom.transferTo(0, channelFrom.size(), channelTo);\n channelTo.force(false);\n channelTo.close();\n channelFrom.close();\n }\n if (newDataFile != null) {\n FileChannel writeCurrentChannel = new FileOutputStream(workingFile).getChannel();\n writeCurrentChannel.truncate(0);\n FileChannel fromChannel = new FileInputStream(newDataFile).getChannel();\n fromChannel.transferTo(0, fromChannel.size(), writeCurrentChannel);\n writeCurrentChannel.force(false);\n writeCurrentChannel.close();\n fromChannel.close();\n if (UtilMethods.isImage(fileName)) {\n BufferedImage img = javax.imageio.ImageIO.read(workingFile);\n int height = img.getHeight();\n file.setHeight(height);\n int width = img.getWidth();\n file.setWidth(width);\n }\n String folderPath = workingFile.getParentFile().getAbsolutePath();\n Identifier identifier = IdentifierCache.getIdentifierFromIdentifierCache(file);\n java.io.File directory = new java.io.File(folderPath);\n java.io.File[] files = directory.listFiles((new FileFactory()).new ThumbnailsFileNamesFilter(identifier));\n for (java.io.File iofile : files) {\n try {\n iofile.delete();\n } catch (SecurityException e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + iofile.getName() + \" cannot be erased. Please check the file permissions.\");\n } catch (Exception e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + e.getMessage());\n }\n }\n }\n }\n", "label": 0} {"func1": " public static void save(String packageName, ArrayList fileContents, ArrayList fileNames) throws Exception {\n String dirBase = Util.JAVA_DIR + File.separator + packageName;\n File packageDir = new File(dirBase);\n if (!packageDir.exists()) {\n boolean created = packageDir.mkdir();\n if (!created) {\n File currentPath = new File(\".\");\n throw new Exception(\"Directory \" + packageName + \" could not be created. Current directory: \" + currentPath.getAbsolutePath());\n }\n }\n for (int i = 0; i < fileContents.size(); i++) {\n File file = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(fileContents.get(i));\n fos.flush();\n fos.close();\n }\n for (int i = 0; i < fileNames.size(); i++) {\n File fileSrc = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n File fileDst = new File(dirBase + File.separator + fileNames.get(i));\n BufferedReader reader = new BufferedReader(new FileReader(fileSrc));\n BufferedWriter writer = new BufferedWriter(new FileWriter(fileDst));\n writer.append(\"package \" + packageName + \";\\n\");\n String line = \"\";\n while ((line = reader.readLine()) != null) writer.append(line + \"\\n\");\n writer.flush();\n writer.close();\n reader.close();\n }\n }\n", "func2": " public String uploadFile(String url, int port, String uname, String upass, InputStream input) {\n String serverPath = config.getServerPath() + DateUtil.getSysmonth();\n FTPClient ftp = new FTPClient();\n try {\n int replyCode;\n ftp.connect(url, port);\n ftp.login(uname, upass);\n replyCode = ftp.getReplyCode();\n if (!FTPReply.isPositiveCompletion(replyCode)) {\n ftp.disconnect();\n return config.getServerPath();\n }\n if (!ftp.changeWorkingDirectory(serverPath)) {\n ftp.makeDirectory(DateUtil.getSysmonth());\n ftp.changeWorkingDirectory(serverPath);\n }\n ftp.storeFile(getFileName(), input);\n input.close();\n ftp.logout();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return serverPath;\n }\n", "label": 0} {"func1": " public void run(String[] args) throws Throwable {\n FileInputStream input = new FileInputStream(args[0]);\n FileOutputStream output = new FileOutputStream(args[0] + \".out\");\n Reader reader = $(Reader.class, $declass(input));\n Writer writer = $(Writer.class, $declass(output));\n Pump pump;\n if (args.length > 1 && \"diag\".equals(args[1])) {\n pump = $(new Reader() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public int read(byte[] buffer, int off, int len) throws Exception {\n Integer rd = (Integer) $next();\n if (rd > 0) {\n counter += rd;\n }\n return 0;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Read from input \" + counter + \" bytes.\");\n }\n }, reader, writer, new Writer() {\n\n int counter;\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void write(byte[] buffer, int off, int len) throws Exception {\n counter += len;\n }\n\n @ToContext(mode = InvocationMode.sideEffect)\n public void close() throws Exception {\n System.out.println(\"Written to output \" + counter + \" bytes.\");\n }\n });\n } else {\n pump = $(reader, writer);\n }\n pump.pump();\n }\n", "func2": " private boolean saveNodeMeta(NodeInfo info, int properties) {\n boolean rCode = false;\n String query = mServer + \"save.php\" + (\"?id=\" + info.getId());\n try {\n URL url = new URL(query);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n byte[] body = Helpers.EncodeString(Helpers.ASCII, createURLEncodedPropertyString(info, properties));\n conn.setAllowUserInteraction(false);\n conn.setRequestMethod(\"POST\");\n conn.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n setCredentials(conn);\n conn.setDoOutput(true);\n conn.getOutputStream().write(body);\n rCode = saveNode(info, conn);\n } catch (Exception ex) {\n System.out.println(\"Exception: \" + ex.toString());\n }\n return rCode;\n }\n", "label": 0} {"func1": " public static String getMD5Hash(String original) {\n StringBuffer sb = new StringBuffer();\n try {\n StringReader sr = null;\n int crypt_byte = 0;\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(original.getBytes());\n byte[] digest = md.digest();\n sr = new StringReader(new String(digest, \"ISO8859_1\"));\n while ((crypt_byte = sr.read()) != -1) {\n String hexString = Integer.toHexString(crypt_byte);\n if (crypt_byte < 16) {\n hexString = \"0\" + hexString;\n }\n sb.append(hexString);\n }\n } catch (NoSuchAlgorithmException nsae) {\n } catch (IOException ioe) {\n }\n return sb.toString();\n }\n", "func2": " public void googleImageSearch(String search, String start) {\n try {\n String u = \"http://images.google.com/images?q=\" + search + start;\n if (u.contains(\" \")) {\n u = u.replace(\" \", \"+\");\n }\n URL url = new URL(u);\n HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();\n httpcon.addRequestProperty(\"User-Agent\", \"Mozilla/4.76\");\n BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));\n googleImages.clear();\n String text = \"\";\n String lin = \"\";\n while ((lin = readIn.readLine()) != null) {\n text += lin;\n }\n readIn.close();\n if (text.contains(\"\\n\")) {\n text = text.replace(\"\\n\", \"\");\n }\n String[] array = text.split(\"\\\\Qhref=\\\"/imgres?imgurl=\\\\E\");\n for (String s : array) {\n if (s.startsWith(\"http://\") || s.startsWith(\"https://\") && s.contains(\"&\")) {\n String s1 = s.substring(0, s.indexOf(\"&\"));\n googleImages.add(s1);\n }\n }\n } catch (Exception ex4) {\n MusicBoxView.showErrorDialog(ex4);\n }\n MusicBoxView.jButton7.setEnabled(true);\n ImageIcon icon;\n try {\n icon = new ImageIcon(new URL(googleImages.elementAt(MusicBoxView.googleImageLocation)));\n ImageIcon ico = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH));\n MusicBoxView.albumArtLabel.setIcon(ico);\n } catch (MalformedURLException ex1) {\n MusicBoxView.showErrorDialog(ex1);\n }\n }\n", "label": 0} {"func1": " private InputStream sendRequest(SequenceI seq) throws UnsupportedEncodingException, IOException {\n StringBuilder putBuf = new StringBuilder();\n processOptions(putBuf);\n putBuf.append(\"INPUT_SEQUENCE=\");\n putBuf.append(URLEncoder.encode(\">\" + seq.getName() + \"\\n\", ENCODING));\n putBuf.append(URLEncoder.encode(seq.getResidues(), ENCODING));\n URL url = new URL(PRIMER_BLAST_URL);\n URLConnection conn = url.openConnection();\n conn.setDoOutput(true);\n OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\n wr.write(putBuf.toString());\n wr.flush();\n wr.close();\n apollo.util.IOUtil.informationDialog(\"Primer-BLAST request sent\");\n return conn.getInputStream();\n }\n", "func2": " private String digest(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[64];\n md.update(input.getBytes(\"iso-8859-1\"), 0, input.length());\n md5hash = md.digest();\n return this.convertToHex(md5hash);\n }\n", "label": 0} {"func1": " public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setConnectTimeout(timeout);\n connection.setReadTimeout(timeout);\n BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());\n return loadXml(buffInputStream, xmlType);\n }\n", "func2": " private static void loadDefaultSettings(final String configFileName) {\n InputStream in = null;\n OutputStream out = null;\n try {\n in = Thread.currentThread().getContextClassLoader().getResourceAsStream(META_INF_DEFAULT_CONFIG_PROPERTIES);\n out = new FileOutputStream(configFileName);\n IOUtils.copy(in, out);\n } catch (final Exception e) {\n log.warn(\"Unable to pull out the default.\", e);\n throw new RuntimeException(e);\n } finally {\n IOUtils.closeQuietly(in);\n IOUtils.closeQuietly(out);\n }\n }\n", "label": 0} {"func1": " private boolean checkHashBack(Facade facade, HttpServletRequest req) {\n String txtTransactionID = req.getParameter(\"txtTransactionID\");\n String txtOrderTotal = req.getParameter(\"txtOrderTotal\");\n String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);\n String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);\n String txtHashBack = req.getParameter(\"txtHashBack\");\n String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);\n String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;\n MessageDigest digest;\n try {\n digest = java.security.MessageDigest.getInstance(\"MD5\");\n digest.update(securityValue.getBytes());\n byte[] array = digest.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n String hash = sb.toString();\n System.out.println(\"com.eshop.http.servlets.PaymentController.checkHashBack: \" + hash + \" \" + txtHashBack);\n if (txtHashBack.equals(hash)) {\n return true;\n }\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n return false;\n }\n", "func2": " public void sendTextFile(String filename) throws IOException {\n Checker.checkEmpty(filename, \"filename\");\n URL url = _getFile(filename);\n PrintWriter out = getWriter();\n Streams.copy(new InputStreamReader(url.openStream()), out);\n out.close();\n }\n", "label": 0} {"func1": " private final String createMD5(String pwd) throws Exception {\n MessageDigest md = (MessageDigest) MessageDigest.getInstance(\"MD5\").clone();\n md.update(pwd.getBytes(\"UTF-8\"));\n byte[] pd = md.digest();\n StringBuffer app = new StringBuffer();\n for (int i = 0; i < pd.length; i++) {\n String s2 = Integer.toHexString(pd[i] & 0xFF);\n app.append((s2.length() == 1) ? \"0\" + s2 : s2);\n }\n return app.toString();\n }\n", "func2": " private String copyImageFile(String urlString, String filePath) {\n FileOutputStream destination = null;\n File destination_file = null;\n String inLine;\n String dest_name = \"\";\n byte[] buffer;\n int bytes_read;\n int last_offset = 0;\n int offset = 0;\n InputStream imageFile = null;\n try {\n URL url = new URL(urlString);\n imageFile = url.openStream();\n dest_name = url.getFile();\n offset = 0;\n last_offset = 0;\n offset = dest_name.indexOf('/', offset + 1);\n while (offset > -1) {\n last_offset = offset + 1;\n offset = dest_name.indexOf('/', offset + 1);\n }\n dest_name = filePath + File.separator + dest_name.substring(last_offset);\n destination_file = new File(dest_name);\n if (destination_file.exists()) {\n if (destination_file.isFile()) {\n if (!destination_file.canWrite()) {\n System.out.println(\"FileCopy: destination \" + \"file is unwriteable: \" + dest_name);\n }\n System.out.println(\"File \" + dest_name + \" already exists. File will be overwritten.\");\n } else {\n System.out.println(\"FileCopy: destination \" + \"is not a file: \" + dest_name);\n }\n } else {\n File parentdir = parent(destination_file);\n if (!parentdir.exists()) {\n System.out.println(\"FileCopy: destination \" + \"directory doesn't exist: \" + dest_name);\n }\n if (!parentdir.canWrite()) {\n System.out.println(\"FileCopy: destination \" + \"directory is unwriteable: \" + dest_name);\n }\n }\n destination = new FileOutputStream(dest_name);\n buffer = new byte[1024];\n while (true) {\n bytes_read = imageFile.read(buffer);\n if (bytes_read == -1) break;\n destination.write(buffer, 0, bytes_read);\n }\n } catch (MalformedURLException ex) {\n System.out.println(\"Bad URL \" + urlString);\n } catch (IOException ex) {\n System.out.println(\" IO error: \" + ex.getMessage());\n } finally {\n if (imageFile != null) {\n try {\n imageFile.close();\n } catch (IOException e) {\n }\n }\n if (destination != null) {\n try {\n destination.close();\n } catch (IOException e) {\n }\n }\n }\n return (dest_name);\n }\n", "label": 0} {"func1": " @Test\n public void test30_passwordAging() throws Exception {\n Db db = DbConnection.defaultCieDbRW();\n try {\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"5\", 1);\n PreparedStatement pst = db.prepareStatement(\"UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?\");\n pst.setString(1, \"esis\");\n db.executeUpdate(pst);\n db.commit();\n p_logout();\n t30login1();\n assertTrue(isPasswordExpired());\n PeopleInfoLine me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));\n t30chgpasswd();\n assertFalse(isPasswordExpired());\n me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));\n p_logout();\n t30login2();\n assertFalse(isPasswordExpired());\n t30chgpasswd2();\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"0\", 1);\n db.commit();\n } catch (Exception e) {\n e.printStackTrace();\n db.rollback();\n } finally {\n db.safeClose();\n }\n }\n", "func2": " @Test\n public void returnsEnclosedResponseOnUnsuccessfulException() throws Exception {\n Exception e = new UnsuccessfulResponseException(resp);\n expect(mockBackend.execute(host, req, ctx)).andThrow(e);\n replay(mockBackend);\n HttpResponse result = impl.execute(host, req, ctx);\n verify(mockBackend);\n assertSame(resp, result);\n }\n", "label": 0} {"func1": " public static String connRemote(JSONObject jsonObject, String OPCode) {\n String retSrc = \"\";\n try {\n HttpClient httpClient = new DefaultHttpClient();\n HttpPost httpPost = new HttpPost(AZConstants.validateURL);\n HttpParams httpParams = new BasicHttpParams();\n List nameValuePair = new ArrayList();\n nameValuePair.add(new BasicNameValuePair(AZConstants.ACTION_TYPE, OPCode));\n nameValuePair.add(new BasicNameValuePair(AZConstants.PARAM, jsonObject.toString()));\n httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));\n httpPost.setParams(httpParams);\n HttpResponse response = httpClient.execute(httpPost);\n retSrc = EntityUtils.toString(response.getEntity());\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }\n return retSrc;\n }\n", "func2": " private void loadBinaryStream(String streamName, InputStream streamToLoad, long sz, HttpServletRequest req, HttpServletResponse resp) throws IOException {\n resp.setContentType(getContentType(req, streamName));\n resp.setHeader(\"Content-Disposition\", \"inline;filename=\" + streamName);\n resp.setContentLength((int) sz);\n OutputStream out = resp.getOutputStream();\n BufferedOutputStream bos = new BufferedOutputStream(out, 2048);\n try {\n IOUtils.copy(streamToLoad, bos);\n } finally {\n IOUtils.closeQuietly(streamToLoad);\n IOUtils.closeQuietly(bos);\n }\n getCargo().put(GWT_ENTRY_POINT_PAGE_PARAM, null);\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " public UserFunction loadMFileViaWeb(URL codeBase, String directoryAndFile, String mFileName) {\n String code = \"\";\n UserFunction function = null;\n ErrorLogger.debugLine(\"MFileLoader: loading >\" + mFileName + \".m<\");\n try {\n URL url = new URL(codeBase, directoryAndFile);\n InputStream in = url.openStream();\n BufferedReader inReader = new BufferedReader(new InputStreamReader(in));\n String line;\n while ((line = inReader.readLine()) != null) {\n code += line + \"\\n\";\n }\n inReader.close();\n } catch (Exception e) {\n Errors.throwMathLibException(\"MFileLoader: m-file exception via web\");\n }\n ErrorLogger.debugLine(\"MFileLoader: code: begin \\n\" + code + \"\\ncode end\");\n FunctionParser funcParser = new FunctionParser();\n function = funcParser.parseFunction(code);\n function.setName(mFileName);\n ErrorLogger.debugLine(\"MFileLoader: finished webloading >\" + mFileName + \".m<\");\n return function;\n }\n", "label": 0} {"func1": " private void CopyTo(File dest) throws IOException {\n FileReader in = null;\n FileWriter out = null;\n int c;\n try {\n in = new FileReader(image);\n out = new FileWriter(dest);\n while ((c = in.read()) != -1) out.write(c);\n } finally {\n if (in != null) try {\n in.close();\n } catch (Exception e) {\n }\n if (out != null) try {\n out.close();\n } catch (Exception e) {\n }\n }\n }\n", "func2": " public Configuration(URL url) {\n InputStream in = null;\n try {\n load(in = url.openStream());\n } catch (Exception e) {\n throw new RuntimeException(\"Could not load configuration from \" + url, e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException ignore) {\n }\n }\n }\n }\n", "label": 0} {"func1": " public int updateuser(User u) {\n int i = 0;\n Connection conn = null;\n PreparedStatement pm = null;\n try {\n conn = Pool.getConnection();\n conn.setAutoCommit(false);\n pm = conn.prepareStatement(\"update user set username=?,passwd=?,existstate=?,management=? where userid=?\");\n pm.setString(1, u.getUsername());\n pm.setString(2, u.getPasswd());\n pm.setInt(3, u.getExiststate());\n pm.setInt(4, u.getManagement());\n pm.setString(5, u.getUserid());\n i = pm.executeUpdate();\n conn.commit();\n Pool.close(pm);\n Pool.close(conn);\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n Pool.close(pm);\n Pool.close(conn);\n } finally {\n Pool.close(pm);\n Pool.close(conn);\n }\n return i;\n }\n", "func2": " public static void saveFileData(File file, File destination, java.io.File newDataFile) throws Exception {\n String fileName = file.getFileName();\n String assetsPath = FileFactory.getRealAssetsRootPath();\n new java.io.File(assetsPath).mkdir();\n java.io.File workingFile = getAssetIOFile(file);\n DotResourceCache vc = CacheLocator.getVeloctyResourceCache();\n vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingFile.getPath());\n if (destination != null && destination.getInode() > 0) {\n FileInputStream is = new FileInputStream(workingFile);\n FileChannel channelFrom = is.getChannel();\n java.io.File newVersionFile = getAssetIOFile(destination);\n FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();\n channelFrom.transferTo(0, channelFrom.size(), channelTo);\n channelTo.force(false);\n channelTo.close();\n channelFrom.close();\n }\n if (newDataFile != null) {\n FileChannel writeCurrentChannel = new FileOutputStream(workingFile).getChannel();\n writeCurrentChannel.truncate(0);\n FileChannel fromChannel = new FileInputStream(newDataFile).getChannel();\n fromChannel.transferTo(0, fromChannel.size(), writeCurrentChannel);\n writeCurrentChannel.force(false);\n writeCurrentChannel.close();\n fromChannel.close();\n if (UtilMethods.isImage(fileName)) {\n BufferedImage img = javax.imageio.ImageIO.read(workingFile);\n int height = img.getHeight();\n file.setHeight(height);\n int width = img.getWidth();\n file.setWidth(width);\n }\n String folderPath = workingFile.getParentFile().getAbsolutePath();\n Identifier identifier = IdentifierCache.getIdentifierFromIdentifierCache(file);\n java.io.File directory = new java.io.File(folderPath);\n java.io.File[] files = directory.listFiles((new FileFactory()).new ThumbnailsFileNamesFilter(identifier));\n for (java.io.File iofile : files) {\n try {\n iofile.delete();\n } catch (SecurityException e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + iofile.getName() + \" cannot be erased. Please check the file permissions.\");\n } catch (Exception e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + e.getMessage());\n }\n }\n }\n }\n", "label": 0} {"func1": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String senha = \"\";\n String email = request.getParameter(\"EmailLogin\");\n try {\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(request.getParameter(\"SenhaLogin\").getBytes(), 0, request.getParameter(\"SenhaLogin\").length());\n senha = new BigInteger(1, messageDigest.digest()).toString(16);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);\n String redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"?&msg=3\";\n if (request.getHeader(\"REFERER\").indexOf(\"?\") != -1) {\n redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"&msg=3\";\n }\n if (usuario.getNome() != null) {\n HttpSession session = request.getSession();\n session.setAttribute(\"usuario\", usuario);\n redirect = \"index.jsp\";\n }\n response.sendRedirect(redirect);\n }\n", "func2": " private String File2String(String directory, String filename) {\n String line;\n InputStream in = null;\n try {\n File f = new File(filename);\n System.out.println(\"File On:>>>>>>>>>> \" + f.getCanonicalPath());\n in = new FileInputStream(f);\n } catch (FileNotFoundException ex) {\n in = null;\n } catch (IOException ex) {\n in = null;\n }\n try {\n if (in == null) {\n filename = directory + \"/\" + filename;\n java.net.URL urlFile = ClassLoader.getSystemResource(filename);\n if (urlFile == null) {\n System.out.println(\"Integrated Chips list file not found: \" + filename);\n System.exit(-1);\n }\n in = urlFile.openStream();\n }\n BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n StringBuffer xmlText = new StringBuffer();\n while ((line = reader.readLine()) != null) {\n xmlText.append(line);\n }\n reader.close();\n return xmlText.toString();\n } catch (FileNotFoundException ex) {\n System.out.println(\"Integrated Chips list file not found\");\n System.exit(-1);\n } catch (IOException ex) {\n ex.printStackTrace();\n System.exit(-1);\n }\n return null;\n }\n", "label": 0} {"func1": " public static void copy(File src, File dest) throws FileNotFoundException, IOException {\n FileInputStream in = new FileInputStream(src);\n FileOutputStream out = new FileOutputStream(dest);\n try {\n byte[] buf = new byte[1024];\n int c = -1;\n while ((c = in.read(buf)) > 0) out.write(buf, 0, c);\n } finally {\n in.close();\n out.close();\n }\n }\n", "func2": " private void update(String statement, SyrupConnection con, boolean do_log) throws Exception {\n Statement s = null;\n try {\n s = con.createStatement();\n s.executeUpdate(statement);\n con.commit();\n } catch (Throwable e) {\n if (do_log) {\n logger.log(Level.INFO, \"Update failed. Transaction is rolled back\", e);\n }\n con.rollback();\n }\n }\n", "label": 0} {"func1": " private static byte[] baseHash(String name, String password) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n digest.reset();\n digest.update(name.toLowerCase().getBytes());\n digest.update(password.getBytes());\n return digest.digest();\n } catch (NoSuchAlgorithmException ex) {\n d(\"MD5 algorithm not found!\");\n throw new RuntimeException(\"MD5 algorithm not found! Unable to authenticate\");\n }\n }\n", "func2": " static void copy(String src, String dest) throws IOException {\n File ifp = new File(src);\n File ofp = new File(dest);\n if (ifp.exists() == false) {\n throw new IOException(\"file '\" + src + \"' does not exist\");\n }\n FileInputStream fis = new FileInputStream(ifp);\n FileOutputStream fos = new FileOutputStream(ofp);\n byte[] b = new byte[1024];\n while (fis.read(b) > 0) fos.write(b);\n fis.close();\n fos.close();\n }\n", "label": 0} {"func1": " public InputStream retrieveStream(String url) {\n HttpGet getRequest = new HttpGet(url);\n try {\n HttpResponse getResponse = getClient().execute(getRequest);\n final int statusCode = getResponse.getStatusLine().getStatusCode();\n if (statusCode != HttpStatus.SC_OK) {\n Log.w(getClass().getSimpleName(), \"Error \" + statusCode + \" for URL \" + url);\n return null;\n }\n HttpEntity getResponseEntity = getResponse.getEntity();\n return getResponseEntity.getContent();\n } catch (Exception e) {\n getRequest.abort();\n Log.w(getClass().getSimpleName(), \"Error for URL \" + url, e);\n }\n return null;\n }\n", "func2": " private void copyFile(final String sourceFileName, final File path) throws IOException {\n final File source = new File(sourceFileName);\n final File destination = new File(path, source.getName());\n FileChannel srcChannel = null;\n FileChannel dstChannel = null;\n try {\n srcChannel = new FileInputStream(source).getChannel();\n dstChannel = new FileOutputStream(destination).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } finally {\n try {\n if (dstChannel != null) {\n dstChannel.close();\n }\n } catch (Exception exception) {\n }\n try {\n if (srcChannel != null) {\n srcChannel.close();\n }\n } catch (Exception exception) {\n }\n }\n }\n", "label": 0} {"func1": " private String cookieString(String url, String ip) {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"SHA-1\");\n md.update((url + \"&&\" + ip + \"&&\" + salt.toString()).getBytes());\n java.math.BigInteger hash = new java.math.BigInteger(1, md.digest());\n return hash.toString(16);\n } catch (NoSuchAlgorithmException e) {\n filterConfig.getServletContext().log(this.getClass().getName() + \" error \" + e);\n return null;\n }\n }\n", "func2": " public static void main(String[] args) throws Exception {\n if (args.length != 2) {\n System.out.println(\"Usage: URLDumper \");\n System.exit(1);\n }\n String location = args[0];\n String file = args[1];\n URL url = new URL(location);\n FileOutputStream fos = new FileOutputStream(file);\n byte[] bytes = new byte[4096];\n InputStream is = url.openStream();\n int read;\n while ((read = is.read(bytes)) != -1) {\n fos.write(bytes, 0, read);\n }\n is.close();\n fos.close();\n }\n", "label": 0} {"func1": " public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setConnectTimeout(timeout);\n connection.setReadTimeout(timeout);\n BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());\n return loadXml(buffInputStream, xmlType);\n }\n", "func2": " public static void loginBitShare() throws Exception {\n HttpParams params = new BasicHttpParams();\n params.setParameter(\"http.useragent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6\");\n DefaultHttpClient httpclient = new DefaultHttpClient(params);\n System.out.println(\"Trying to log in to bitshare.com\");\n HttpPost httppost = new HttpPost(\"http://bitshare.com/login.html\");\n List formparams = new ArrayList();\n formparams.add(new BasicNameValuePair(\"user\", \"007007dinesh\"));\n formparams.add(new BasicNameValuePair(\"password\", \"\"));\n formparams.add(new BasicNameValuePair(\"submit\", \"Login\"));\n UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, \"UTF-8\");\n httppost.setEntity(entity);\n HttpResponse httpresponse = httpclient.execute(httppost);\n Iterator it = httpclient.getCookieStore().getCookies().iterator();\n Cookie escookie = null;\n while (it.hasNext()) {\n escookie = it.next();\n System.out.println(escookie.getName() + \" = \" + escookie.getValue());\n }\n System.out.println(EntityUtils.toString(httpresponse.getEntity()));\n }\n", "label": 0} {"func1": " public static String getFileContentFromPlugin(String path) {\n URL url = getURLFromPlugin(path);\n StringBuffer sb = new StringBuffer();\n try {\n Scanner scanner = new Scanner(url.openStream());\n while (scanner.hasNextLine()) {\n String line = scanner.nextLine();\n sb.append(line + \"\\n\");\n }\n scanner.close();\n } catch (Exception e) {\n e.printStackTrace();\n return \"\";\n }\n return sb.toString();\n }\n", "func2": " private VelocityEngine newVelocityEngine() {\n VelocityEngine velocityEngine = null;\n InputStream is = null;\n try {\n URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);\n is = url.openStream();\n Properties props = new Properties();\n props.load(is);\n velocityEngine = new VelocityEngine(props);\n velocityEngine.init();\n } catch (Exception e) {\n throw new RuntimeException(\"can not find velocity props file, file=\" + VELOCITY_PROPS_FILE, e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return velocityEngine;\n }\n", "label": 0} {"func1": " public static byte[] loadURLToBuffer(URL url) throws IOException {\n byte[] buf = new byte[4096];\n byte[] data = null;\n byte[] temp = null;\n int iCount = 0;\n int iTotal = 0;\n BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480);\n while ((iCount = in.read(buf, 0, buf.length)) != -1) {\n if (iTotal == 0) {\n data = new byte[iCount];\n System.arraycopy(buf, 0, data, 0, iCount);\n iTotal = iCount;\n } else {\n temp = new byte[iCount + iTotal];\n System.arraycopy(data, 0, temp, 0, iTotal);\n System.arraycopy(buf, 0, temp, iTotal, iCount);\n data = temp;\n iTotal = iTotal + iCount;\n }\n }\n in.close();\n return data;\n }\n", "func2": " public void makeRead(String user, long databaseID, long time) throws SQLException {\n String query = \"replace into fs.read_post (post, user, read_date) values (?, ?, ?)\";\n ensureConnection();\n PreparedStatement statement = m_connection.prepareStatement(query);\n try {\n statement.setLong(1, databaseID);\n statement.setString(2, user);\n statement.setTimestamp(3, new Timestamp(time));\n int count = statement.executeUpdate();\n if (0 == count) throw new SQLException(\"Nothing updated.\");\n m_connection.commit();\n } catch (SQLException e) {\n m_connection.rollback();\n throw e;\n } finally {\n statement.close();\n }\n }\n", "label": 0} {"func1": " public static void copyFile(File src, File dst) throws IOException {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[1024];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n }\n", "func2": " private ByteArrayInputStream fetchUrl(String urlString, Exception[] outException) {\n URL url;\n try {\n url = new URL(urlString);\n InputStream is = null;\n int inc = 65536;\n int curr = 0;\n byte[] result = new byte[inc];\n try {\n is = url.openStream();\n int n;\n while ((n = is.read(result, curr, result.length - curr)) != -1) {\n curr += n;\n if (curr == result.length) {\n byte[] temp = new byte[curr + inc];\n System.arraycopy(result, 0, temp, 0, curr);\n result = temp;\n }\n }\n return new ByteArrayInputStream(result, 0, curr);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n }\n }\n }\n } catch (Exception e) {\n if (outException != null) {\n outException[0] = e;\n }\n }\n return null;\n }\n", "label": 0} {"func1": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String senha = \"\";\n String email = request.getParameter(\"EmailLogin\");\n try {\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(request.getParameter(\"SenhaLogin\").getBytes(), 0, request.getParameter(\"SenhaLogin\").length());\n senha = new BigInteger(1, messageDigest.digest()).toString(16);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);\n String redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"?&msg=3\";\n if (request.getHeader(\"REFERER\").indexOf(\"?\") != -1) {\n redirect = request.getHeader(\"REFERER\").replace(\"?msg=3\", \"\").replace(\"&msg=3\", \"\") + \"&msg=3\";\n }\n if (usuario.getNome() != null) {\n HttpSession session = request.getSession();\n session.setAttribute(\"usuario\", usuario);\n redirect = \"index.jsp\";\n }\n response.sendRedirect(redirect);\n }\n", "func2": " @Test\n public void test30_passwordAging() throws Exception {\n Db db = DbConnection.defaultCieDbRW();\n try {\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"5\", 1);\n PreparedStatement pst = db.prepareStatement(\"UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?\");\n pst.setString(1, \"esis\");\n db.executeUpdate(pst);\n db.commit();\n p_logout();\n t30login1();\n assertTrue(isPasswordExpired());\n PeopleInfoLine me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));\n t30chgpasswd();\n assertFalse(isPasswordExpired());\n me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));\n p_logout();\n t30login2();\n assertFalse(isPasswordExpired());\n t30chgpasswd2();\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"0\", 1);\n db.commit();\n } catch (Exception e) {\n e.printStackTrace();\n db.rollback();\n } finally {\n db.safeClose();\n }\n }\n", "label": 0} {"func1": " public HttpResponseExchange execute() throws Exception {\n HttpResponseExchange forwardResponse = null;\n int fetchSizeLimit = Config.getInstance().getFetchLimitSize();\n while (null != lastContentRange) {\n forwardRequest.setBody(new byte[0]);\n ContentRangeHeaderValue old = lastContentRange;\n long sendSize = fetchSizeLimit;\n if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {\n sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);\n }\n if (sendSize <= 0) {\n break;\n }\n lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));\n forwardResponse = syncFetch(forwardRequest);\n if (sendSize < fetchSizeLimit) {\n lastContentRange = null;\n }\n }\n return forwardResponse;\n }\n", "func2": " public static void main(String args[]) throws IOException {\n BufferedReader in = new BufferedReader(new FileReader(args[0]));\n Writer out = new FileWriter(args[1]);\n out = new WrapFilter(new BufferedWriter(out), 40);\n out = new TitleCaseFilter(out);\n String line;\n while ((line = in.readLine()) != null) out.write(line + \"\\n\");\n out.close();\n in.close();\n }\n", "label": 0} {"func1": " public UserFunction loadMFileViaWeb(URL codeBase, String directoryAndFile, String mFileName) {\n String code = \"\";\n UserFunction function = null;\n ErrorLogger.debugLine(\"MFileLoader: loading >\" + mFileName + \".m<\");\n try {\n URL url = new URL(codeBase, directoryAndFile);\n InputStream in = url.openStream();\n BufferedReader inReader = new BufferedReader(new InputStreamReader(in));\n String line;\n while ((line = inReader.readLine()) != null) {\n code += line + \"\\n\";\n }\n inReader.close();\n } catch (Exception e) {\n Errors.throwMathLibException(\"MFileLoader: m-file exception via web\");\n }\n ErrorLogger.debugLine(\"MFileLoader: code: begin \\n\" + code + \"\\ncode end\");\n FunctionParser funcParser = new FunctionParser();\n function = funcParser.parseFunction(code);\n function.setName(mFileName);\n ErrorLogger.debugLine(\"MFileLoader: finished webloading >\" + mFileName + \".m<\");\n return function;\n }\n", "func2": " public String digest(String message) throws NoSuchAlgorithmException, EncoderException {\n MessageDigest messageDigest = MessageDigest.getInstance(\"SHA-256\");\n messageDigest.update(message.getBytes());\n byte[] raw = messageDigest.digest();\n byte[] chars = new Base64().encode(raw);\n return new String(chars);\n }\n", "label": 0} {"func1": " @Test(expected = GadgetException.class)\n public void malformedGadgetSpecIsCachedAndThrows() throws Exception {\n HttpRequest request = createCacheableRequest();\n expect(pipeline.execute(request)).andReturn(new HttpResponse(\"malformed junk\")).once();\n replay(pipeline);\n try {\n specFactory.getGadgetSpec(createContext(SPEC_URL, false));\n fail(\"No exception thrown on bad parse\");\n } catch (GadgetException e) {\n }\n specFactory.getGadgetSpec(createContext(SPEC_URL, false));\n }\n", "func2": " @Test\n public void test01_ok_failed_500_no_logo() throws Exception {\n DefaultHttpClient client = new DefaultHttpClient();\n try {\n HttpPost post = new HttpPost(xlsURL);\n HttpResponse response = client.execute(post);\n assertEquals(\"failed code for \", 500, response.getStatusLine().getStatusCode());\n } finally {\n client.getConnectionManager().shutdown();\n }\n }\n", "label": 0} {"func1": " public Bitmap retrieveBitmap(String urlString) {\n Log.d(Constants.LOG_TAG, \"making HTTP trip for image:\" + urlString);\n Bitmap bitmap = null;\n try {\n URL url = new URL(urlString);\n URLConnection conn = url.openConnection();\n conn.setConnectTimeout(3000);\n conn.setReadTimeout(5000);\n bitmap = BitmapFactory.decodeStream(conn.getInputStream());\n } catch (MalformedURLException e) {\n Log.e(Constants.LOG_TAG, \"Exception loading image, malformed URL\", e);\n } catch (IOException e) {\n Log.e(Constants.LOG_TAG, \"Exception loading image, IO error\", e);\n }\n return bitmap;\n }\n", "func2": " public static Model downloadModel(String url) {\n Model model = ModelFactory.createDefaultModel();\n try {\n URLConnection connection = new URL(url).openConnection();\n if (connection instanceof HttpURLConnection) {\n HttpURLConnection httpConnection = (HttpURLConnection) connection;\n httpConnection.setRequestProperty(\"Accept\", \"application/rdf+xml, */*;q=.1\");\n httpConnection.setRequestProperty(\"Accept-Language\", \"en\");\n }\n InputStream in = connection.getInputStream();\n model.read(in, url);\n in.close();\n return model;\n } catch (MalformedURLException e) {\n cat.debug(\"Unable to download model from \" + url, e);\n throw new RuntimeException(e);\n } catch (IOException e) {\n cat.debug(\"Unable to download model from \" + url, e);\n throw new RuntimeException(e);\n }\n }\n", "label": 0} {"func1": " public static void main(String[] args) throws Exception {\n int result = 20;\n if (args.length == 1) {\n StringBuffer urlString = new StringBuffer(args[0]);\n if (urlString.lastIndexOf(\"/\") != urlString.length() - 1) {\n urlString.append('/');\n }\n urlString.append(\"GetConfig.jsp\");\n URLConnection conn = new URL(urlString.toString()).openConnection();\n System.out.println(Configuration.readObject(conn.getInputStream()));\n result = 0;\n } else {\n System.err.println(\"usage: GetConfig \");\n }\n System.exit(result);\n }\n", "func2": " public boolean update(String dbName, Query[] queries) throws ServiceException {\n Connection con = null;\n PreparedStatement pstmt = null;\n int rows = 0;\n try {\n con = getDbConnection().getConnection(dbName);\n con.setAutoCommit(false);\n for (int i = 0; i < queries.length; i++) {\n Query query = queries[i];\n System.out.println(query.getSql());\n pstmt = con.prepareStatement(query.getSql());\n addParametersToQuery(query, pstmt);\n rows += pstmt.executeUpdate();\n }\n con.commit();\n return rows > 0;\n } catch (DbException e) {\n log.error(\"[DAOService::update] \" + e.getMessage(), e);\n log.error(\"[DAOService::update] Execute rollback \" + e.getMessage(), e);\n try {\n con.rollback();\n } catch (SQLException e1) {\n log.error(\"[DAOService::update] Errore durante il rollback \" + e.getMessage(), e);\n throw new ServiceException(e.getMessage());\n }\n throw new ServiceException(e.getMessage());\n } catch (SQLException e) {\n log.error(\"[DAOService::update] \" + e.getMessage(), e);\n try {\n con.rollback();\n } catch (SQLException e1) {\n log.error(\"[DAOService::update] Errore durante il rollback \" + e.getMessage(), e);\n throw new ServiceException(e.getMessage());\n }\n throw new ServiceException(e.getMessage());\n } finally {\n closeConnection(con, pstmt, null);\n }\n }\n", "label": 0} {"func1": " protected String downloadURLtoString(URL url) throws IOException {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer sb = new StringBuffer(100 * 1024);\n String str;\n while ((str = in.readLine()) != null) {\n sb.append(str);\n }\n in.close();\n return sb.toString();\n }\n", "func2": " @Test\n public void testSpeedyShareUpload() throws Exception {\n request.setUrl(\"http://www.speedyshare.com/upload.php\");\n request.setFile(\"fileup0\", file);\n HttpResponse response = httpClient.execute(request);\n assertTrue(response.is2xxSuccess());\n assertTrue(response.getResponseHeaders().size() > 0);\n String body = IOUtils.toString(response.getResponseBody());\n assertTrue(body.contains(\"Download link\"));\n assertTrue(body.contains(\"Delete password\"));\n response.close();\n }\n", "label": 0} {"func1": " private boolean getWave(String url, String Word) {\n try {\n File FF = new File(f.getParent() + \"/\" + f.getName() + \"pron\");\n FF.mkdir();\n URL url2 = new URL(url);\n BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));\n File Fdel = new File(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n if (!Fdel.exists()) {\n FileOutputStream outstream = new FileOutputStream(f.getParent() + \"/\" + f.getName() + \"pron/\" + Word + \".wav\");\n BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));\n char[] binput = new char[1024];\n int len = stream.read(binput, 0, 1024);\n while (len > 0) {\n bwriter.write(binput, 0, len);\n len = stream.read(binput, 0, 1024);\n }\n bwriter.close();\n outstream.close();\n }\n stream.close();\n } catch (Exception e) {\n System.out.println(e.getMessage());\n return false;\n }\n return true;\n }\n", "func2": " public String transformByMD5(String password) throws XSServiceException {\n MessageDigest md5;\n byte[] output;\n StringBuffer bufferPass;\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n logger.warn(\"DataAccessException thrown while getting MD5 algorithm:\" + e.getMessage(), e);\n throw new XSServiceException(\"Database error while saving user\");\n }\n md5.reset();\n md5.update(password.getBytes());\n output = md5.digest();\n bufferPass = new StringBuffer();\n for (byte b : output) {\n bufferPass.append(Integer.toHexString(0xff & b).length() == 1 ? \"0\" + Integer.toHexString(0xff & b) : Integer.toHexString(0xff & b));\n }\n return bufferPass.toString();\n }\n", "label": 0} {"func1": " @Test\n public void test30_passwordAging() throws Exception {\n Db db = DbConnection.defaultCieDbRW();\n try {\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"5\", 1);\n PreparedStatement pst = db.prepareStatement(\"UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?\");\n pst.setString(1, \"esis\");\n db.executeUpdate(pst);\n db.commit();\n p_logout();\n t30login1();\n assertTrue(isPasswordExpired());\n PeopleInfoLine me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));\n t30chgpasswd();\n assertFalse(isPasswordExpired());\n me = getCurrentPeople();\n assertNotNull(me.getPasswordExpirationDate());\n assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));\n p_logout();\n t30login2();\n assertFalse(isPasswordExpired());\n t30chgpasswd2();\n db.begin();\n Config.setProperty(db, \"com.entelience.esis.security.passwordAge\", \"0\", 1);\n db.commit();\n } catch (Exception e) {\n e.printStackTrace();\n db.rollback();\n } finally {\n db.safeClose();\n }\n }\n", "func2": " public void seeURLConnection() throws Exception {\n URL url = new URL(\"http://wantmeet.iptime.org\");\n URLConnection uc = url.openConnection();\n BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));\n String s = null;\n StringBuffer sb = new StringBuffer();\n while ((s = br.readLine()) != null) {\n sb.append(s);\n }\n br.close();\n log.debug(\"sb=[\" + sb.toString() + \"]\");\n }\n", "label": 0} {"func1": " public static void copyFile(File from, File to) throws IOException {\n assert (from != null);\n assert (to != null);\n if (!to.exists()) {\n File parentDir = to.getParentFile();\n if (!parentDir.exists()) parentDir.mkdirs();\n to.createNewFile();\n }\n FileInputStream in = null;\n FileOutputStream out = null;\n try {\n in = new FileInputStream(from);\n try {\n out = new FileOutputStream(to);\n FileChannel ic = in.getChannel();\n try {\n FileChannel oc = out.getChannel();\n try {\n oc.transferFrom(ic, 0, from.length());\n } finally {\n if (oc != null) {\n oc.close();\n }\n }\n } finally {\n if (ic != null) {\n ic.close();\n }\n }\n } finally {\n if (out != null) {\n out.close();\n }\n }\n } finally {\n if (in != null) {\n in.close();\n }\n }\n }\n", "func2": " public int updateuser(User u) {\n int i = 0;\n Connection conn = null;\n PreparedStatement pm = null;\n try {\n conn = Pool.getConnection();\n conn.setAutoCommit(false);\n pm = conn.prepareStatement(\"update user set username=?,passwd=?,existstate=?,management=? where userid=?\");\n pm.setString(1, u.getUsername());\n pm.setString(2, u.getPasswd());\n pm.setInt(3, u.getExiststate());\n pm.setInt(4, u.getManagement());\n pm.setString(5, u.getUserid());\n i = pm.executeUpdate();\n conn.commit();\n Pool.close(pm);\n Pool.close(conn);\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n Pool.close(pm);\n Pool.close(conn);\n } finally {\n Pool.close(pm);\n Pool.close(conn);\n }\n return i;\n }\n", "label": 0} {"func1": " public static SVNConfiguracion load(URL urlConfiguracion) {\n SVNConfiguracion configuracion = null;\n try {\n XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());\n configuracion = (SVNConfiguracion) xenc.readObject();\n configuracion.setFicheroConfiguracion(urlConfiguracion);\n xenc.close();\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n return configuracion;\n }\n", "func2": " private VelocityEngine newVelocityEngine() {\n VelocityEngine velocityEngine = null;\n InputStream is = null;\n try {\n URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);\n is = url.openStream();\n Properties props = new Properties();\n props.load(is);\n velocityEngine = new VelocityEngine(props);\n velocityEngine.init();\n } catch (Exception e) {\n throw new RuntimeException(\"can not find velocity props file, file=\" + VELOCITY_PROPS_FILE, e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return velocityEngine;\n }\n", "label": 0} {"func1": " @Override\n public EntrySet read(EntrySet set) throws ReadFailedException {\n if (!SourceCache.contains(url)) {\n SSL.certify(url);\n try {\n super.setParser(Parser.detectParser(url.openStream()));\n final PipedInputStream in = new PipedInputStream();\n final PipedOutputStream forParser = new PipedOutputStream(in);\n new Thread(new Runnable() {\n\n public void run() {\n try {\n OutputStream out = SourceCache.startCaching(url);\n InputStream is = url.openStream();\n byte[] buffer = new byte[100000];\n while (true) {\n int amountRead = is.read(buffer);\n if (amountRead == -1) {\n break;\n }\n forParser.write(buffer, 0, amountRead);\n out.write(buffer, 0, amountRead);\n }\n forParser.close();\n out.close();\n SourceCache.finish(url);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }).start();\n super.setIos(in);\n } catch (Exception e) {\n throw new ReadFailedException(e);\n }\n return super.read(set);\n } else {\n try {\n return SourceCache.get(url).read(set);\n } catch (IOException e) {\n throw new ReadFailedException(e);\n }\n }\n }\n", "func2": " private void reload() {\n if (xml != null) {\n try {\n String currentDate = new SimpleDateFormat(\"yyyy-MM-dd\").format(new Date());\n if (currentDate.equalsIgnoreCase(exchangeRateDate)) {\n return;\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n XPath xpath = null;\n try {\n DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\n URLConnection conn = null;\n URL url = new URL(\"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml\");\n conn = url.openConnection();\n xml = docBuilder.parse(conn.getInputStream());\n xpath = XPathFactory.newInstance().newXPath();\n exchangeRateDate = xpath.evaluate(\"/Envelope/Cube/Cube/@time\", xml);\n xpath = XPathFactory.newInstance().newXPath();\n NodeList currenciesNode = (NodeList) xpath.evaluate(\"/Envelope/Cube/Cube/Cube[@currency]\", xml, XPathConstants.NODESET);\n currencies = new String[currenciesNode.getLength()];\n for (int i = 0; i < currencies.length; i++) {\n currencies[i] = currenciesNode.item(i).getAttributes().getNamedItem(\"currency\").getTextContent();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public static URL[] getDirectoryListing(URL url) throws IOException, CancelledOperationException {\n FileSystem.logger.log(Level.FINER, \"listing {0}\", url);\n String file = url.getFile();\n if (file.charAt(file.length() - 1) != '/') {\n url = new URL(url.toString() + '/');\n }\n String userInfo = KeyChain.getDefault().getUserInfo(url);\n URLConnection urlConnection = url.openConnection();\n urlConnection.setAllowUserInteraction(false);\n urlConnection.setConnectTimeout(FileSystem.settings().getConnectTimeoutMs());\n if (userInfo != null) {\n String encode = Base64.encodeBytes(userInfo.getBytes());\n urlConnection.setRequestProperty(\"Authorization\", \"Basic \" + encode);\n }\n InputStream urlStream;\n urlStream = urlConnection.getInputStream();\n return getDirectoryListing(url, urlStream);\n }\n", "func2": " public void googleImageSearch() {\n if (artist.compareToIgnoreCase(previousArtist) != 0) {\n MusicBoxView.googleImageLocation = 0;\n try {\n String u = \"http://images.google.com/images?q=\" + currentTrack.getArtist() + \" - \" + currentTrack.getAlbum() + \"&sa=N&start=0&ndsp=21\";\n if (u.contains(\" \")) {\n u = u.replace(\" \", \"+\");\n }\n URL url = new URL(u);\n HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();\n httpcon.addRequestProperty(\"User-Agent\", \"Mozilla/4.76\");\n BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));\n String text = \"\";\n String lin = \"\";\n while ((lin = readIn.readLine()) != null) {\n text += lin;\n }\n readIn.close();\n if (text.contains(\"\\n\")) {\n text = text.replace(\"\\n\", \"\");\n }\n String[] array = text.split(\"\\\\Qhref=\\\"/imgres?imgurl=\\\\E\");\n for (String s : array) {\n if (s.startsWith(\"http://\") || s.startsWith(\"https://\") && s.contains(\"&\")) {\n String s1 = s.substring(0, s.indexOf(\"&\"));\n googleImages.add(s1);\n }\n }\n } catch (Exception ex4) {\n MusicBoxView.showErrorDialog(ex4);\n }\n }\n }\n", "label": 0} {"func1": " public void serialize(OutputStream out) throws IOException, BadIMSCPException {\n ensureParsed();\n ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser();\n parser.setContentPackage(cp);\n if (on_disk != null) on_disk.delete();\n on_disk = createTemporaryFile();\n parser.serialize(on_disk);\n InputStream in = new FileInputStream(on_disk);\n IOUtils.copy(in, out);\n }\n", "func2": " public void updateUser(final User user) throws IOException {\n try {\n Connection conn = null;\n boolean autoCommit = false;\n try {\n conn = pool.getConnection();\n autoCommit = conn.getAutoCommit();\n conn.setAutoCommit(false);\n final PreparedStatement updateUser = conn.prepareStatement(\"update users set mainRoleId=? where userId=?\");\n updateUser.setInt(1, user.getMainRole().getId());\n updateUser.setString(2, user.getUserId());\n updateUser.executeUpdate();\n final PreparedStatement deleteRoles = conn.prepareStatement(\"delete from userRoles where userId=?\");\n deleteRoles.setString(1, user.getUserId());\n deleteRoles.executeUpdate();\n final PreparedStatement insertRoles = conn.prepareStatement(\"insert into userRoles (userId, roleId) values (?,?)\");\n for (final Role role : user.getRoles()) {\n insertRoles.setString(1, user.getUserId());\n insertRoles.setInt(2, role.getId());\n insertRoles.executeUpdate();\n }\n conn.commit();\n } catch (Throwable t) {\n if (conn != null) conn.rollback();\n throw new SQLException(t.toString());\n } finally {\n if (conn != null) {\n conn.setAutoCommit(autoCommit);\n conn.close();\n }\n }\n } catch (final SQLException sqle) {\n log.log(Level.SEVERE, sqle.toString(), sqle);\n throw new IOException(sqle.toString());\n }\n }\n", "label": 0} {"func1": " private static void copyFile(String src, String target) throws IOException {\n FileChannel ic = new FileInputStream(src).getChannel();\n FileChannel oc = new FileOutputStream(target).getChannel();\n ic.transferTo(0, ic.size(), oc);\n ic.close();\n oc.close();\n }\n", "func2": " public boolean actEstadoEnBD(int idRonda) {\n int intResult = 0;\n String sql = \"UPDATE ronda \" + \" SET estado = 1\" + \" WHERE numeroRonda = \" + idRonda;\n try {\n connection = conexionBD.getConnection();\n connection.setAutoCommit(false);\n ps = connection.prepareStatement(sql);\n intResult = ps.executeUpdate();\n connection.commit();\n } catch (SQLException ex) {\n ex.printStackTrace();\n try {\n connection.rollback();\n } catch (SQLException exe) {\n exe.printStackTrace();\n }\n } finally {\n conexionBD.close(ps);\n conexionBD.close(connection);\n }\n return (intResult > 0);\n }\n", "label": 0} {"func1": " public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "func2": " private void extractZipFile(String filename, JTextPane progressText) throws IOException {\n String destinationname = \"\";\n byte[] buf = new byte[1024];\n ZipInputStream zipinputstream = null;\n ZipEntry zipentry;\n zipinputstream = new ZipInputStream(new FileInputStream(filename));\n while ((zipentry = zipinputstream.getNextEntry()) != null) {\n String entryName = zipentry.getName();\n if (progressText != null) {\n progressText.setText(\"extracting \" + entryName);\n }\n int n;\n FileOutputStream fileoutputstream;\n if (zipentry.isDirectory()) {\n (new File(destinationname + entryName)).mkdir();\n continue;\n }\n fileoutputstream = new FileOutputStream(destinationname + entryName);\n while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n);\n fileoutputstream.close();\n zipinputstream.closeEntry();\n }\n if (progressText != null) {\n progressText.setText(\"Files extracted\");\n }\n zipinputstream.close();\n }\n", "label": 0} {"func1": " private static Properties loadPropertiesFromClasspath(String path) {\n Enumeration locations;\n Properties props = new Properties();\n try {\n locations = Thread.currentThread().getContextClassLoader().getResources(path);\n while (locations.hasMoreElements()) {\n URL url = locations.nextElement();\n InputStream in = url.openStream();\n props.load(in);\n in.close();\n logger.config(\"Load properties from \" + url);\n }\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"load properties from classpath \\\"\" + path + \"\\\" failed\", e);\n }\n return props;\n }\n", "func2": " public boolean update(String dbName, Query[] queries) throws ServiceException {\n Connection con = null;\n PreparedStatement pstmt = null;\n int rows = 0;\n try {\n con = getDbConnection().getConnection(dbName);\n con.setAutoCommit(false);\n for (int i = 0; i < queries.length; i++) {\n Query query = queries[i];\n System.out.println(query.getSql());\n pstmt = con.prepareStatement(query.getSql());\n addParametersToQuery(query, pstmt);\n rows += pstmt.executeUpdate();\n }\n con.commit();\n return rows > 0;\n } catch (DbException e) {\n log.error(\"[DAOService::update] \" + e.getMessage(), e);\n log.error(\"[DAOService::update] Execute rollback \" + e.getMessage(), e);\n try {\n con.rollback();\n } catch (SQLException e1) {\n log.error(\"[DAOService::update] Errore durante il rollback \" + e.getMessage(), e);\n throw new ServiceException(e.getMessage());\n }\n throw new ServiceException(e.getMessage());\n } catch (SQLException e) {\n log.error(\"[DAOService::update] \" + e.getMessage(), e);\n try {\n con.rollback();\n } catch (SQLException e1) {\n log.error(\"[DAOService::update] Errore durante il rollback \" + e.getMessage(), e);\n throw new ServiceException(e.getMessage());\n }\n throw new ServiceException(e.getMessage());\n } finally {\n closeConnection(con, pstmt, null);\n }\n }\n", "label": 0} {"func1": " private static HttpURLConnection sendPost(String reqUrl, Map parameters) {\n HttpURLConnection urlConn = null;\n try {\n String params = generatorParamString(parameters);\n URL url = new URL(reqUrl);\n urlConn = (HttpURLConnection) url.openConnection();\n urlConn.setRequestMethod(\"POST\");\n urlConn.setConnectTimeout(5000);\n urlConn.setReadTimeout(5000);\n urlConn.setDoOutput(true);\n byte[] b = params.getBytes();\n urlConn.getOutputStream().write(b, 0, b.length);\n urlConn.getOutputStream().flush();\n urlConn.getOutputStream().close();\n } catch (Exception e) {\n throw new RuntimeException(e.getMessage(), e);\n }\n return urlConn;\n }\n", "func2": " private void doImageProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {\n response.setContentType(\"image/\" + type + \"\");\n Point imgSize = null;\n if (width > 0 || height > 0) {\n imgSize = new Point(width, height);\n }\n if (fmt != null && imageFormats.containsKey(fmt)) {\n imgSize = imageFormats.get(fmt);\n }\n InputStream imageInputStream = inputStream != null ? inputStream : imageUrl.openStream();\n if (imageInputStream == null) {\n throw new RuntimeException(\"File \" + imageUrl + \" does not exist!\");\n }\n if (imgSize == null) {\n IOUtils.copy(imageInputStream, response.getOutputStream());\n } else {\n byte[] imageBytes = getImageBytes(type, imgSize, imageInputStream);\n response.setContentLength(imageBytes.length);\n response.getOutputStream().write(imageBytes);\n }\n response.getOutputStream().flush();\n response.getOutputStream().close();\n }\n", "label": 0} {"func1": " public void parse() throws ParserConfigurationException, SAXException, IOException {\n DefaultHttpClient httpclient = initialise();\n HttpResponse result = httpclient.execute(new HttpGet(urlString));\n SAXParserFactory spf = SAXParserFactory.newInstance();\n if (spf != null) {\n SAXParser sp = spf.newSAXParser();\n sp.parse(result.getEntity().getContent(), this);\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 0} {"func1": " private void updateFile(File file) throws FileNotFoundException, IOException {\n File destFile = new File(file.getPath().replace(URL_UNZIPPED_PREFIX + latestVersion, \"\"));\n FileChannel in = null;\n FileChannel out = null;\n try {\n if (!destFile.exists()) {\n destFile.getParentFile().mkdirs();\n destFile.createNewFile();\n }\n in = new FileInputStream(file).getChannel();\n out = new FileOutputStream(destFile).getChannel();\n in.transferTo(0, in.size(), out);\n } finally {\n if (out != null) out.close();\n if (in != null) in.close();\n }\n }\n", "func2": " String fetch_pls(String pls) {\n InputStream pstream = null;\n if (pls.startsWith(\"http://\")) {\n try {\n URL url = null;\n if (running_as_applet) {\n url = new URL(getCodeBase(), pls);\n } else {\n url = new URL(pls);\n }\n URLConnection urlc = url.openConnection();\n pstream = urlc.getInputStream();\n } catch (Exception ee) {\n System.err.println(ee);\n return null;\n }\n }\n if (pstream == null && !running_as_applet) {\n try {\n pstream = new FileInputStream(System.getProperty(\"user.dir\") + System.getProperty(\"file.separator\") + pls);\n } catch (Exception ee) {\n System.err.println(ee);\n return null;\n }\n }\n String line = null;\n while (true) {\n try {\n line = readline(pstream);\n } catch (Exception e) {\n }\n if (line == null) {\n break;\n }\n if (line.startsWith(\"File1=\")) {\n byte[] foo = line.getBytes();\n int i = 6;\n for (; i < foo.length; i++) {\n if (foo[i] == 0x0d) {\n break;\n }\n }\n return line.substring(6, i);\n }\n }\n return null;\n }\n", "label": 0} {"func1": " public InputStream retrieveStream(String url) {\n HttpGet getRequest = new HttpGet(url);\n try {\n HttpResponse getResponse = getClient().execute(getRequest);\n final int statusCode = getResponse.getStatusLine().getStatusCode();\n if (statusCode != HttpStatus.SC_OK) {\n Log.w(getClass().getSimpleName(), \"Error \" + statusCode + \" for URL \" + url);\n return null;\n }\n HttpEntity getResponseEntity = getResponse.getEntity();\n return getResponseEntity.getContent();\n } catch (Exception e) {\n getRequest.abort();\n Log.w(getClass().getSimpleName(), \"Error for URL \" + url, e);\n }\n return null;\n }\n", "func2": " public static String fromHtml(URL url, String defaultEncoding, boolean overrideEncoding) throws IOException, BadDocumentException {\n URLConnection conn = url.openConnection();\n String contentType = conn.getContentType();\n String encoding = conn.getContentEncoding();\n if (encoding == null) {\n int i = contentType.indexOf(\"charset\");\n if (i >= 0) {\n String s = contentType.substring(i);\n i = s.indexOf('=');\n if (i >= 0) {\n s = contentType.substring(i + 1).trim();\n encoding = s.replace(\"\\'\", \"\").replace(\"\\\"\", \"\").trim();\n if (encoding.equals(\"\")) {\n encoding = defaultEncoding;\n }\n }\n } else {\n encoding = defaultEncoding;\n }\n }\n String expected = \"text/html\";\n if (contentType == null) {\n DefaultXMLNoteErrorHandler.warning(null, 90190, \"Returned content type for url.openConnection() is null\");\n contentType = expected;\n }\n int index = contentType.indexOf(';');\n if (index >= 0) {\n contentType = contentType.substring(0, index).trim();\n }\n if (!contentType.equals(expected)) {\n String msg = translator.translate(\"The content type of url '%s' is not '%s', it is '%s'\");\n throw new BadDocumentException(String.format(msg, url.toString(), expected, contentType));\n }\n BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));\n return fromHtml(in, encoding);\n }\n", "label": 0} {"func1": " public static byte[] encrypt(String x) throws Exception {\n java.security.MessageDigest d = null;\n d = java.security.MessageDigest.getInstance(\"SHA-1\");\n d.reset();\n d.update(x.getBytes());\n return d.digest();\n }\n", "func2": " private String getFullScreenUrl() {\n progressDown.setIndeterminate(true);\n System.out.println(\"Har: \" + ytUrl);\n String u = ytUrl;\n URLConnection conn = null;\n String line = null;\n String data = \"\";\n String fullUrl = \"\";\n try {\n URL url = new URL(u);\n conn = url.openConnection();\n conn.setDoOutput(true);\n BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n while ((line = rd.readLine()) != null) {\n if (line.contains(\"fullscreenUrl\")) {\n data = line.trim();\n }\n }\n rd.close();\n System.out.println(data);\n int start = 0;\n String[] lines = data.split(\"&\");\n String[] tmp = null;\n String video_id = null;\n String t = null;\n String title = null;\n for (int i = 0; i < lines.length; i++) {\n if (lines[i].startsWith(\"video_id=\")) {\n tmp = lines[i].split(\"=\");\n video_id = tmp[1];\n }\n if (lines[i].startsWith(\"t=\")) {\n tmp = lines[i].split(\"=\");\n t = tmp[1];\n }\n if (lines[i].startsWith(\"title=\")) {\n tmp = lines[i].split(\"=\");\n title = tmp[1].substring(0, (tmp[1].length() - 2));\n }\n System.out.println(lines[i]);\n }\n System.out.println(\"So we got...\");\n System.out.println(\"video_id: \" + video_id);\n System.out.println(\"t: \" + t);\n System.out.println(\"title: \" + title);\n ytTitle = title;\n fullUrl = \"http://www.youtube.com/get_video.php?video_id=\" + video_id + \"&t=\" + t;\n } catch (Exception e) {\n System.err.println(\"Error: \" + e.getLocalizedMessage());\n }\n progressDown.setIndeterminate(false);\n return fullUrl;\n }\n", "label": 0} {"func1": " private InputStream sendRequest(SequenceI seq) throws UnsupportedEncodingException, IOException {\n StringBuilder putBuf = new StringBuilder();\n processOptions(putBuf);\n putBuf.append(\"INPUT_SEQUENCE=\");\n putBuf.append(URLEncoder.encode(\">\" + seq.getName() + \"\\n\", ENCODING));\n putBuf.append(URLEncoder.encode(seq.getResidues(), ENCODING));\n URL url = new URL(PRIMER_BLAST_URL);\n URLConnection conn = url.openConnection();\n conn.setDoOutput(true);\n OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\n wr.write(putBuf.toString());\n wr.flush();\n wr.close();\n apollo.util.IOUtil.informationDialog(\"Primer-BLAST request sent\");\n return conn.getInputStream();\n }\n", "func2": " private synchronized void loadDDL() throws IOException {\n try {\n conn.createStatement().executeQuery(\"SELECT * FROM non_generic_favs\").close();\n } catch (SQLException e) {\n Statement stmt = null;\n if (!e.getMessage().matches(ERR_MISSING_TABLE)) {\n e.printStackTrace(System.out);\n throw new IOException(\"Error on initial data store read\");\n }\n String[] qry = { \"CREATE TABLE non_generic_favs (id INT NOT NULL PRIMARY KEY)\", \"CREATE TABLE ignore_chan_favs (id INT NOT NULL PRIMARY KEY, chanlist LONG VARCHAR)\", \"CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))\", \"INSERT INTO settings (var, val) VALUES ('schema', '1')\" };\n try {\n conn.setAutoCommit(false);\n stmt = conn.createStatement();\n for (String q : qry) stmt.executeUpdate(q);\n conn.commit();\n } catch (SQLException e2) {\n try {\n conn.rollback();\n } catch (SQLException e3) {\n e3.printStackTrace(System.out);\n }\n e2.printStackTrace(new PrintWriter(System.out));\n throw new IOException(\"Error initializing data store\");\n } finally {\n if (stmt != null) {\n try {\n stmt.close();\n } catch (SQLException e4) {\n e4.printStackTrace(System.out);\n throw new IOException(\"Unable to cleanup data store resources\");\n }\n }\n try {\n conn.setAutoCommit(true);\n } catch (SQLException e3) {\n e3.printStackTrace(System.out);\n throw new IOException(\"Unable to reset data store auto commit\");\n }\n }\n }\n return;\n }\n", "label": 0} {"func1": " public static String SHA1(String text) {\n byte[] sha1hash = new byte[40];\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n sha1hash = md.digest();\n } catch (UnsupportedEncodingException ex) {\n Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);\n } catch (NoSuchAlgorithmException ex) {\n Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);\n }\n return convertToHex(sha1hash);\n }\n", "func2": " public static ArrayList loadURLToStrings(URL url, int maxLines, String userAgent, int timeout) throws IOException {\n URLConnection connection = url.openConnection();\n if (userAgent != null && userAgent.trim().length() > 0) {\n connection.setRequestProperty(\"User-Agent\", userAgent);\n } else {\n connection.setRequestProperty(\"User-Agent\", \"Mozilla/5.0 (compatible; astrominer/1.0;)\");\n }\n if (timeout > 0) {\n connection.setConnectTimeout(timeout);\n }\n connection.connect();\n return loadURLToStrings(connection, maxLines);\n }\n", "label": 0} {"func1": " private void copy(File inputFile, File outputFile) throws Exception {\n FileReader in = new FileReader(inputFile);\n FileWriter out = new FileWriter(outputFile);\n int c;\n while ((c = in.read()) != -1) out.write(c);\n in.close();\n out.close();\n }\n", "func2": " public boolean actEstadoEnBD(int idRonda) {\n int intResult = 0;\n String sql = \"UPDATE ronda \" + \" SET estado = 1\" + \" WHERE numeroRonda = \" + idRonda;\n try {\n connection = conexionBD.getConnection();\n connection.setAutoCommit(false);\n ps = connection.prepareStatement(sql);\n intResult = ps.executeUpdate();\n connection.commit();\n } catch (SQLException ex) {\n ex.printStackTrace();\n try {\n connection.rollback();\n } catch (SQLException exe) {\n exe.printStackTrace();\n }\n } finally {\n conexionBD.close(ps);\n conexionBD.close(connection);\n }\n return (intResult > 0);\n }\n", "label": 0} {"func1": " public void open(Input input) throws IOException, ResolverException {\n if (!input.isUriDefinitive()) return;\n URI uri;\n try {\n uri = new URI(input.getUri());\n } catch (URISyntaxException e) {\n throw new ResolverException(e);\n }\n if (!uri.isAbsolute()) throw new ResolverException(\"cannot open relative URI: \" + uri);\n URL url = new URL(uri.toASCIIString());\n input.setByteStream(url.openStream());\n }\n", "func2": " private String md5(String uri) throws ConnoteaRuntimeException {\n try {\n MessageDigest messageDigest = MessageDigest.getInstance(\"MD5\");\n messageDigest.update(uri.getBytes());\n byte[] bytes = messageDigest.digest();\n StringBuffer stringBuffer = new StringBuffer();\n for (byte b : bytes) {\n String hex = Integer.toHexString(0xff & b);\n if (hex.length() == 1) {\n stringBuffer.append('0');\n }\n stringBuffer.append(hex);\n }\n return stringBuffer.toString();\n } catch (NoSuchAlgorithmException e) {\n throw new ConnoteaRuntimeException(e);\n }\n }\n", "label": 0} {"func1": " public void hyperlinkUpdate(HyperlinkEvent e) {\n if (e.getEventType() == EventType.ACTIVATED) {\n try {\n URL url = e.getURL();\n InputStream stream = url.openStream();\n try {\n StringWriter writer = new StringWriter();\n IOUtils.copy(stream, writer, \"UTF-8\");\n JEditorPane editor = new JEditorPane(\"text/plain\", writer.toString());\n editor.setEditable(false);\n editor.setBackground(Color.WHITE);\n editor.setCaretPosition(0);\n editor.setPreferredSize(new Dimension(600, 400));\n String name = url.toString();\n name = name.substring(name.lastIndexOf('/') + 1);\n JDialog dialog = new JDialog(this, \"内容解析: \" + name);\n dialog.add(new JScrollPane(editor));\n dialog.pack();\n dialog.setVisible(true);\n } finally {\n stream.close();\n }\n } catch (IOException exception) {\n exception.printStackTrace();\n }\n }\n }\n", "func2": " public static String getUniqueKey() {\n String digest = \"\";\n try {\n final MessageDigest md = MessageDigest.getInstance(\"MD5\");\n final String timeVal = \"\" + (System.currentTimeMillis() + 1);\n String localHost = \"\";\n try {\n localHost = InetAddress.getLocalHost().toString();\n } catch (UnknownHostException e) {\n println(\"Warn: getUniqueKey(), Error trying to get localhost\" + e.getMessage());\n }\n final String randVal = \"\" + new Random().nextInt();\n final String val = timeVal + localHost + randVal;\n md.reset();\n md.update(val.getBytes());\n digest = toHexString(md.digest());\n } catch (NoSuchAlgorithmException e) {\n println(\"Warn: getUniqueKey() \" + e);\n }\n return digest;\n }\n", "label": 0} {"func1": " public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException {\n if (dest.exists()) if (force) dest.delete(); else throw new IOException(\"Cannot overwrite existing file: \" + dest.getName());\n byte[] buffer = new byte[bufSize];\n int read = 0;\n InputStream in = null;\n OutputStream out = null;\n try {\n in = new FileInputStream(src);\n out = new FileOutputStream(dest);\n while (true) {\n read = in.read(buffer);\n if (read == -1) break;\n out.write(buffer, 0, read);\n }\n } finally {\n if (in != null) try {\n in.close();\n } finally {\n if (out != null) out.close();\n }\n }\n }\n", "func2": " private void generateDeviceUUID() {\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(deviceType.getBytes());\n md5.update(internalId.getBytes());\n md5.update(bindAddress.getHostName().getBytes());\n StringBuffer hexString = new StringBuffer();\n byte[] digest = md5.digest();\n for (int i = 0; i < digest.length; i++) {\n hexString.append(Integer.toHexString(0xFF & digest[i]));\n }\n uuid = hexString.toString().toUpperCase();\n } catch (Exception ex) {\n RuntimeException runTimeEx = new RuntimeException(\"Unexpected error during MD5 hash creation, check your JRE\");\n runTimeEx.initCause(ex);\n throw runTimeEx;\n }\n }\n", "label": 0} {"func1": " private void readIntoList(URL url, Map list) {\n try {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n String inputLine;\n while ((inputLine = in.readLine()) != null) {\n int commandNameBegin = inputLine.indexOf(\">\") + 1;\n int commandNameEnd = inputLine.indexOf(\"
\");\n JMenuItem item = new JMenuItem(\"\" + inputLine + \"\");\n if (list == allRooms) {\n item.setActionCommand(\"/room \" + inputLine.substring(commandNameBegin, commandNameEnd));\n } else {\n item.setActionCommand(\"/\" + inputLine.substring(commandNameBegin, commandNameEnd) + \" \");\n }\n item.addActionListener(new ActionListener() {\n\n public void actionPerformed(ActionEvent e) {\n jTextField1.setText(e.getActionCommand());\n popup.setVisible(false);\n }\n });\n list.put(inputLine.substring(commandNameBegin, commandNameEnd), item);\n }\n in.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "func2": " public static InputStream getFileInputStream(String path) throws IOException {\n InputStream is = null;\n File file = new File(path);\n if (file.exists()) is = new BufferedInputStream(new FileInputStream(file));\n if (is == null) {\n URL url = FileUtils.class.getClassLoader().getResource(path);\n is = (url == null) ? null : url.openStream();\n }\n return is;\n }\n", "label": 0} {"func1": " public static String encrypt(String text) throws NoSuchAlgorithmException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n try {\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "func2": " public Vector getNetworkServersIPs(String netaddress) {\n Vector result = new Vector();\n boolean serverline = false;\n String line;\n String[] splitline;\n try {\n URL url = new URL(netaddress);\n URLConnection connection = url.openConnection();\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n while ((line = reader.readLine()) != null) {\n if ((serverline) && line.startsWith(\";\")) {\n serverline = false;\n }\n if (serverline) {\n splitline = line.split(\":\");\n result.add(splitline[1]);\n }\n if (line.startsWith(\"!SERVERS\")) {\n serverline = true;\n }\n }\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return result;\n }\n", "label": 0} {"func1": " @Test\n public void testLoadHttpGzipped() throws Exception {\n String url = HTTP_GZIPPED;\n LoadingInfo loadingInfo = Utils.openFileObject(fsManager.resolveFile(url));\n InputStream contentInputStream = loadingInfo.getContentInputStream();\n byte[] actual = IOUtils.toByteArray(contentInputStream);\n byte[] expected = IOUtils.toByteArray(new GZIPInputStream(new URL(url).openStream()));\n assertEquals(expected.length, actual.length);\n }\n", "func2": " public void setImg() {\n JFileChooser jFileChooser1 = new JFileChooser();\n String separator = \"\";\n if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) {\n setPath(jFileChooser1.getSelectedFile().getPath());\n separator = jFileChooser1.getSelectedFile().separator;\n File dirImg = new File(\".\" + separator + \"images\");\n if (!dirImg.exists()) {\n dirImg.mkdir();\n }\n int index = getPath().lastIndexOf(separator);\n String imgName = getPath().substring(index);\n String newPath = dirImg + imgName;\n try {\n File inputFile = new File(getPath());\n File outputFile = new File(newPath);\n if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) {\n FileInputStream in = new FileInputStream(inputFile);\n FileOutputStream out = new FileOutputStream(outputFile);\n int c;\n while ((c = in.read()) != -1) out.write(c);\n in.close();\n out.close();\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n LogHandler.log(ex.getMessage(), Level.INFO, \"LOG_MSG\", isLoggingEnabled());\n JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + \"-\" + getClass(), \"Set image\", JOptionPane.ERROR_MESSAGE);\n }\n setPath(newPath);\n bckImg = new ImageIcon(getPath());\n }\n }\n", "label": 0} {"func1": " private void updateFile(File file) throws FileNotFoundException, IOException {\n File destFile = new File(file.getPath().replace(URL_UNZIPPED_PREFIX + latestVersion, \"\"));\n FileChannel in = null;\n FileChannel out = null;\n try {\n if (!destFile.exists()) {\n destFile.getParentFile().mkdirs();\n destFile.createNewFile();\n }\n in = new FileInputStream(file).getChannel();\n out = new FileOutputStream(destFile).getChannel();\n in.transferTo(0, in.size(), out);\n } finally {\n if (out != null) out.close();\n if (in != null) in.close();\n }\n }\n", "func2": " public void update(String channelPath, String dataField, String fatherDocId) {\n String sqlInitial = \"select uri from t_ip_doc_res where doc_id = '\" + fatherDocId + \"' and type=\" + \" '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n String sqlsortURL = \"update t_ip_doc_res set uri = ? where doc_id = '\" + fatherDocId + \"' \" + \" and type = '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n Connection conn = null;\n ResultSet rs = null;\n PreparedStatement ps = null;\n try {\n dbo = (ERDBOperation) createDBOperation();\n String url = \"\";\n boolean flag = true;\n StringTokenizer st = null;\n conn = dbo.getConnection();\n conn.setAutoCommit(false);\n ps = conn.prepareStatement(sqlInitial);\n rs = ps.executeQuery();\n if (rs.next()) url = rs.getString(1);\n if (!url.equals(\"\")) {\n st = new StringTokenizer(url, \",\");\n String sortDocId = \"\";\n while (st.hasMoreTokens()) {\n if (flag) {\n sortDocId = \"'\" + st.nextToken() + \"'\";\n flag = false;\n } else {\n sortDocId = sortDocId + \",\" + \"'\" + st.nextToken() + \"'\";\n }\n }\n String sqlsort = \"select id from t_ip_doc where id in (\" + sortDocId + \") order by \" + dataField;\n ps = conn.prepareStatement(sqlsort);\n rs = ps.executeQuery();\n String sortURL = \"\";\n boolean sortflag = true;\n while (rs.next()) {\n if (sortflag) {\n sortURL = rs.getString(1);\n sortflag = false;\n } else {\n sortURL = sortURL + \",\" + rs.getString(1);\n }\n }\n ps = conn.prepareStatement(sqlsortURL);\n ps.setString(1, sortURL);\n ps.executeUpdate();\n }\n conn.commit();\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n } finally {\n close(rs, null, ps, conn, dbo);\n }\n }\n", "label": 0} {"func1": " public static String getDigest(String user, String realm, String password, String method, String uri, String nonce) {\n String digest1 = user + \":\" + realm + \":\" + password;\n String digest2 = method + \":\" + uri;\n try {\n MessageDigest digestOne = MessageDigest.getInstance(\"md5\");\n digestOne.update(digest1.getBytes());\n String hexDigestOne = getHexString(digestOne.digest());\n MessageDigest digestTwo = MessageDigest.getInstance(\"md5\");\n digestTwo.update(digest2.getBytes());\n String hexDigestTwo = getHexString(digestTwo.digest());\n String digest3 = hexDigestOne + \":\" + nonce + \":\" + hexDigestTwo;\n MessageDigest digestThree = MessageDigest.getInstance(\"md5\");\n digestThree.update(digest3.getBytes());\n String hexDigestThree = getHexString(digestThree.digest());\n return hexDigestThree;\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " public static void copyFromTo(File srcFile, File destFile) {\n FileChannel in = null, out = null;\n FileInputStream fis = null;\n FileOutputStream fos = null;\n try {\n fis = new FileInputStream(srcFile);\n } catch (FileNotFoundException fnfe) {\n System.out.println(\"File: \" + srcFile.toString());\n System.out.println(\"file does not exist, \" + \"is a directory rather than a regular file, \" + \"or for some other reason cannot be opened for reading\");\n System.exit(-1);\n }\n try {\n fos = new FileOutputStream(destFile);\n } catch (FileNotFoundException fnfe) {\n System.out.println(\"File: \" + destFile.toString());\n System.out.println(\"file exists but is a directory rather than a regular file, \" + \"does not exist but cannot be created, \" + \"or cannot be opened for any other reason\");\n System.exit(-1);\n }\n try {\n in = fis.getChannel();\n out = fos.getChannel();\n in.transferTo(0, in.size(), out);\n fos.flush();\n fos.close();\n out.close();\n fis.close();\n in.close();\n System.out.println(\"Completed copying \" + srcFile.toString() + \" to \" + destFile.toString());\n } catch (IOException ioe) {\n System.out.println(\"IOException copying file: \" + ioe.getMessage());\n System.exit(-1);\n }\n long srcModified = srcFile.lastModified();\n if (srcModified > 0L && destFile.exists()) {\n destFile.setLastModified(srcModified);\n }\n }\n", "label": 0} {"func1": " public boolean deleteRoleType(int id, int namespaceId, boolean removeReferencesInRoleTypes, DTSPermission permit) throws SQLException, PermissionException, DTSValidationException {\n checkPermission(permit, String.valueOf(namespaceId));\n boolean exist = isRoleTypeUsed(namespaceId, id);\n if (exist) {\n throw new DTSValidationException(ApelMsgHandler.getInstance().getMsg(\"DTS-0034\"));\n }\n if (!removeReferencesInRoleTypes) {\n StringBuffer msgBuf = new StringBuffer();\n DTSTransferObject[] objects = fetchRightIdentityReferences(namespaceId, id);\n if (objects.length > 0) {\n msgBuf.append(\"Role Type is Right Identity in one or more Role Types.\");\n }\n objects = fetchParentReferences(namespaceId, id);\n if (objects.length > 0) {\n if (msgBuf.length() > 0) {\n msgBuf.append(\"\\n\");\n }\n msgBuf.append(\"Role Type is Parent of one or more Role Types.\");\n }\n if (msgBuf.length() > 0) {\n throw new DTSValidationException(msgBuf.toString());\n }\n }\n String sqlRightId = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE_RIGHT_IDENTITY_REF\");\n String sqlParent = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE_PARENT_REF\");\n String sql = getDAO().getStatement(ROLE_TYPE_TABLE_KEY, \"DELETE\");\n PreparedStatement pstmt = null;\n boolean success = false;\n long typeGid = getGID(namespaceId, id);\n conn.setAutoCommit(false);\n int defaultLevel = conn.getTransactionIsolation();\n conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n try {\n pstmt = conn.prepareStatement(sqlRightId);\n pstmt.setLong(1, typeGid);\n pstmt.executeUpdate();\n pstmt.close();\n pstmt = conn.prepareStatement(sqlParent);\n pstmt.setLong(1, typeGid);\n pstmt.executeUpdate();\n pstmt.close();\n pstmt = conn.prepareStatement(sql);\n pstmt.setLong(1, typeGid);\n int count = pstmt.executeUpdate();\n success = (count == 1);\n conn.commit();\n } catch (SQLException e) {\n conn.rollback();\n throw e;\n } finally {\n conn.setTransactionIsolation(defaultLevel);\n conn.setAutoCommit(true);\n closeStatement(pstmt);\n }\n return success;\n }\n", "func2": " public static void main(String[] args) throws Exception {\n if (args.length != 2) {\n System.out.println(\"Usage: URLDumper \");\n System.exit(1);\n }\n String location = args[0];\n String file = args[1];\n URL url = new URL(location);\n FileOutputStream fos = new FileOutputStream(file);\n byte[] bytes = new byte[4096];\n InputStream is = url.openStream();\n int read;\n while ((read = is.read(bytes)) != -1) {\n fos.write(bytes, 0, read);\n }\n is.close();\n fos.close();\n }\n", "label": 0} {"func1": " public static String doPost(String URL, List params) {\n try {\n OauthUtil util = new OauthUtil();\n URI uri = new URI(URL);\n HttpClient httpclient = util.getNewHttpClient();\n HttpPost postMethod = new HttpPost(uri);\n StringBuffer paramString = new StringBuffer();\n paramString.append(\"OAuth\");\n for (int i = 0; i < params.size(); i++) {\n paramString.append(\" \" + params.get(i).getName());\n paramString.append(\"=\\\"\" + encodeUrl(params.get(i).getValue()) + \"\\\",\");\n }\n String xx = paramString.substring(0, paramString.length() - 1);\n postMethod.addHeader(\"Authorization\", xx);\n HttpResponse httpResponse = httpclient.execute(postMethod);\n if (httpResponse.getStatusLine().getStatusCode() == 200) {\n String strResult = EntityUtils.toString(httpResponse.getEntity());\n Log.i(\"DEBUG\", \"result: \" + strResult);\n return strResult;\n }\n } catch (Exception e) {\n Log.i(\"DEBUG\", e.toString());\n }\n return null;\n }\n", "func2": " public String transformByMD5(String password) throws XSServiceException {\n MessageDigest md5;\n byte[] output;\n StringBuffer bufferPass;\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n logger.warn(\"DataAccessException thrown while getting MD5 algorithm:\" + e.getMessage(), e);\n throw new XSServiceException(\"Database error while saving user\");\n }\n md5.reset();\n md5.update(password.getBytes());\n output = md5.digest();\n bufferPass = new StringBuffer();\n for (byte b : output) {\n bufferPass.append(Integer.toHexString(0xff & b).length() == 1 ? \"0\" + Integer.toHexString(0xff & b) : Integer.toHexString(0xff & b));\n }\n return bufferPass.toString();\n }\n", "label": 0} {"func1": " public static void main(String[] args) throws IOException {\n String urltext = \"http://www.vogella.de\";\n URL url = new URL(urltext);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n String inputLine;\n while ((inputLine = in.readLine()) != null) {\n System.out.println(inputLine);\n }\n in.close();\n }\n", "func2": " public DataRecord addRecord(InputStream input) throws DataStoreException {\n File temporary = null;\n try {\n temporary = newTemporaryFile();\n DataIdentifier tempId = new DataIdentifier(temporary.getName());\n usesIdentifier(tempId);\n long length = 0;\n MessageDigest digest = MessageDigest.getInstance(DIGEST);\n OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest);\n try {\n length = IOUtils.copyLarge(input, output);\n } finally {\n output.close();\n }\n DataIdentifier identifier = new DataIdentifier(digest.digest());\n File file;\n synchronized (this) {\n usesIdentifier(identifier);\n file = getFile(identifier);\n if (!file.exists()) {\n File parent = file.getParentFile();\n parent.mkdirs();\n if (temporary.renameTo(file)) {\n temporary = null;\n } else {\n throw new IOException(\"Can not rename \" + temporary.getAbsolutePath() + \" to \" + file.getAbsolutePath() + \" (media read only?)\");\n }\n } else {\n long now = System.currentTimeMillis();\n if (getLastModified(file) < now + ACCESS_TIME_RESOLUTION) {\n setLastModified(file, now + ACCESS_TIME_RESOLUTION);\n }\n }\n if (file.length() != length) {\n if (!file.isFile()) {\n throw new IOException(\"Not a file: \" + file);\n }\n throw new IOException(DIGEST + \" collision: \" + file);\n }\n }\n inUse.remove(tempId);\n return new FileDataRecord(identifier, file);\n } catch (NoSuchAlgorithmException e) {\n throw new DataStoreException(DIGEST + \" not available\", e);\n } catch (IOException e) {\n throw new DataStoreException(\"Could not add record\", e);\n } finally {\n if (temporary != null) {\n temporary.delete();\n }\n }\n }\n", "label": 0} {"func1": " public static byte[] hash(final byte[] saltBefore, final String content, final byte[] saltAfter, final int repeatedHashingCount) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n if (content == null) return null;\n final MessageDigest digest = MessageDigest.getInstance(DIGEST);\n if (digestLength == -1) digestLength = digest.getDigestLength();\n for (int i = 0; i < repeatedHashingCount; i++) {\n if (i > 0) digest.update(digest.digest());\n digest.update(saltBefore);\n digest.update(content.getBytes(WebCastellumFilter.DEFAULT_CHARACTER_ENCODING));\n digest.update(saltAfter);\n }\n return digest.digest();\n }\n", "func2": " private static void loadDefaultPreferences() {\n try {\n URL url = ClassLoader.getSystemResource(\"OpenDarkRoom.defaults.properties\");\n preferences.load(url.openStream());\n } catch (FileNotFoundException e) {\n log.error(\"Default preferences file not found\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " public static String getMD5Hash(String original) {\n StringBuffer sb = new StringBuffer();\n try {\n StringReader sr = null;\n int crypt_byte = 0;\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(original.getBytes());\n byte[] digest = md.digest();\n sr = new StringReader(new String(digest, \"ISO8859_1\"));\n while ((crypt_byte = sr.read()) != -1) {\n String hexString = Integer.toHexString(crypt_byte);\n if (crypt_byte < 16) {\n hexString = \"0\" + hexString;\n }\n sb.append(hexString);\n }\n } catch (NoSuchAlgorithmException nsae) {\n } catch (IOException ioe) {\n }\n return sb.toString();\n }\n", "label": 0} {"func1": " public List getTicketsForQueue(final String queueName, long limit) {\n getSession();\n final List params = new ArrayList();\n params.add(new BasicNameValuePair(\"query\", \"Queue='\" + queueName + \"' AND Status='open'\"));\n params.add(new BasicNameValuePair(\"format\", \"i\"));\n params.add(new BasicNameValuePair(\"orderby\", \"-id\"));\n final HttpGet get = new HttpGet(m_baseURL + \"/REST/1.0/search/ticket?\" + URLEncodedUtils.format(params, \"UTF-8\"));\n final List tickets = new ArrayList();\n final List ticketIds = new ArrayList();\n try {\n final HttpResponse response = getClient().execute(get);\n int responseCode = response.getStatusLine().getStatusCode();\n if (responseCode != HttpStatus.SC_OK) {\n throw new RequestTrackerException(\"Received a non-200 response code from the server: \" + responseCode);\n } else {\n InputStreamReader isr = null;\n BufferedReader br = null;\n try {\n if (response.getEntity() == null) return null;\n isr = new InputStreamReader(response.getEntity().getContent());\n br = new BufferedReader(isr);\n String line = null;\n do {\n line = br.readLine();\n if (line != null) {\n if (line.contains(\"does not exist.\")) {\n return null;\n }\n if (line.startsWith(\"ticket/\")) {\n ticketIds.add(Long.parseLong(line.replace(\"ticket/\", \"\")));\n }\n }\n } while (line != null);\n } catch (final Exception e) {\n throw new RequestTrackerException(\"Unable to read ticket IDs from query.\", e);\n } finally {\n IOUtils.closeQuietly(br);\n IOUtils.closeQuietly(isr);\n }\n }\n } catch (final Exception e) {\n LogUtils.errorf(this, e, \"An exception occurred while getting tickets for queue \" + queueName);\n return null;\n }\n for (final Long id : ticketIds) {\n try {\n tickets.add(getTicket(id, false));\n } catch (final RequestTrackerException e) {\n LogUtils.warnf(this, e, \"Unable to retrieve ticket.\");\n }\n }\n return tickets;\n }\n", "func2": " public FileParse(String fileStr, String type) throws MalformedURLException, IOException {\n this.inFile = fileStr;\n this.type = type;\n System.out.println(\"File str \" + fileStr);\n if (fileStr.indexOf(\"http://\") == 0) {\n URL url = new URL(fileStr);\n urlconn = url.openConnection();\n inStream = urlconn.getInputStream();\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"File\")) {\n File inFile = new File(fileStr);\n size = inFile.length();\n inStream = new FileInputStream(inFile);\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"URL\")) {\n URL url = new URL(fileStr);\n urlconn = url.openConnection();\n inStream = urlconn.getInputStream();\n bufReader = new BufferedReader(new InputStreamReader(inStream));\n } else if (type.equals(\"URLZip\")) {\n URL url = new URL(fileStr);\n inStream = new GZIPInputStream(url.openStream(), 16384);\n InputStreamReader zis = new InputStreamReader(inStream);\n bufReader = new BufferedReader(zis, 16384);\n } else {\n System.out.println(\"Unknown FileParse inType \" + type);\n }\n }\n", "label": 0} {"func1": " public static void main(String[] args) throws FileNotFoundException {\n if (args.length < 2) throw new IllegalArgumentException();\n String fnOut = args[args.length - 1];\n PrintWriter writer = new PrintWriter(fnOut);\n for (int i = 0; i < args.length - 1; i++) {\n File fInput = new File(args[i]);\n Scanner in = new Scanner(fInput);\n while (in.hasNext()) {\n writer.println(in.nextLine());\n }\n }\n writer.close();\n }\n", "func2": " public ArrayList showTopLetters() {\n int[] tempArray = new int[engCountLetters.length];\n char[] tempArrayLetters = new char[abcEng.length];\n ArrayList resultTopFiveLetters = new ArrayList();\n tempArray = engCountLetters.clone();\n tempArrayLetters = abcEng.clone();\n int tempCount;\n char tempLetters;\n for (int j = 0; j < (abcEng.length * abcEng.length); j++) {\n for (int i = 0; i < abcEng.length - 1; i++) {\n if (tempArray[i] > tempArray[i + 1]) {\n tempCount = tempArray[i];\n tempLetters = tempArrayLetters[i];\n tempArray[i] = tempArray[i + 1];\n tempArrayLetters[i] = tempArrayLetters[i + 1];\n tempArray[i + 1] = tempCount;\n tempArrayLetters[i + 1] = tempLetters;\n }\n }\n }\n for (int i = tempArrayLetters.length - 1; i > tempArrayLetters.length - 6; i--) {\n resultTopFiveLetters.add(tempArrayLetters[i] + \":\" + tempArray[i]);\n }\n return resultTopFiveLetters;\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " public String get(String url) {\n try {\n HttpGet get = new HttpGet(url);\n HttpResponse response = this.getHttpClient().execute(get);\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n throw new RuntimeException(\"response body was empty\");\n }\n return EntityUtils.toString(entity);\n } catch (RuntimeException ex) {\n throw ex;\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n", "label": 0} {"func1": " public static URL addToArchive(Pod pod, ZipOutputStream podArchiveOutputStream, String filename, InputStream source) throws IOException {\n ZipEntry entry = new ZipEntry(filename);\n podArchiveOutputStream.putNextEntry(entry);\n IOUtils.copy(source, podArchiveOutputStream);\n podArchiveOutputStream.closeEntry();\n return PodArchiveResolver.withinPodArchive(pod, filename);\n }\n", "func2": " @Override\n public byte[] download(URI uri) throws NetworkException {\n log.info(\"download: \" + uri);\n HttpGet httpGet = new HttpGet(uri.toString());\n try {\n HttpResponse httpResponse = httpClient.execute(httpGet);\n return EntityUtils.toByteArray(httpResponse.getEntity());\n } catch (IOException e) {\n throw new NetworkException(e);\n } finally {\n httpGet.abort();\n }\n }\n", "label": 0} {"func1": " public void run() {\n BufferedReader reader = null;\n String message = null;\n int messageStyle = SWT.ICON_WARNING;\n try {\n URL url = new URL(Version.LATEST_VERSION_URL);\n URLConnection conn = url.openConnection();\n reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n String latestVersion = reader.readLine();\n latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);\n if (!Version.getVersion().equals(latestVersion)) {\n message = Labels.getLabel(\"text.version.old\");\n message = message.replaceFirst(\"%LATEST\", latestVersion);\n message = message.replaceFirst(\"%VERSION\", Version.getVersion());\n messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;\n } else {\n message = Labels.getLabel(\"text.version.latest\");\n messageStyle = SWT.ICON_INFORMATION;\n }\n } catch (Exception e) {\n message = Labels.getLabel(\"exception.UserErrorException.version.latestFailed\");\n Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);\n } finally {\n try {\n if (reader != null) reader.close();\n } catch (IOException e) {\n }\n final String messageToShow = message;\n final int messageStyleToShow = messageStyle;\n Display.getDefault().asyncExec(new Runnable() {\n\n public void run() {\n statusBar.setStatusText(null);\n MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);\n messageBox.setText(Version.getFullName());\n messageBox.setMessage(messageToShow);\n if (messageBox.open() == SWT.YES) {\n BrowserLauncher.openURL(Version.DOWNLOAD_URL);\n }\n }\n });\n }\n }\n", "func2": " public static String getMD5Hash(String in) {\n StringBuffer result = new StringBuffer(32);\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(in.getBytes());\n Formatter f = new Formatter(result);\n for (byte b : md5.digest()) {\n f.format(\"%02x\", b);\n }\n } catch (NoSuchAlgorithmException ex) {\n ex.printStackTrace();\n }\n return result.toString();\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " public void testCodingEmptyFile() throws Exception {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n WritableByteChannel channel = newChannel(baos);\n HttpParams params = new BasicHttpParams();\n SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);\n HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();\n LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);\n encoder.write(wrap(\"stuff;\"));\n File tmpFile = File.createTempFile(\"testFile\", \"txt\");\n FileOutputStream fout = new FileOutputStream(tmpFile);\n OutputStreamWriter wrtout = new OutputStreamWriter(fout);\n wrtout.flush();\n wrtout.close();\n FileChannel fchannel = new FileInputStream(tmpFile).getChannel();\n encoder.transfer(fchannel, 0, 20);\n encoder.write(wrap(\"more stuff\"));\n String s = baos.toString(\"US-ASCII\");\n assertTrue(encoder.isCompleted());\n assertEquals(\"stuff;more stuff\", s);\n tmpFile.delete();\n }\n", "label": 0} {"func1": " private InputStream getInputStream(String item) {\n InputStream is = null;\n URLConnection urlc = null;\n try {\n URL url = new URL(item);\n urlc = url.openConnection();\n is = urlc.getInputStream();\n current_source = url.getProtocol() + \"://\" + url.getHost() + \":\" + url.getPort() + url.getFile();\n } catch (Exception ee) {\n System.err.println(ee);\n }\n int i = 0;\n udp_port = -1;\n udp_baddress = null;\n while (urlc != null) {\n String s = urlc.getHeaderField(i);\n String t = urlc.getHeaderFieldKey(i);\n if (s == null) {\n break;\n }\n i++;\n if (\"udp-port\".equals(t)) {\n try {\n udp_port = Integer.parseInt(s);\n } catch (Exception e) {\n }\n } else if (\"udp-broadcast-address\".equals(t)) {\n udp_baddress = s;\n }\n }\n return is;\n }\n", "func2": " public static void copyFileByNIO(File in, File out) throws IOException {\n FileChannel sourceChannel = new FileInputStream(in).getChannel();\n FileChannel destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n }\n", "label": 0} {"func1": " public static int[] sortAscending(float input[]) {\n int[] order = new int[input.length];\n for (int i = 0; i < order.length; i++) order[i] = i;\n for (int i = input.length; --i >= 0; ) {\n for (int j = 0; j < i; j++) {\n if (input[j] > input[j + 1]) {\n float mem = input[j];\n input[j] = input[j + 1];\n input[j + 1] = mem;\n int id = order[j];\n order[j] = order[j + 1];\n order[j + 1] = id;\n }\n }\n }\n return order;\n }\n", "func2": " public void load(URL url) throws IOException {\n ResourceLocator locator = null;\n try {\n locator = new RelativeResourceLocator(url);\n } catch (URISyntaxException use) {\n throw new IllegalArgumentException(\"Bad URL: \" + use);\n }\n ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, locator);\n InputStream stream = null;\n try {\n stream = url.openStream();\n if (stream == null) {\n throw new IOException(\"Failed to load materials file '\" + url + \"'\");\n }\n logger.fine(\"Loading materials from '\" + url + \"'...\");\n load(stream);\n } finally {\n if (stream != null) stream.close();\n ResourceLocatorTool.removeResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, locator);\n locator = null;\n }\n }\n", "label": 0} {"func1": " public static long getFileSize(String address) {\n URL url = null;\n try {\n url = new URL(address);\n System.err.println(\"Indirizzo valido - \" + url.toString().substring(0, 10) + \"...\");\n } catch (MalformedURLException ex) {\n System.err.println(\"Indirizzo non valido!\");\n }\n try {\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestProperty(\"Range\", \"bytes=0-\");\n connection.connect();\n return connection.getContentLength();\n } catch (IOException ioe) {\n System.err.println(\"I/O error!\");\n return 0;\n }\n }\n", "func2": " public static boolean loadContentFromURL(String fromURL, String toFile) {\n try {\n URL url = new URL(\"http://bible-desktop.com/xml\" + fromURL);\n File file = new File(toFile);\n URLConnection ucon = url.openConnection();\n InputStream is = ucon.getInputStream();\n BufferedInputStream bis = new BufferedInputStream(is);\n ByteArrayBuffer baf = new ByteArrayBuffer(50);\n int current = 0;\n while ((current = bis.read()) != -1) {\n baf.append((byte) current);\n }\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(baf.toByteArray());\n fos.close();\n } catch (IOException e) {\n Log.e(TAG, e);\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " public String readRemoteFile() throws IOException {\n String response = \"\";\n boolean eof = false;\n URL url = new URL(StaticData.remoteFile);\n InputStream is = url.openStream();\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\n String s;\n s = br.readLine();\n response = s;\n while (!eof) {\n try {\n s = br.readLine();\n if (s == null) {\n eof = true;\n br.close();\n } else response += s;\n } catch (EOFException eo) {\n eof = true;\n } catch (IOException e) {\n System.out.println(\"IO Error : \" + e.getMessage());\n }\n }\n return response;\n }\n", "func2": " public InputStream openInput(Fragment path) throws IOException {\n int len = path.words().size();\n String p = Util.combine(\"/\", path.words().subList(1, len));\n URL url = new URL(\"http\", path.words().get(0), p);\n InputStream result = url.openStream();\n return result;\n }\n", "label": 0} {"func1": " @Test\n public void test01_ok_failed_500_no_logo() throws Exception {\n DefaultHttpClient client = new DefaultHttpClient();\n try {\n HttpPost post = new HttpPost(xlsURL);\n HttpResponse response = client.execute(post);\n assertEquals(\"failed code for \", 500, response.getStatusLine().getStatusCode());\n } finally {\n client.getConnectionManager().shutdown();\n }\n }\n", "func2": " public static void copy(File source, File destination) throws FileNotFoundException, IOException {\n if (source == null) throw new NullPointerException(\"The source may not be null.\");\n if (destination == null) throw new NullPointerException(\"The destination may not be null.\");\n FileInputStream sourceStream = new FileInputStream(source);\n destination.getParentFile().mkdirs();\n FileOutputStream destStream = new FileOutputStream(destination);\n try {\n FileChannel sourceChannel = sourceStream.getChannel();\n FileChannel destChannel = destStream.getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n } finally {\n try {\n sourceStream.close();\n destStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n", "label": 0} {"func1": " public static String installOvalDefinitions(final String xml_location) {\n InputStream in_stream = null;\n try {\n URL url = _toURL(xml_location);\n if (url == null) {\n in_stream = new FileInputStream(xml_location);\n } else {\n in_stream = url.openStream();\n }\n } catch (IOException ex) {\n throw new OvalException(ex);\n }\n Class type = OvalDefinitions.class;\n OvalDefinitions object = _unmarshalObject(type, in_stream);\n String pid = _getDatastore().save(type, object);\n return pid;\n }\n", "func2": " public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {\n File dest = new File(this.getRealFile(), name);\n LOGGER.debug(\"PUT?? - real file: \" + this.getRealFile() + \",name: \" + name);\n if (isOwner) {\n if (!\".request\".equals(name) && !\".tokens\".equals(name)) {\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n } else {\n if (ServerConfiguration.isDynamicSEL()) {\n } else {\n }\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n }\n return factory.resolveFile(this.host, dest);\n } else {\n LOGGER.error(\"User isn't owner of this folder\");\n return null;\n }\n }\n", "label": 0} {"func1": " public static MessageService getMessageService(String fileId) {\n MessageService ms = null;\n if (serviceCache == null) init();\n if (serviceCache.containsKey(fileId)) return serviceCache.get(fileId);\n Properties p = new Properties();\n try {\n URL url = I18nPlugin.getFileURL(fileId);\n p.load(url.openStream());\n ms = new MessageService(p);\n } catch (Exception e) {\n ms = new MessageService();\n }\n serviceCache.put(fileId, ms);\n return ms;\n }\n", "func2": " public String new2Password(String passwd) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n String clearPassword = passwd;\n md.update(clearPassword.getBytes());\n byte[] digestedPassword = md.digest();\n return new String(digestedPassword);\n } catch (java.security.NoSuchAlgorithmException e) {\n System.out.println(\"MD5 doesn't exist\");\n System.out.println(e.toString());\n return null;\n }\n }\n", "label": 0} {"func1": " public static boolean dump(File source, File target) {\n boolean done = false;\n try {\n InputStream is = new BufferedInputStream(new FileInputStream(source));\n OutputStream os = new BufferedOutputStream(new FileOutputStream(target));\n while (is.available() > 0) {\n os.write(is.read());\n }\n os.flush();\n os.close();\n is.close();\n return true;\n } catch (IOException e) {\n }\n return done;\n }\n", "func2": " public static String getSHADigest(String password) {\n String digest = null;\n MessageDigest sha = null;\n try {\n sha = MessageDigest.getInstance(\"SHA-1\");\n sha.reset();\n sha.update(password.getBytes());\n byte[] pwhash = sha.digest();\n digest = \"{SHA}\" + new String(Base64.encode(pwhash));\n } catch (NoSuchAlgorithmException nsae) {\n CofaxToolsUtil.log(\"Algorithme SHA-1 non supporte a la creation du hashage\" + nsae + id);\n }\n return digest;\n }\n", "label": 0} {"func1": " private void runGetAppListing() {\n DataStorage.clearAppListings();\n GenericUrl url = new GoogleUrl(EnterpriseMarketplaceUrl.generateAppListingUrl() + DataStorage.getVendorProfile().vendorId);\n AppListingList appListingList;\n try {\n HttpRequest request = requestFactory.buildGetRequest(url);\n request.addParser(jsonHttpParser);\n request.readTimeout = readTimeout;\n HttpResponse response = request.execute();\n appListingList = response.parseAs(AppListingList.class);\n if (appListingList != null && appListingList.appListings != null) {\n operationStatus = true;\n DataStorage.setAppListings(appListingList.appListings);\n }\n response.getContent().close();\n } catch (IOException e) {\n AppsMarketplacePluginLog.logError(e);\n }\n }\n", "func2": " public static void copyFile(File srcFile, File destFile) throws IOException {\n logger.debug(\"copyFile(srcFile={}, destFile={}) - start\", srcFile, destFile);\n FileChannel srcChannel = new FileInputStream(srcFile).getChannel();\n FileChannel dstChannel = new FileOutputStream(destFile).getChannel();\n try {\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } finally {\n srcChannel.close();\n dstChannel.close();\n }\n }\n", "label": 0} {"func1": " private VelocityEngine newVelocityEngine() {\n VelocityEngine velocityEngine = null;\n InputStream is = null;\n try {\n URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);\n is = url.openStream();\n Properties props = new Properties();\n props.load(is);\n velocityEngine = new VelocityEngine(props);\n velocityEngine.init();\n } catch (Exception e) {\n throw new RuntimeException(\"can not find velocity props file, file=\" + VELOCITY_PROPS_FILE, e);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n return velocityEngine;\n }\n", "func2": " static void copy(String src, String dest) throws IOException {\n File ifp = new File(src);\n File ofp = new File(dest);\n if (ifp.exists() == false) {\n throw new IOException(\"file '\" + src + \"' does not exist\");\n }\n FileInputStream fis = new FileInputStream(ifp);\n FileOutputStream fos = new FileOutputStream(ofp);\n byte[] b = new byte[1024];\n while (fis.read(b) > 0) fos.write(b);\n fis.close();\n fos.close();\n }\n", "label": 0} {"func1": " private void loadBinaryStream(String streamName, InputStream streamToLoad, long sz, HttpServletRequest req, HttpServletResponse resp) throws IOException {\n resp.setContentType(getContentType(req, streamName));\n resp.setHeader(\"Content-Disposition\", \"inline;filename=\" + streamName);\n resp.setContentLength((int) sz);\n OutputStream out = resp.getOutputStream();\n BufferedOutputStream bos = new BufferedOutputStream(out, 2048);\n try {\n IOUtils.copy(streamToLoad, bos);\n } finally {\n IOUtils.closeQuietly(streamToLoad);\n IOUtils.closeQuietly(bos);\n }\n getCargo().put(GWT_ENTRY_POINT_PAGE_PARAM, null);\n }\n", "func2": " private String executePost(String targetURL, String urlParameters) {\n URL url;\n HttpURLConnection connection = null;\n try {\n url = new URL(targetURL);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n connection.setRequestProperty(\"Content-Length\", \"\" + Integer.toString(urlParameters.getBytes().length));\n connection.setRequestProperty(\"Content-Language\", \"en-US\");\n connection.setUseCaches(false);\n connection.setDoInput(true);\n connection.setDoOutput(true);\n DataOutputStream wr = new DataOutputStream(connection.getOutputStream());\n wr.writeBytes(urlParameters);\n wr.flush();\n wr.close();\n InputStream is = connection.getInputStream();\n BufferedReader rd = new BufferedReader(new InputStreamReader(is));\n String line;\n StringBuffer response = new StringBuffer();\n while ((line = rd.readLine()) != null) {\n response.append(line);\n response.append('\\r');\n }\n rd.close();\n return response.toString();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n }\n", "label": 0} {"func1": " public Configuration(URL url) {\n InputStream in = null;\n try {\n load(in = url.openStream());\n } catch (Exception e) {\n throw new RuntimeException(\"Could not load configuration from \" + url, e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException ignore) {\n }\n }\n }\n }\n", "func2": " public static byte[] getSystemStateHash() {\n MessageDigest sha1;\n try {\n sha1 = MessageDigest.getInstance(\"SHA1\");\n } catch (Exception e) {\n throw new Error(\"Error in RandomSeed, no sha1 hash\");\n }\n sha1.update((byte) System.currentTimeMillis());\n sha1.update((byte) Runtime.getRuntime().totalMemory());\n sha1.update((byte) Runtime.getRuntime().freeMemory());\n sha1.update(stackDump(new Throwable()));\n try {\n Properties props = System.getProperties();\n Enumeration names = props.propertyNames();\n while (names.hasMoreElements()) {\n String name = (String) names.nextElement();\n sha1.update(name.getBytes());\n sha1.update(props.getProperty(name).getBytes());\n }\n } catch (Throwable t) {\n sha1.update(stackDump(t));\n }\n sha1.update((byte) System.currentTimeMillis());\n try {\n sha1.update(InetAddress.getLocalHost().toString().getBytes());\n } catch (Throwable t) {\n sha1.update(stackDump(t));\n }\n sha1.update((byte) System.currentTimeMillis());\n Runtime.getRuntime().gc();\n sha1.update((byte) Runtime.getRuntime().freeMemory());\n sha1.update((byte) System.currentTimeMillis());\n return sha1.digest();\n }\n", "label": 0} {"func1": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String version = null;\n String build = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".version\")) version = line.substring(8).trim(); else if (line.startsWith(\".build\")) build = line.substring(6).trim();\n }\n bin.close();\n if (version != null && build != null) {\n if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else {\n GUIUtilities.message(view, \"version-check\" + \".up-to-date\", new String[0]);\n }\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "func2": " private static void loadMappings(Configuration cfg) {\n try {\n Enumeration en = LoadingUtils.getResources(MAPPINGS_FILE);\n while (en.hasMoreElements()) {\n URL url = (URL) en.nextElement();\n logger.info(\"Found mapping module \" + url.toExternalForm());\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n HibConfiguration hm = loadModuleMappings(inputStream);\n configureModuleMappings(cfg, hm.getSessionFactory());\n } catch (IOException e) {\n logger.warn(\"Could not load mappings file \\\"\" + url.toExternalForm() + \"\\\"\", e);\n } catch (JAXBException e) {\n logger.warn(\"Unable to instantiate JAXBContext \", e);\n } finally {\n try {\n if (inputStream != null) inputStream.close();\n } catch (IOException e) {\n logger.debug(e);\n }\n }\n }\n } catch (IOException e) {\n logger.warn(\"Could not find any mappings file hibernate.mappings.xml\", e);\n }\n }\n", "label": 0} {"func1": " private static String getVersion() {\n debug.print(\"\");\n String version = null;\n String version_url = \"http://kmttg.googlecode.com/svn/trunk/version\";\n try {\n URL url = new URL(version_url);\n URLConnection con = url.openConnection();\n BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));\n String inputLine;\n while ((inputLine = in.readLine()) != null) version = inputLine;\n in.close();\n } catch (Exception ex) {\n version = null;\n }\n return version;\n }\n", "func2": " public PTask stop(PTask task, SyrupConnection con) throws Exception {\n PreparedStatement s = null;\n ResultSet result = null;\n try {\n s = con.prepareStatementFromCache(sqlImpl().sqlStatements().checkWorkerStatement());\n s.setString(1, task.key());\n result = s.executeQuery();\n con.commit();\n if (result.next()) {\n String url = result.getString(\"worker\");\n InputStream i = null;\n try {\n Object b = new URL(url).getContent();\n if (b instanceof InputStream) {\n i = (InputStream) b;\n byte[] bb = new byte[256];\n int ll = i.read(bb);\n String k = new String(bb, 0, ll);\n if (k.equals(task.key())) {\n return task;\n }\n }\n } catch (Exception e) {\n } finally {\n if (i != null) {\n i.close();\n }\n }\n PreparedStatement s2 = null;\n s2 = con.prepareStatementFromCache(sqlImpl().sqlStatements().resetWorkerStatement());\n s2.setString(1, task.key());\n s2.executeUpdate();\n task = sqlImpl().queryFunctions().readPTask(task.key(), con);\n sqlImpl().loggingFunctions().log(task.key(), LogEntry.STOPPED, con);\n con.commit();\n }\n } finally {\n con.rollback();\n close(result);\n }\n return task;\n }\n", "label": 0} {"func1": " public static void copyFile(File src, File dst) throws IOException {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[1024];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n }\n", "func2": " public void get() {\n try {\n int cnt;\n URL url = new URL(urlStr);\n URLConnection conn = url.openConnection();\n conn.setDoInput(true);\n conn.setDoOutput(false);\n InputStream is = conn.getInputStream();\n String filename = new File(url.getFile()).getName();\n FileOutputStream fos = new FileOutputStream(dstDir + File.separator + filename);\n byte[] buffer = new byte[4096];\n while ((cnt = is.read(buffer, 0, buffer.length)) != -1) fos.write(buffer, 0, cnt);\n fos.close();\n is.close();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public HttpResponse doRequest(HttpMethods method, HttpHeader[] headers, boolean auth, URI target, BlipMessagePart body) throws HttpRequestException {\n HttpRequest con = createConnection(method, target);\n if (defaultHeaders != null) {\n putHeaders(con, defaultHeaders);\n }\n if (headers != null) {\n putHeaders(con, headers);\n }\n try {\n if (auth && authStrategy != null) {\n authStrategy.perform(con);\n }\n if (body != null) {\n bodyGenerator.writeBody(con, body);\n }\n HttpResponse res = execute(con);\n return res;\n } catch (IOException e) {\n throw new HttpRequestException(\"Error executing request\", e);\n }\n }\n", "func2": " @Override\n public OBJModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {\n boolean baseURLWasNull = setBaseURLFromModelURL(url);\n OBJModel model = loadModel(url.openStream(), skin);\n if (baseURLWasNull) {\n popBaseURL();\n }\n return (model);\n }\n", "label": 0} {"func1": " ClassFile getClassFile(String name) throws IOException, ConstantPoolException {\n URL url = getClass().getResource(name);\n InputStream in = url.openStream();\n try {\n return ClassFile.read(in);\n } finally {\n in.close();\n }\n }\n", "func2": " public synchronized String encrypt(String plaintext) throws Exception {\n StringBuffer sb = new StringBuffer();\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"SHA-512\");\n } catch (NoSuchAlgorithmException e) {\n throw new Exception(e.getMessage());\n }\n try {\n md.update(plaintext.getBytes(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new Exception(e.getMessage());\n }\n byte raw[] = md.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "label": 0} {"func1": " @Override\n public EntrySet read(EntrySet set) throws ReadFailedException {\n if (!SourceCache.contains(url)) {\n SSL.certify(url);\n try {\n super.setParser(Parser.detectParser(url.openStream()));\n final PipedInputStream in = new PipedInputStream();\n final PipedOutputStream forParser = new PipedOutputStream(in);\n new Thread(new Runnable() {\n\n public void run() {\n try {\n OutputStream out = SourceCache.startCaching(url);\n InputStream is = url.openStream();\n byte[] buffer = new byte[100000];\n while (true) {\n int amountRead = is.read(buffer);\n if (amountRead == -1) {\n break;\n }\n forParser.write(buffer, 0, amountRead);\n out.write(buffer, 0, amountRead);\n }\n forParser.close();\n out.close();\n SourceCache.finish(url);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }).start();\n super.setIos(in);\n } catch (Exception e) {\n throw new ReadFailedException(e);\n }\n return super.read(set);\n } else {\n try {\n return SourceCache.get(url).read(set);\n } catch (IOException e) {\n throw new ReadFailedException(e);\n }\n }\n }\n", "func2": " protected JSONObject doJSONRequest(JSONObject jsonRequest) throws JSONRPCException {\n HttpPost request = new HttpPost(serviceUri);\n HttpParams params = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());\n HttpConnectionParams.setSoTimeout(params, getSoTimeout());\n HttpProtocolParams.setVersion(params, PROTOCOL_VERSION);\n request.setParams(params);\n request.addHeader(\"Authorization\", \"Basic \" + Base64Coder.encodeString(serviceUser + \":\" + servicePass));\n HttpEntity entity;\n try {\n entity = new JSONEntity(jsonRequest);\n } catch (UnsupportedEncodingException e1) {\n throw new JSONRPCException(\"Unsupported encoding\", e1);\n }\n request.setEntity(entity);\n try {\n long t = System.currentTimeMillis();\n HttpResponse response = httpClient.execute(request);\n t = System.currentTimeMillis() - t;\n Log.d(\"json-rpc\", \"Request time :\" + t);\n String responseString = EntityUtils.toString(response.getEntity());\n responseString = responseString.trim();\n JSONObject jsonResponse = new JSONObject(responseString);\n if (jsonResponse.has(\"error\")) {\n Object jsonError = jsonResponse.get(\"error\");\n if (!jsonError.equals(null)) throw new JSONRPCException(jsonResponse.get(\"error\"));\n return jsonResponse;\n } else {\n return jsonResponse;\n }\n } catch (ClientProtocolException e) {\n throw new JSONRPCException(\"HTTP error\", e);\n } catch (IOException e) {\n throw new JSONRPCException(\"IO error\", e);\n } catch (JSONException e) {\n throw new JSONRPCException(\"Invalid JSON response\", e);\n }\n }\n", "label": 0} {"func1": " String sendRequest(String[] getVars, String[] postVars, Object[] fileVars, boolean getSessionKey) throws IOException {\n String uri = wikiBaseURI;\n if (getVars != null) for (int i = 0; i + 1 < getVars.length; i += 2) uri += (i == 0 ? '?' : '&') + urlEncode(getVars[i]) + '=' + urlEncode(getVars[i + 1]);\n URL url = new URL(uri);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setDoInput(true);\n conn.setUseCaches(false);\n if (!getSessionKey) {\n String cookie = \"\";\n for (String key : cookies.keySet()) cookie += (cookie.length() == 0 ? \"\" : \"; \") + key + \"=\" + cookies.get(key);\n conn.setRequestProperty(\"Cookie\", cookie);\n }\n if (fileVars != null) {\n conn.setRequestProperty(\"Content-Type\", \"multipart/form-data; boundary=\" + boundary);\n conn.setDoOutput(true);\n conn.setRequestMethod(\"POST\");\n conn.connect();\n PrintStream ps = new PrintStream(conn.getOutputStream());\n for (int i = 0; fileVars != null && i + 2 < fileVars.length; i += 3) {\n ps.print(\"--\" + boundary + \"\\r\\n\");\n postFile(ps, conn, (String) fileVars[i], (String) fileVars[i + 1], (byte[]) fileVars[i + 2]);\n }\n for (int i = 0; postVars != null && i + 1 < postVars.length; i += 2) ps.print(\"--\" + boundary + \"\\r\\n\" + \"Content-Disposition: \" + \"form-data; name=\\\"\" + postVars[i] + \"\\\"\\r\\n\\r\\n\" + postVars[i + 1] + \"\\r\\n\");\n ps.println(\"--\" + boundary + \"--\");\n ps.close();\n } else if (postVars != null) {\n conn.setDoOutput(true);\n conn.setRequestMethod(\"POST\");\n conn.connect();\n PrintStream ps = new PrintStream(conn.getOutputStream());\n for (int i = 0; postVars != null && i + 1 < postVars.length; i += 2) ps.print((i == 0 ? \"\" : \"&\") + urlEncode(postVars[i]) + \"=\" + urlEncode(postVars[i + 1]));\n ps.close();\n }\n int httpCode = conn.getResponseCode();\n if (httpCode != 200) throw new IOException(\"HTTP code: \" + httpCode);\n if (getSessionKey) getCookies(conn.getHeaderFields().get(\"Set-Cookie\"));\n InputStream in = conn.getInputStream();\n response = \"\";\n byte[] buffer = new byte[1 << 16];\n for (; ; ) {\n int len = in.read(buffer);\n if (len < 0) break;\n response += new String(buffer, 0, len);\n }\n in.close();\n return response;\n }\n", "func2": " public static int[] sortstring(int[] a1) {\n int temp;\n for (int j = 0; j < (a1.length * a1.length); j++) {\n for (int i = 0; i < a1.length - 1; i++) {\n if (a1[i] > a1[i + 1]) {\n temp = a1[i];\n a1[i] = a1[i + 1];\n a1[i + 1] = temp;\n }\n }\n }\n return a1;\n }\n", "label": 0} {"func1": " public AsciiParser(String systemID) throws GridBagException {\n String id = systemID;\n if (id.endsWith(\".xml\")) {\n id = StringUtils.replace(id, \".xml\", \".gbc\");\n }\n ClassLoader loader = this.getClass().getClassLoader();\n URL url = loader.getResource(id);\n if (url == null) {\n throw new GridBagException(\"Cannot located resource : \\\"\" + systemID + \"\\\".\");\n }\n try {\n InputStream inStream = url.openStream();\n constraints = getLines(inStream);\n inStream.close();\n } catch (IOException ie1) {\n throw new GridBagException(\"Cannot read from resource \" + id);\n }\n }\n", "func2": " public static byte[] getSystemStateHash() {\n MessageDigest sha1;\n try {\n sha1 = MessageDigest.getInstance(\"SHA1\");\n } catch (Exception e) {\n throw new Error(\"Error in RandomSeed, no sha1 hash\");\n }\n sha1.update((byte) System.currentTimeMillis());\n sha1.update((byte) Runtime.getRuntime().totalMemory());\n sha1.update((byte) Runtime.getRuntime().freeMemory());\n sha1.update(stackDump(new Throwable()));\n try {\n Properties props = System.getProperties();\n Enumeration names = props.propertyNames();\n while (names.hasMoreElements()) {\n String name = (String) names.nextElement();\n sha1.update(name.getBytes());\n sha1.update(props.getProperty(name).getBytes());\n }\n } catch (Throwable t) {\n sha1.update(stackDump(t));\n }\n sha1.update((byte) System.currentTimeMillis());\n try {\n sha1.update(InetAddress.getLocalHost().toString().getBytes());\n } catch (Throwable t) {\n sha1.update(stackDump(t));\n }\n sha1.update((byte) System.currentTimeMillis());\n Runtime.getRuntime().gc();\n sha1.update((byte) Runtime.getRuntime().freeMemory());\n sha1.update((byte) System.currentTimeMillis());\n return sha1.digest();\n }\n", "label": 0} {"func1": " public static void extractNativeLib(String sysName, String name, boolean load, boolean warning) throws IOException {\n String fullname = System.mapLibraryName(name);\n String path = \"native/\" + sysName + \"/\" + fullname;\n URL url = Thread.currentThread().getContextClassLoader().getResource(path);\n if (url == null) {\n if (!warning) {\n logger.log(Level.WARNING, \"Cannot locate native library: {0}/{1}\", new String[] { sysName, fullname });\n }\n return;\n }\n URLConnection conn = url.openConnection();\n InputStream in = conn.getInputStream();\n File targetFile = new File(getExtractionDir(), fullname);\n OutputStream out = null;\n try {\n if (targetFile.exists()) {\n long targetLastModified = targetFile.lastModified();\n long sourceLastModified = conn.getLastModified();\n if (targetLastModified + 1000 > sourceLastModified) {\n logger.log(Level.FINE, \"Not copying library {0}. Latest already extracted.\", fullname);\n return;\n }\n }\n out = new FileOutputStream(targetFile);\n int len;\n while ((len = in.read(buf)) > 0) {\n out.write(buf, 0, len);\n }\n in.close();\n in = null;\n out.close();\n out = null;\n targetFile.setLastModified(conn.getLastModified());\n } catch (FileNotFoundException ex) {\n if (ex.getMessage().contains(\"used by another process\")) {\n return;\n }\n throw ex;\n } finally {\n if (load) {\n System.load(targetFile.getAbsolutePath());\n }\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n }\n logger.log(Level.FINE, \"Copied {0} to {1}\", new Object[] { fullname, targetFile });\n }\n", "func2": " public void testTransactions() throws Exception {\n con = TestUtil.openDB();\n Statement st;\n ResultSet rs;\n con.setAutoCommit(false);\n assertTrue(!con.getAutoCommit());\n con.setAutoCommit(true);\n assertTrue(con.getAutoCommit());\n st = con.createStatement();\n st.executeUpdate(\"insert into test_a (imagename,image,id) values ('comttest',1234,5678)\");\n con.setAutoCommit(false);\n st.executeUpdate(\"update test_a set image=9876 where id=5678\");\n con.commit();\n rs = st.executeQuery(\"select image from test_a where id=5678\");\n assertTrue(rs.next());\n assertEquals(9876, rs.getInt(1));\n rs.close();\n st.executeUpdate(\"update test_a set image=1111 where id=5678\");\n con.rollback();\n rs = st.executeQuery(\"select image from test_a where id=5678\");\n assertTrue(rs.next());\n assertEquals(9876, rs.getInt(1));\n rs.close();\n TestUtil.closeDB(con);\n }\n", "label": 0} {"func1": " private void copyResource() throws Exception {\n URL url = getResource(source);\n InputStream input;\n if (url != null) {\n input = url.openStream();\n } else if (new File(source).exists()) {\n input = new FileInputStream(source);\n } else {\n throw new Exception(\"Could not load resource: \" + source);\n }\n OutputStream output = new FileOutputStream(destinationFile());\n int b;\n while ((b = input.read()) != -1) output.write(b);\n input.close();\n output.close();\n }\n", "func2": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"At RandomGUID !!!\", e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n logger.error(\"At RandomGUID !!!\", e);\n }\n }\n", "label": 0} {"func1": " @Test\n public void testIdentification() {\n try {\n String username = \"muchu\";\n String password = \"123\";\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(password.getBytes());\n LogService logServiceMock = EasyMock.createMock(LogService.class);\n DbService dbServiceMock = EasyMock.createMock(DbService.class);\n userServ.setDbServ(dbServiceMock);\n userServ.setLogger(logServiceMock);\n logServiceMock.info(DbUserServiceImpl.class, \">>>identification \" + username + \"<<<\");\n IFeelerUser user = new FeelerUserImpl();\n user.setUsername(username);\n user.setPassword(new String(md5.digest()));\n EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(user);\n EasyMock.replay(logServiceMock, dbServiceMock);\n Assert.assertTrue(userServ.identification(username, password));\n EasyMock.verify(logServiceMock, dbServiceMock);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n }\n", "func2": " private static String getVersion() {\n debug.print(\"\");\n String version = null;\n String version_url = \"http://kmttg.googlecode.com/svn/trunk/version\";\n try {\n URL url = new URL(version_url);\n URLConnection con = url.openConnection();\n BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));\n String inputLine;\n while ((inputLine = in.readLine()) != null) version = inputLine;\n in.close();\n } catch (Exception ex) {\n version = null;\n }\n return version;\n }\n", "label": 0} {"func1": " private InputStream getPageStream(String query) throws MalformedURLException, IOException {\n URL url = new URL(baseUrl + query + \"&rhtml=no\");\n URLConnection connection = url.openConnection();\n connection.connect();\n InputStream in = connection.getInputStream();\n BufferedInputStream bis = new BufferedInputStream(in);\n return bis;\n }\n", "func2": " private long getSize(String url) throws ClientProtocolException, IOException {\n url = normalizeUrl(url);\n Log.i(LOG_TAG, \"Head \" + url);\n HttpHead httpGet = new HttpHead(url);\n HttpResponse response = mHttpClient.execute(httpGet);\n if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {\n throw new IOException(\"Unexpected Http status code \" + response.getStatusLine().getStatusCode());\n }\n Header[] clHeaders = response.getHeaders(\"Content-Length\");\n if (clHeaders.length > 0) {\n Header header = clHeaders[0];\n return Long.parseLong(header.getValue());\n }\n return -1;\n }\n", "label": 0} {"func1": " private static byte[] baseHash(String name, String password) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n digest.reset();\n digest.update(name.toLowerCase().getBytes());\n digest.update(password.getBytes());\n return digest.digest();\n } catch (NoSuchAlgorithmException ex) {\n d(\"MD5 algorithm not found!\");\n throw new RuntimeException(\"MD5 algorithm not found! Unable to authenticate\");\n }\n }\n", "func2": " public static void copyFile(File src, File dst) throws IOException {\n try {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[TEMP_FILE_BUFFER_SIZE];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n } catch (FileNotFoundException e1) {\n MLUtil.runtimeError(e1, src.toString());\n } catch (IOException e2) {\n MLUtil.runtimeError(e2, src.toString());\n }\n }\n", "label": 0} {"func1": " public static void copyOverWarFile() {\n System.out.println(\"Copy Over War File:\");\n File dir = new File(theAppsDataDir);\n FileFilter ff = new WildcardFileFilter(\"*.war\");\n if (dir.listFiles(ff).length == 0) {\n dir = new File(System.getProperty(\"user.dir\") + \"/war\");\n if (dir.exists()) {\n File[] files = dir.listFiles(ff);\n for (File f : files) {\n try {\n File newFile = new File(\"\" + theAppsDataDir + \"/\" + f.getName());\n System.out.println(\"Creating new file \\\"\" + f.getAbsolutePath() + \"\\\"\");\n newFile.createNewFile();\n InputStream fi = new FileInputStream(f);\n OutputStream fo = new FileOutputStream(newFile);\n IOUtils.copy(fi, fo);\n moveUnzipAndExtract(newFile);\n } catch (Exception ex) {\n Logger.getLogger(AppDataDir.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }\n } else {\n System.out.println(\"Found a war in the apps data dir, ignoring a fresh copy\");\n }\n new JFileChooser().setCurrentDirectory(new File(theAppsDataDir));\n System.setProperty(\"user.dir\", theAppsDataDir);\n System.out.println(\"User.dir : \" + System.getProperty(\"user.dir\"));\n }\n", "func2": " private static void loadMappings(Configuration cfg) {\n try {\n Enumeration en = LoadingUtils.getResources(MAPPINGS_FILE);\n while (en.hasMoreElements()) {\n URL url = (URL) en.nextElement();\n logger.info(\"Found mapping module \" + url.toExternalForm());\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n HibConfiguration hm = loadModuleMappings(inputStream);\n configureModuleMappings(cfg, hm.getSessionFactory());\n } catch (IOException e) {\n logger.warn(\"Could not load mappings file \\\"\" + url.toExternalForm() + \"\\\"\", e);\n } catch (JAXBException e) {\n logger.warn(\"Unable to instantiate JAXBContext \", e);\n } finally {\n try {\n if (inputStream != null) inputStream.close();\n } catch (IOException e) {\n logger.debug(e);\n }\n }\n }\n } catch (IOException e) {\n logger.warn(\"Could not find any mappings file hibernate.mappings.xml\", e);\n }\n }\n", "label": 0} {"func1": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "func2": " public void update(String channelPath, String dataField, String fatherDocId) {\n String sqlInitial = \"select uri from t_ip_doc_res where doc_id = '\" + fatherDocId + \"' and type=\" + \" '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n String sqlsortURL = \"update t_ip_doc_res set uri = ? where doc_id = '\" + fatherDocId + \"' \" + \" and type = '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n Connection conn = null;\n ResultSet rs = null;\n PreparedStatement ps = null;\n try {\n dbo = (ERDBOperation) createDBOperation();\n String url = \"\";\n boolean flag = true;\n StringTokenizer st = null;\n conn = dbo.getConnection();\n conn.setAutoCommit(false);\n ps = conn.prepareStatement(sqlInitial);\n rs = ps.executeQuery();\n if (rs.next()) url = rs.getString(1);\n if (!url.equals(\"\")) {\n st = new StringTokenizer(url, \",\");\n String sortDocId = \"\";\n while (st.hasMoreTokens()) {\n if (flag) {\n sortDocId = \"'\" + st.nextToken() + \"'\";\n flag = false;\n } else {\n sortDocId = sortDocId + \",\" + \"'\" + st.nextToken() + \"'\";\n }\n }\n String sqlsort = \"select id from t_ip_doc where id in (\" + sortDocId + \") order by \" + dataField;\n ps = conn.prepareStatement(sqlsort);\n rs = ps.executeQuery();\n String sortURL = \"\";\n boolean sortflag = true;\n while (rs.next()) {\n if (sortflag) {\n sortURL = rs.getString(1);\n sortflag = false;\n } else {\n sortURL = sortURL + \",\" + rs.getString(1);\n }\n }\n ps = conn.prepareStatement(sqlsortURL);\n ps.setString(1, sortURL);\n ps.executeUpdate();\n }\n conn.commit();\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n } finally {\n close(rs, null, ps, conn, dbo);\n }\n }\n", "label": 0} {"func1": " public void read() throws IOException {\n if (log.isInfoEnabled()) {\n log.info(\"Reading the camera log, \" + url);\n }\n final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n String line;\n int i = 0;\n try {\n while ((line = in.readLine()) != null) {\n i++;\n try {\n final CameraLogRecord logDatum = new CameraLogRecord(line);\n records.add(logDatum);\n } catch (LogParseException e) {\n if (log.isInfoEnabled()) {\n log.info(\"Bad record in \" + url + \" at line:\" + i);\n }\n }\n }\n } finally {\n in.close();\n }\n Collections.sort(records);\n if (log.isInfoEnabled()) {\n log.info(\"Finished reading the camera log, \" + url);\n }\n }\n", "func2": " private void unJarStart(String jarPath, String jarEntryStart) {\n String path;\n if (jarPath.lastIndexOf(\"lib/\") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf(\"lib/\")); else path = jarPath.substring(0, jarPath.lastIndexOf(\"/\"));\n String relPath = jarEntryStart.substring(0, jarEntryStart.lastIndexOf(\"/\"));\n try {\n new File(path + \"/\" + relPath).mkdirs();\n JarFile jar = new JarFile(jarPath);\n Enumeration entries = jar.entries();\n while (entries.hasMoreElements()) {\n JarEntry entry = entries.nextElement();\n String jarEntry = entry.getName();\n if (jarEntry.startsWith(jarEntryStart)) {\n ZipEntry ze = jar.getEntry(jarEntry);\n File bin = new File(path + \"/\" + jarEntry);\n IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public String readPage(boolean ignoreComments) throws Exception {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n String inputLine;\n String html = \"\";\n if (ignoreComments) {\n while ((inputLine = in.readLine()) != null) {\n if (inputLine.length() > 0) {\n if (inputLine.substring(0, 1).compareTo(\"#\") != 0) {\n html = html + inputLine + \"\\n\";\n }\n }\n }\n } else {\n while ((inputLine = in.readLine()) != null) {\n html = html + inputLine + \"\\n\";\n }\n }\n in.close();\n return html;\n }\n", "func2": " public void parse() throws ParserConfigurationException, SAXException, IOException {\n DefaultHttpClient httpclient = initialise();\n HttpResponse result = httpclient.execute(new HttpGet(urlString));\n SAXParserFactory spf = SAXParserFactory.newInstance();\n if (spf != null) {\n SAXParser sp = spf.newSAXParser();\n sp.parse(result.getEntity().getContent(), this);\n }\n }\n", "label": 0} {"func1": " private void setProfile(String loginName, SimpleUserProfile profile) throws MM4UCannotStoreUserProfileException {\n try {\n OutputStream outStream = null;\n URL url = new URL(this.profileURI + profile.getID() + FILE_SUFFIX);\n if (url.getProtocol().equals(\"file\")) {\n File file = new File(url.getFile());\n outStream = new FileOutputStream(file);\n } else {\n URLConnection connection = url.openConnection();\n connection.setDoOutput(true);\n outStream = connection.getOutputStream();\n }\n OutputStreamWriter writer = new OutputStreamWriter(outStream);\n Enumeration myEnum = profile.keys();\n while (myEnum.hasMoreElements()) {\n String key = myEnum.nextElement().toString();\n if (key != \"id\") writer.write(key + \"=\" + profile.getStringValue(key) + System.getProperty(\"line.separator\"));\n }\n writer.flush();\n writer.close();\n } catch (Exception e) {\n throw new MM4UCannotStoreUserProfileException(this, \"setProfile\", e.toString());\n }\n }\n", "func2": " public static byte[] encrypt(String x) throws Exception {\n java.security.MessageDigest d = null;\n d = java.security.MessageDigest.getInstance(\"SHA-1\");\n d.reset();\n d.update(x.getBytes());\n return d.digest();\n }\n", "label": 0} {"func1": " public void transport(File file) throws TransportException {\n if (file.exists()) {\n if (file.isDirectory()) {\n File[] files = file.listFiles();\n for (int i = 0; i < files.length; i++) {\n transport(file);\n }\n } else if (file.isFile()) {\n try {\n FileChannel inChannel = new FileInputStream(file).getChannel();\n FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n log.error(\"File transfer failed\", e);\n }\n }\n }\n }\n", "func2": " private static String encrypt(String algorithm, String password, Long digestSeed) {\n try {\n MessageDigest digest = MessageDigest.getInstance(algorithm);\n digest.reset();\n digest.update(password.getBytes(\"UTF-8\"));\n digest.update(digestSeed.toString().getBytes(\"UTF-8\"));\n byte[] messageDigest = digest.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4));\n hexString.append(Integer.toHexString(0x0f & messageDigest[i]));\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n } catch (NullPointerException e) {\n return new StringBuffer().toString();\n }\n }\n", "label": 0} {"func1": " public void elimina(Cliente cli) throws errorSQL, errorConexionBD {\n System.out.println(\"GestorCliente.elimina()\");\n int id = cli.getId();\n String sql;\n Statement stmt = null;\n try {\n gd.begin();\n sql = \"DELETE FROM cliente WHERE cod_cliente =\" + id;\n System.out.println(\"Ejecutando: \" + sql);\n stmt = gd.getConexion().createStatement();\n stmt.executeUpdate(sql);\n System.out.println(\"executeUpdate\");\n sql = \"DELETE FROM persona WHERE id =\" + id;\n System.out.println(\"Ejecutando: \" + sql);\n stmt.executeUpdate(sql);\n gd.commit();\n System.out.println(\"commit\");\n stmt.close();\n } catch (SQLException e) {\n gd.rollback();\n throw new errorSQL(e.toString());\n } catch (errorConexionBD e) {\n System.err.println(\"Error en GestorCliente.elimina(): \" + e);\n } catch (errorSQL e) {\n System.err.println(\"Error en GestorCliente.elimina(): \" + e);\n }\n }\n", "func2": " @Override\n public String transformSingleFile(X3DEditorSupport.X3dEditor xed) {\n Node[] node = xed.getActivatedNodes();\n X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject();\n FileObject mySrc = dob.getPrimaryFile();\n File mySrcF = FileUtil.toFile(mySrc);\n File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + \".x3dv.gz\");\n TransformListener co = TransformListener.getInstance();\n co.message(NbBundle.getMessage(getClass(), \"Gzip_compression_starting\"));\n co.message(NbBundle.getMessage(getClass(), \"Saving_as_\") + myOutF.getAbsolutePath());\n co.moveToFront();\n co.setNode(node[0]);\n try {\n String x3dvFile = ExportClassicVRMLAction.instance.transformSingleFile(xed);\n FileInputStream fis = new FileInputStream(new File(x3dvFile));\n GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF));\n byte[] buf = new byte[4096];\n int ret;\n while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret);\n gzos.close();\n } catch (Exception ex) {\n co.message(NbBundle.getMessage(getClass(), \"Exception:__\") + ex.getLocalizedMessage());\n return null;\n }\n co.message(NbBundle.getMessage(getClass(), \"Gzip_compression_complete\"));\n return myOutF.getAbsolutePath();\n }\n", "label": 0} {"func1": " public static ArrayList importRoles(String urlString) {\n ArrayList results = new ArrayList();\n try {\n URL url = new URL(urlString);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer buff = new StringBuffer();\n String line;\n while ((line = in.readLine()) != null) {\n buff.append(line);\n if (line.equals(\"\")) {\n RoleName name = ProfileParser.parseRoleName(buff.toString());\n results.add(name);\n buff = new StringBuffer();\n } else {\n buff.append(NL);\n }\n }\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n } catch (ParsingException e) {\n }\n return results;\n }\n", "func2": " public InputStream openInput(Fragment path) throws IOException {\n int len = path.words().size();\n String p = Util.combine(\"/\", path.words().subList(1, len));\n URL url = new URL(\"http\", path.words().get(0), p);\n InputStream result = url.openStream();\n return result;\n }\n", "label": 0} {"func1": " public static Vector[] getLinksFromURLFast(String p_url) throws Exception {\n timeCheck(\"getLinksFromURLFast \");\n URL x_url = new URL(p_url);\n URLConnection x_conn = x_url.openConnection();\n InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream());\n BufferedReader x_reader = new BufferedReader(x_is_reader);\n String x_line = null;\n RE e = new RE(\"(.*/)\", RE.REG_ICASE);\n System.out.println(\"RE: \" + e.toString());\n REMatch x_match = e.getMatch(p_url);\n String x_dir = p_url.substring(x_match.getSubStartIndex(1), x_match.getSubEndIndex(1));\n e = new RE(\"(http://.*?)/?\", RE.REG_ICASE);\n x_match = e.getMatch(p_url);\n String x_root = p_url.substring(x_match.getSubStartIndex(1), x_match.getSubEndIndex(1));\n e = new RE(\"(.*?)\", RE.REG_ICASE);\n System.out.println(\"RE: \" + e.toString());\n Vector x_links = new Vector(100);\n Vector x_texts = new Vector(100);\n StringBuffer x_buf = new StringBuffer(10000);\n REMatch[] x_matches = null;\n timeCheck(\"starting parsing \");\n while ((x_line = x_reader.readLine()) != null) {\n x_buf.append(x_line);\n }\n String x_page = x_buf.toString();\n String x_link = null;\n x_matches = e.getAllMatches(x_page);\n for (int i = 0; i < x_matches.length; i++) {\n x_link = x_page.substring(x_matches[i].getSubStartIndex(1), x_matches[i].getSubEndIndex(1));\n if (x_link.indexOf(\"mailto:\") != -1) continue;\n x_link = toAbsolute(x_root, x_dir, x_link);\n x_links.addElement(x_link);\n x_texts.addElement(x_page.substring(x_matches[i].getSubStartIndex(2), x_matches[i].getSubEndIndex(2)));\n }\n Vector[] x_result = new Vector[2];\n x_result[0] = x_links;\n x_result[1] = x_texts;\n timeCheck(\"end parsing \");\n return x_result;\n }\n", "func2": " public static byte[] loadURLToBuffer(URL url) throws IOException {\n byte[] buf = new byte[4096];\n byte[] data = null;\n byte[] temp = null;\n int iCount = 0;\n int iTotal = 0;\n BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480);\n while ((iCount = in.read(buf, 0, buf.length)) != -1) {\n if (iTotal == 0) {\n data = new byte[iCount];\n System.arraycopy(buf, 0, data, 0, iCount);\n iTotal = iCount;\n } else {\n temp = new byte[iCount + iTotal];\n System.arraycopy(data, 0, temp, 0, iTotal);\n System.arraycopy(buf, 0, temp, iTotal, iCount);\n data = temp;\n iTotal = iTotal + iCount;\n }\n }\n in.close();\n return data;\n }\n", "label": 0} {"func1": " public void open(Input input) throws IOException, ResolverException {\n if (!input.isUriDefinitive()) return;\n URI uri;\n try {\n uri = new URI(input.getUri());\n } catch (URISyntaxException e) {\n throw new ResolverException(e);\n }\n if (!uri.isAbsolute()) throw new ResolverException(\"cannot open relative URI: \" + uri);\n URL url = new URL(uri.toASCIIString());\n input.setByteStream(url.openStream());\n }\n", "func2": " public static int createEmptyCart() {\n int SHOPPING_ID = 0;\n Connection con = null;\n try {\n con = getConnection();\n } catch (java.lang.Exception ex) {\n ex.printStackTrace();\n }\n try {\n PreparedStatement insert_cart = null;\n SHOPPING_ID = Integer.parseInt(Sequence.getSequenceNumber(\"shopping_cart\"));\n insert_cart = con.prepareStatement(\"INSERT INTO shopping_cart (sc_id, sc_time) VALUES ( ? , NOW() )\");\n insert_cart.setInt(1, SHOPPING_ID);\n insert_cart.executeUpdate();\n con.commit();\n insert_cart.close();\n returnConnection(con);\n } catch (java.lang.Exception ex) {\n try {\n con.rollback();\n ex.printStackTrace();\n } catch (Exception se) {\n System.err.println(\"Transaction rollback failed.\");\n }\n }\n return SHOPPING_ID;\n }\n", "label": 0} {"func1": " public static String encrypt(String text) throws NoSuchAlgorithmException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n try {\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "func2": " public void getHttpURL() throws Exception {\n boolean display = true;\n boolean allHeaders = false;\n String url = null;\n url = \"http://localhost/cubigraf2\";\n url = \"http://www.accenture.com/NR/rdonlyres/971C4EEE-24E2-4BAA-8C7B-D5A5133D5968/0/en_sprout.jpg\";\n url = \"http://www.uni.pt/img/home-direito.gif\";\n url = \"http://www.google.com\";\n URLConnection uc = new URL(url).openConnection();\n println(\"HEADERS:\");\n if (allHeaders) {\n Iterator>> itHeaders = uc.getHeaderFields().entrySet().iterator();\n while (itHeaders.hasNext()) {\n Map.Entry> e = itHeaders.next();\n Iterator itValues = e.getValue().iterator();\n while (itValues.hasNext()) {\n println(e.getKey() + \": \" + itValues.next());\n }\n }\n } else {\n showObjectProperty(uc, \"getContentEncoding\");\n showObjectProperty(uc, \"getContentLength\");\n showObjectProperty(uc, \"getContentType\");\n showObjectProperty(uc, \"getDate\", FORMAT.TIMESTAMP);\n showObjectProperty(uc, \"getExpiration\", FORMAT.TIMESTAMP);\n showObjectProperty(uc, \"getLastModified\", FORMAT.TIMESTAMP);\n }\n ExtendedInputStream in = new ExtendedInputStream(uc.getInputStream(), url.toString());\n if (display) {\n println(\"BODY:\");\n ExtendedReader reader = new ExtendedReader(in);\n for (String s = reader.readLine(); s != null; s = reader.readLine()) {\n println(s);\n }\n } else {\n println(\"(BODY saved to a file)\");\n String contentType = uc.getContentType();\n StringBuilder filename = new StringBuilder(\"C:\\\\Documents and Settings\\\\Carlos_da_S_Pereira\\\\Desktop\\\\JAVA_NET_TESTS\");\n filename.append(\".\");\n filename.append(contentType.substring(contentType.indexOf(\"/\") + 1));\n File file = new File(filename.toString());\n ExtendedOutputStream out = new ExtendedOutputStream(new FileOutputStream(file), file.getAbsolutePath());\n Streams.copy(in, out);\n out.close();\n }\n in.close();\n }\n", "label": 0} {"func1": " protected String downloadURLtoString(URL url) throws IOException {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer sb = new StringBuffer(100 * 1024);\n String str;\n while ((str = in.readLine()) != null) {\n sb.append(str);\n }\n in.close();\n return sb.toString();\n }\n", "func2": " public static void copy(File source, File destination) throws FileNotFoundException, IOException {\n if (source == null) throw new NullPointerException(\"The source may not be null.\");\n if (destination == null) throw new NullPointerException(\"The destination may not be null.\");\n FileInputStream sourceStream = new FileInputStream(source);\n destination.getParentFile().mkdirs();\n FileOutputStream destStream = new FileOutputStream(destination);\n try {\n FileChannel sourceChannel = sourceStream.getChannel();\n FileChannel destChannel = destStream.getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n } finally {\n try {\n sourceStream.close();\n destStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n", "label": 0} {"func1": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "func2": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n System.err.println(\"Failed to load the MD5 MessageDigest. \" + \"Jive will be unable to function normally.\");\n nsae.printStackTrace();\n }\n }\n digest.update(data.getBytes());\n return toHex(digest.digest());\n }\n", "label": 0} {"func1": " public static String hashStringMD5(String string) throws NoSuchAlgorithmException {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(string.getBytes());\n byte byteData[] = md.digest();\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < byteData.length; i++) {\n sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));\n }\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < byteData.length; i++) {\n String hex = Integer.toHexString(0xff & byteData[i]);\n if (hex.length() == 1) hexString.append('0');\n hexString.append(hex);\n }\n return hexString.toString();\n }\n", "func2": " private List webArchives(ServletContext servletContext) throws IOException {\n List list = new ArrayList();\n Set paths = servletContext.getResourcePaths(WEB_LIB_PREFIX);\n for (Object pathObject : paths) {\n String path = (String) pathObject;\n if (!path.endsWith(\".jar\")) {\n continue;\n }\n URL url = servletContext.getResource(path);\n String jarURLString = \"jar:\" + url.toString() + \"!/\";\n url = new URL(jarURLString);\n JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();\n JarEntry signal = jarFile.getJarEntry(FACES_CONFIG_IMPLICIT);\n if (signal == null) {\n if (log().isTraceEnabled()) {\n log().trace(\"Skip JAR file \" + path + \" because it has no META-INF/faces-config.xml resource\");\n }\n continue;\n }\n list.add(jarFile);\n }\n return list;\n }\n", "label": 0} {"func1": " protected String downloadURLtoString(URL url) throws IOException {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer sb = new StringBuffer(100 * 1024);\n String str;\n while ((str = in.readLine()) != null) {\n sb.append(str);\n }\n in.close();\n return sb.toString();\n }\n", "func2": " public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {\n HttpURLConnection con = null;\n InputStream is = null;\n try {\n URL u = new URL(url);\n if (url.startsWith(\"file://\")) {\n is = new BufferedInputStream(u.openStream());\n } else {\n Proxy proxy;\n if (proxyHost != null) {\n proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));\n } else {\n proxy = Proxy.NO_PROXY;\n }\n con = (HttpURLConnection) u.openConnection(proxy);\n con.addRequestProperty(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6\");\n con.addRequestProperty(\"Accept-Charset\", \"UTF-8\");\n con.addRequestProperty(\"Accept-Language\", \"en-US,en\");\n con.addRequestProperty(\"Accept\", \"text/html,image/*\");\n con.setDoInput(true);\n con.setDoOutput(false);\n con.connect();\n is = new BufferedInputStream(con.getInputStream());\n }\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(is, baos);\n return baos.toByteArray();\n } finally {\n IOUtils.closeQuietly(is);\n if (con != null) {\n con.disconnect();\n }\n }\n }\n", "label": 0} {"func1": " public static int createEmptyCart() {\n int SHOPPING_ID = 0;\n Connection con = null;\n try {\n con = getConnection();\n } catch (java.lang.Exception ex) {\n ex.printStackTrace();\n }\n try {\n PreparedStatement insert_cart = null;\n SHOPPING_ID = Integer.parseInt(Sequence.getSequenceNumber(\"shopping_cart\"));\n insert_cart = con.prepareStatement(\"INSERT INTO shopping_cart (sc_id, sc_time) VALUES ( ? , NOW() )\");\n insert_cart.setInt(1, SHOPPING_ID);\n insert_cart.executeUpdate();\n con.commit();\n insert_cart.close();\n returnConnection(con);\n } catch (java.lang.Exception ex) {\n try {\n con.rollback();\n ex.printStackTrace();\n } catch (Exception se) {\n System.err.println(\"Transaction rollback failed.\");\n }\n }\n return SHOPPING_ID;\n }\n", "func2": " private InputStream openRemoteStream(String remoteURL, String pathSuffix) {\n URL url;\n InputStream in = null;\n try {\n url = new URL(remoteURL + pathSuffix);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n in = connection.getInputStream();\n } catch (Exception e) {\n }\n return in;\n }\n", "label": 0} {"func1": " @Test\n public void test() throws Exception {\n InputStream is = this.getClass().getResourceAsStream(\"originAndDestination.xml\");\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n IOUtils.copy(is, byteArrayOutputStream);\n TrafficModelDefinition def = MDFReader.read(byteArrayOutputStream.toByteArray());\n TrafficSimulationEngine se = new TrafficSimulationEngine();\n se.init(def);\n int linkId = 2;\n int segmentId = 0;\n Map> linkSegments = new HashMap>();\n Set segments = new HashSet();\n segments.add(segmentId);\n linkSegments.put(linkId, segments);\n FrameProperties frameProperties = new FrameProperties(linkSegments, new HashSet());\n se.setFrameProperties(frameProperties);\n for (float time = 0; time < 60 * 10; time += 0.1f) {\n se.step(0.1f);\n for (RoadObject vehicle : se.getDynamicObjects()) {\n System.out.println(time + \": X=\" + vehicle.getPosition() + \"\\tV=\" + vehicle.getSpeed());\n }\n }\n }\n", "func2": " private Retailer create() throws SQLException, IOException {\n Connection conn = null;\n Statement st = null;\n String query = null;\n ResultSet rs = null;\n try {\n conn = dataSource.getConnection();\n st = conn.createStatement();\n query = \"insert into \" + DB.Tbl.ret + \"(\" + col.title + \",\" + col.addDate + \",\" + col.authorId + \") \" + \"values('\" + title + \"',now(),\" + user.getId() + \")\";\n st.executeUpdate(query, new String[] { col.id });\n rs = st.getGeneratedKeys();\n if (!rs.next()) {\n throw new SQLException(\"Не удается получить generated key 'id' в таблице retailers.\");\n }\n int genId = rs.getInt(1);\n rs.close();\n saveDescr(genId);\n conn.commit();\n Retailer ret = new Retailer();\n ret.setId(genId);\n ret.setTitle(title);\n ret.setDescr(descr);\n RetailerViewer.getInstance().somethingUpdated();\n return ret;\n } catch (SQLException e) {\n try {\n conn.rollback();\n } catch (Exception e1) {\n }\n throw e;\n } finally {\n try {\n rs.close();\n } catch (Exception e) {\n }\n try {\n st.close();\n } catch (Exception e) {\n }\n try {\n conn.close();\n } catch (Exception e) {\n }\n }\n }\n", "label": 0} {"func1": " public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException {\n Assert.notNull(resourceName, \"Resource name must not be null\");\n ClassLoader clToUse = classLoader;\n if (clToUse == null) {\n clToUse = ClassUtils.getDefaultClassLoader();\n }\n Properties properties = new Properties();\n Enumeration urls = clToUse.getResources(resourceName);\n while (urls.hasMoreElements()) {\n URL url = (URL) urls.nextElement();\n InputStream is = null;\n try {\n URLConnection con = url.openConnection();\n con.setUseCaches(false);\n is = con.getInputStream();\n properties.load(is);\n } finally {\n if (is != null) {\n is.close();\n }\n }\n }\n return properties;\n }\n", "func2": " public HttpResponse fetch(HttpServletRequest request) throws IOException {\n GUI = SwingUI.getApplicatoin();\n DefaultHttpClient httpclient = new DefaultHttpClient();\n CookieSpecFactory csf = new CookieSpecFactory() {\n\n public CookieSpec newInstance(HttpParams params) {\n return new BrowserCompatSpec() {\n\n @Override\n public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {\n }\n };\n }\n };\n if (Helper.useProxy()) {\n HttpHost proxy = new HttpHost(Helper.getProxyServer(), Helper.getProxyPort());\n httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);\n }\n httpclient.getCookieSpecs().register(\"easy\", csf);\n httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, \"easy\");\n String currentRemoteGAEHost = Helper.getRemoteServer();\n try {\n HttpUriRequest httpRequest = createRequest(request);\n addHeader(request, httpRequest);\n HttpResponse response = httpclient.execute(httpRequest);\n if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {\n challengeProxy(currentRemoteGAEHost);\n }\n logger.info(Helper.count.incrementAndGet() + \" Response received from \" + request.getRequestURL().toString() + \", status is \" + response.getStatusLine());\n GUI.updateFetchCount();\n return response;\n } catch (ClientProtocolException e) {\n logger.error(\"Fetch ClientProtocol Error\", e);\n throw e;\n } catch (IOException e) {\n logger.error(\"Fetch IO Error\", e);\n throw e;\n }\n }\n", "label": 0} {"func1": " public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setConnectTimeout(timeout);\n connection.setReadTimeout(timeout);\n BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());\n return loadXml(buffInputStream, xmlType);\n }\n", "func2": " public static String uncompress(String readPath, boolean mkdir) throws Exception {\n ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));\n BufferedInputStream bis = new BufferedInputStream(arcInputStream);\n File baseDir = new File(readPath).getParentFile();\n String basePath = baseDir.getPath() + \"/\";\n if (mkdir) {\n String[] schema = readPath.split(\"/\");\n String baseName = schema[schema.length - 1].replaceAll(\".zip\", \"\");\n FileUtils.forceMkdir(new File(basePath + baseName));\n basePath = basePath + baseName + \"/\";\n }\n ArchiveEntry entry;\n while ((entry = arcInputStream.getNextEntry()) != null) {\n if (entry.isDirectory()) {\n FileUtils.forceMkdir(new File(basePath + entry.getName()));\n } else {\n String writePath = basePath + entry.getName();\n String dirName = FilenameUtils.getPath(writePath);\n FileUtils.forceMkdir(new File(dirName));\n BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));\n int i = 0;\n while ((i = bis.read()) != -1) {\n bos.write(i);\n }\n IOUtils.closeQuietly(bos);\n }\n }\n IOUtils.closeQuietly(bis);\n return basePath;\n }\n", "label": 0} {"func1": " public String getUser() {\n try {\n HttpGet get = new HttpGet(\"http://api.linkedin.com/v1/people/~\");\n consumer.sign(get);\n HttpClient client = new DefaultHttpClient();\n HttpResponse response = client.execute(get);\n if (response != null) {\n int statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != 200) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n }\n StringBuffer sBuf = new StringBuffer();\n String linea;\n BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), \"UTF-8\"));\n while ((linea = reader.readLine()) != null) {\n sBuf.append(linea);\n }\n reader.close();\n response.getEntity().consumeContent();\n get.abort();\n String salida = sBuf.toString();\n String user_firstname = salida.split(\"\")[0].split(\"\")[1];\n String user_lastname = salida.split(\"\")[0].split(\"\")[1];\n return user_firstname + \" \" + user_lastname;\n }\n } catch (UnsupportedEncodingException e) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n } catch (IOException e) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n } catch (OAuthMessageSignerException e) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n } catch (OAuthExpectationFailedException e) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n } catch (OAuthCommunicationException e) {\n this.enviarMensaje(\"Error: Usuario no autenticado en la red de Linkedin\");\n }\n return null;\n }\n", "func2": " public String digest(String message) throws NoSuchAlgorithmException, EncoderException {\n MessageDigest messageDigest = MessageDigest.getInstance(\"SHA-256\");\n messageDigest.update(message.getBytes());\n byte[] raw = messageDigest.digest();\n byte[] chars = new Base64().encode(raw);\n return new String(chars);\n }\n", "label": 0} {"func1": " public boolean connect() {\n boolean isConnected = false;\n try {\n try {\n this.ftpClient.connect(this.server, this.port);\n } catch (SocketException e) {\n status = ErrorResult.CONNECTNOTPOSSIBLE.code;\n return false;\n } catch (IOException e) {\n status = ErrorResult.CONNECTNOTPOSSIBLE.code;\n return false;\n }\n int reply = this.ftpClient.getReplyCode();\n if (!FTPReply.isPositiveCompletion(reply)) {\n this.disconnect();\n status = ErrorResult.CONNECTNOTCORRECT.code;\n return false;\n }\n try {\n if (this.account == null) {\n if (!this.ftpClient.login(this.username, this.passwd)) {\n status = ErrorResult.LOGINNOTCORRECT.code;\n this.ftpClient.logout();\n return false;\n }\n } else if (!this.ftpClient.login(this.username, this.passwd, this.account)) {\n status = ErrorResult.LOGINACCTNOTCORRECT.code;\n this.ftpClient.logout();\n return false;\n }\n } catch (IOException e) {\n status = ErrorResult.ERRORWHILECONNECT.code;\n try {\n this.ftpClient.logout();\n } catch (IOException e1) {\n }\n return false;\n }\n isConnected = true;\n return true;\n } finally {\n if ((!isConnected) && this.ftpClient.isConnected()) {\n this.disconnect();\n }\n }\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 0} {"func1": " public static synchronized BufferedImage loadBufferedJPEGImage(URL url) {\n BufferedImage image = null;\n if (url != null) {\n InputStream in = null;\n try {\n in = url.openStream();\n JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);\n image = decoder.decodeAsBufferedImage();\n } catch (Exception e) {\n log.severe(\"URL: \" + url + \" - \" + e.getMessage());\n image = null;\n } finally {\n try {\n if (in != null) in.close();\n } catch (IOException ioe) {\n log.severe(\"URL: \" + url + \" - \" + ioe.getMessage());\n }\n }\n if (image != null) {\n log.config(\"Image type : \" + image.getType());\n if (image.getWidth() <= 0 || image.getHeight() <= 0) {\n log.severe(\"URL: \" + url + \" =0\");\n image = null;\n }\n }\n }\n return image;\n }\n", "func2": " private String File2String(String directory, String filename) {\n String line;\n InputStream in = null;\n try {\n File f = new File(filename);\n System.out.println(\"File On:>>>>>>>>>> \" + f.getCanonicalPath());\n in = new FileInputStream(f);\n } catch (FileNotFoundException ex) {\n in = null;\n } catch (IOException ex) {\n in = null;\n }\n try {\n if (in == null) {\n filename = directory + \"/\" + filename;\n java.net.URL urlFile = ClassLoader.getSystemResource(filename);\n if (urlFile == null) {\n System.out.println(\"Integrated Chips list file not found: \" + filename);\n System.exit(-1);\n }\n in = urlFile.openStream();\n }\n BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n StringBuffer xmlText = new StringBuffer();\n while ((line = reader.readLine()) != null) {\n xmlText.append(line);\n }\n reader.close();\n return xmlText.toString();\n } catch (FileNotFoundException ex) {\n System.out.println(\"Integrated Chips list file not found\");\n System.exit(-1);\n } catch (IOException ex) {\n ex.printStackTrace();\n System.exit(-1);\n }\n return null;\n }\n", "label": 0} {"func1": " @Override\n public OBJModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {\n boolean baseURLWasNull = setBaseURLFromModelURL(url);\n OBJModel model = loadModel(url.openStream(), skin);\n if (baseURLWasNull) {\n popBaseURL();\n }\n return (model);\n }\n", "func2": " public void resolvePlugins() {\n try {\n File cacheDir = XPontusConfigurationConstantsIF.XPONTUS_CACHE_DIR;\n File pluginsFile = new File(cacheDir, \"plugins.xml\");\n if (!pluginsFile.exists()) {\n URL pluginURL = new URL(\"http://xpontus.sourceforge.net/snapshot/plugins.xml\");\n InputStream is = pluginURL.openStream();\n OutputStream os = FileUtils.openOutputStream(pluginsFile);\n IOUtils.copy(is, os);\n IOUtils.closeQuietly(os);\n IOUtils.closeQuietly(is);\n }\n resolvePlugins(pluginsFile.getAbsolutePath());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public static long getFileSize(String address) {\n URL url = null;\n try {\n url = new URL(address);\n System.err.println(\"Indirizzo valido - \" + url.toString().substring(0, 10) + \"...\");\n } catch (MalformedURLException ex) {\n System.err.println(\"Indirizzo non valido!\");\n }\n try {\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestProperty(\"Range\", \"bytes=0-\");\n connection.connect();\n return connection.getContentLength();\n } catch (IOException ioe) {\n System.err.println(\"I/O error!\");\n return 0;\n }\n }\n", "func2": " static Cipher createCipher(String passwd, int mode) throws Exception {\n PBEKeySpec keySpec = new PBEKeySpec(passwd.toCharArray());\n SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(\"PBEWithMD5AndDES\");\n SecretKey key = keyFactory.generateSecret(keySpec);\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(\"input\".getBytes());\n byte[] digest = md.digest();\n byte[] salt = new byte[8];\n for (int i = 0; i < 8; ++i) salt[i] = digest[i];\n PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);\n Cipher cipher = Cipher.getInstance(\"PBEWithMD5AndDES\");\n cipher.init(mode, key, paramSpec);\n return cipher;\n }\n", "label": 0} {"func1": " private void copyResource() throws Exception {\n URL url = getResource(source);\n InputStream input;\n if (url != null) {\n input = url.openStream();\n } else if (new File(source).exists()) {\n input = new FileInputStream(source);\n } else {\n throw new Exception(\"Could not load resource: \" + source);\n }\n OutputStream output = new FileOutputStream(destinationFile());\n int b;\n while ((b = input.read()) != -1) output.write(b);\n input.close();\n output.close();\n }\n", "func2": " public static void sort(float norm_abst[]) {\n float temp;\n for (int i = 0; i < 7; i++) {\n for (int j = 0; j < 7; j++) {\n if (norm_abst[j] > norm_abst[j + 1]) {\n temp = norm_abst[j];\n norm_abst[j] = norm_abst[j + 1];\n norm_abst[j + 1] = temp;\n }\n }\n }\n printFixed(norm_abst[0]);\n print(\" \");\n printFixed(norm_abst[1]);\n print(\" \");\n printFixed(norm_abst[2]);\n print(\" \");\n printFixed(norm_abst[3]);\n print(\" \");\n printFixed(norm_abst[4]);\n print(\" \");\n printFixed(norm_abst[5]);\n print(\" \");\n printFixed(norm_abst[6]);\n print(\" \");\n printFixed(norm_abst[7]);\n print(\"\\n\");\n }\n", "label": 0} {"func1": " private String getHash(String string) {\n Monitor hashTime = JamonMonitorLogger.getTimeMonitor(Cache.class, \"HashTime\").start();\n MessageDigest md5 = null;\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n md5.reset();\n md5.update(string.getBytes());\n byte[] result = md5.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < result.length; i++) {\n hexString.append(Integer.toHexString(0xFF & result[i]));\n }\n String str = hexString.toString();\n hashTime.stop();\n return str;\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 0} {"func1": " public APIResponse delete(String id) throws Exception {\n APIResponse response = new APIResponse();\n connection = (HttpURLConnection) new URL(url + \"/api/variable/delete/\" + id).openConnection();\n connection.setRequestMethod(\"DELETE\");\n connection.setConnectTimeout(TIMEOUT);\n connection.connect();\n if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {\n response.setDone(true);\n response.setMessage(\"Variable Deleted!\");\n } else {\n response.setDone(false);\n response.setMessage(\"Delete Variable Error Code: Http (\" + connection.getResponseCode() + \")\");\n }\n connection.disconnect();\n return response;\n }\n", "func2": " @Override\n public List search(String query, SortOrder order, int maxResults) throws Exception {\n if (query == null) {\n return null;\n }\n String encodedQuery = \"\";\n try {\n encodedQuery = URLEncoder.encode(query, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw e;\n }\n final int startAt = 0;\n final int pageNr = (startAt - 1) / 30;\n final String url = String.format(QUERYURL, encodedQuery, String.valueOf(pageNr), (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));\n HttpParams httpparams = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);\n HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);\n DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);\n httpclient.getParams().setParameter(\"http.useragent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2\");\n HttpGet httpget = new HttpGet(url);\n HttpResponse response = httpclient.execute(httpget);\n InputStream instream = response.getEntity().getContent();\n String html = HttpHelper.ConvertStreamToString(instream);\n instream.close();\n return parseHtml(html);\n }\n", "label": 0} {"func1": " @Override\n protected String doInBackground(Void... params) {\n HttpClient httpClient = new DefaultHttpClient();\n HttpContext localContext = new BasicHttpContext();\n HttpPost httpPost = new HttpPost(urlFormated);\n try {\n MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);\n for (int index = 0; index < POSTparamList.size(); index++) {\n if (POSTparamList.get(index).getName().equalsIgnoreCase(\"image\")) {\n entity.addPart(POSTparamList.get(index).getName(), new FileBody(new File(POSTparamList.get(index).getValue())));\n } else {\n entity.addPart(POSTparamList.get(index).getName(), new StringBody(POSTparamList.get(index).getValue()));\n }\n }\n httpPost.setEntity(entity);\n HttpResponse response = httpClient.execute(httpPost, localContext);\n return processAnswer(response);\n } catch (IOException e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " @Override\n public OBJModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {\n boolean baseURLWasNull = setBaseURLFromModelURL(url);\n OBJModel model = loadModel(url.openStream(), skin);\n if (baseURLWasNull) {\n popBaseURL();\n }\n return (model);\n }\n", "label": 0} {"func1": " private void loadProperties() {\n if (properties == null) {\n properties = new Properties();\n try {\n URL url = getClass().getResource(propsFile);\n properties.load(url.openStream());\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n }\n", "func2": " @Override\n public String getMessageDigest() throws SarasvatiLoadException {\n if (messageDigest == null) {\n Collections.sort(nodes);\n Collections.sort(externals);\n try {\n MessageDigest digest = MessageDigest.getInstance(\"SHA1\");\n digest.update(name.getBytes());\n for (XmlNode node : nodes) {\n node.addToDigest(digest);\n }\n for (XmlExternal external : externals) {\n external.addToDigest(digest);\n }\n messageDigest = SvUtil.getHexString(digest.digest());\n } catch (NoSuchAlgorithmException nsae) {\n throw new SarasvatiException(\"Unable to load SHA1 algorithm\", nsae);\n }\n }\n return messageDigest;\n }\n", "label": 0} {"func1": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n System.err.println(\"Failed to load the MD5 MessageDigest. \" + \"unable to function normally.\");\n nsae.printStackTrace();\n }\n }\n digest.update(data.getBytes());\n return encodeHex(digest.digest());\n }\n", "func2": " private String postXml(String url, String soapAction, String xml) {\n try {\n URLConnection conn = new URL(url).openConnection();\n if (conn instanceof HttpURLConnection) {\n HttpURLConnection hConn = (HttpURLConnection) conn;\n hConn.setRequestMethod(\"POST\");\n }\n conn.setConnectTimeout(this.connectionTimeout);\n conn.setReadTimeout(this.connectionTimeout);\n conn.setRequestProperty(\"Content-Type\", \"text/xml; charset=utf-8\");\n conn.setRequestProperty(\"Accept\", \"application/soap+xml, text/*\");\n if (soapAction != null) {\n conn.setRequestProperty(\"SOAPAction\", soapAction);\n }\n conn.setDoOutput(true);\n OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());\n out.write(xml);\n out.close();\n BufferedReader resp = new BufferedReader(new InputStreamReader(conn.getInputStream()));\n StringBuilder buf = new StringBuilder();\n String str;\n while ((str = resp.readLine()) != null) {\n buf.append(str);\n }\n return buf.toString();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n", "label": 0} {"func1": " public static void copyFile(File in, File out) throws IOException {\n FileChannel sourceChannel = new FileInputStream(in).getChannel();\n FileChannel destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n }\n", "func2": " private void startScript(wabclient.Attributes prop) throws SAXException {\n dialog.beginScript();\n String url = prop.getValue(\"src\");\n if (url.length() > 0) {\n try {\n BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream()));\n String buffer;\n while (true) {\n buffer = r.readLine();\n if (buffer == null) break;\n dialog.script += buffer + \"\\n\";\n }\n r.close();\n dialog.endScript();\n } catch (IOException ioe) {\n System.err.println(\"[IOError] \" + ioe.getMessage());\n System.exit(0);\n }\n }\n }\n", "label": 0} {"func1": " public void run() {\n URL url;\n try {\n url = new URL(\"http://localhost:8080/glowaxes/dailytrend.jsp\");\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n while ((str = in.readLine()) != null) {\n }\n in.close();\n } catch (MalformedURLException e) {\n } catch (IOException e) {\n }\n }\n", "func2": " KeyStore getKeyStore() throws JarSignerException {\n if (keyStore == null) {\n KeyStore store = null;\n if (providerName == null) {\n try {\n store = KeyStore.getInstance(this.storeType);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n }\n } else {\n try {\n store = KeyStore.getInstance(storeType, providerName);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n } catch (NoSuchProviderException e) {\n e.printStackTrace();\n }\n }\n if (storeURI == null) {\n throw new JarSignerException(\"Cannot load the keystore \" + \" error con el keystore\");\n }\n try {\n storeURI = storeURI.replace(File.separatorChar, '/');\n URL url = null;\n try {\n url = new URL(storeURI);\n } catch (java.net.MalformedURLException e) {\n url = new File(storeURI).toURI().toURL();\n }\n InputStream is = null;\n try {\n is = url.openStream();\n store.load(is, storePass);\n } finally {\n if (is != null) {\n is.close();\n }\n }\n } catch (Exception e) {\n throw new JarSignerException(\"Cannot load the keystore \" + storeURI, e);\n }\n keyStore = store;\n }\n return keyStore;\n }\n", "label": 0} {"func1": " public File read() throws IOException {\n URLConnection conn = url.openConnection();\n conn.setConnectTimeout(5000);\n conn.setReadTimeout(5000);\n conn.connect();\n int length = conn.getContentLength();\n String tempDir = System.getProperty(\"java.io.tmpdir\");\n if (tempDir == null) {\n tempDir = \".\";\n }\n File tempFile = new File(tempDir + \"/\" + new GUID() + \".dat\");\n tempFile.deleteOnExit();\n InputStream in = null;\n OutputStream out = null;\n ProgressMonitor monitor = new ProgressMonitor(parentComponent, \"Downloading \" + url, null, 0, length);\n try {\n in = conn.getInputStream();\n out = new BufferedOutputStream(new FileOutputStream(tempFile));\n int buflen = 1024 * 30;\n int bytesRead = 0;\n byte[] buf = new byte[buflen];\n ;\n long start = System.currentTimeMillis();\n for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {\n if (monitor.isCanceled()) {\n return null;\n }\n bytesRead += nRead;\n out.write(buf, 0, nRead);\n monitor.setProgress(bytesRead);\n }\n } finally {\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n monitor.close();\n }\n return tempFile;\n }\n", "func2": " public static void copy(File from, File to) {\n boolean result;\n if (from.isDirectory()) {\n File[] subFiles = from.listFiles();\n for (int i = 0; i < subFiles.length; i++) {\n File newDir = new File(to, subFiles[i].getName());\n result = false;\n if (subFiles[i].isDirectory()) {\n if (newDir.exists()) result = true; else result = newDir.mkdirs();\n } else if (subFiles[i].isFile()) {\n try {\n result = newDir.createNewFile();\n } catch (IOException e) {\n log.error(\"unable to create new file: \" + newDir, e);\n result = false;\n }\n }\n if (result) copy(subFiles[i], newDir);\n }\n } else if (from.isFile()) {\n FileInputStream in = null;\n FileOutputStream out = null;\n try {\n in = new FileInputStream(from);\n out = new FileOutputStream(to);\n int fileLength = (int) from.length();\n char charBuff[] = new char[fileLength];\n int len;\n int oneChar;\n while ((oneChar = in.read()) != -1) {\n out.write(oneChar);\n }\n } catch (FileNotFoundException e) {\n log.error(\"File not found!\", e);\n } catch (IOException e) {\n log.error(\"Unable to read from file!\", e);\n } finally {\n try {\n if (in != null) in.close();\n if (out != null) out.close();\n } catch (IOException e1) {\n log.error(\"Error closing file reader/writer\", e1);\n }\n }\n }\n }\n", "label": 0} {"func1": " void addDataFromURL(URL theurl) {\n String line;\n InputStream in = null;\n try {\n in = theurl.openStream();\n BufferedReader data = new BufferedReader(new InputStreamReader(in));\n while ((line = data.readLine()) != null) {\n thetext.append(line + \"\\n\");\n }\n } catch (Exception e) {\n System.out.println(e.toString());\n thetext.append(theurl.toString());\n }\n try {\n in.close();\n } catch (Exception e) {\n }\n }\n", "func2": " public void delete(Site site) throws Exception {\n DBOperation dbo = null;\n Connection connection = null;\n PreparedStatement preparedStatement = null;\n ResultSet resultSet = null;\n try {\n String chkSql = \"select id from t_ip_doc where channel_path=?\";\n dbo = createDBOperation();\n connection = dbo.getConnection();\n connection.setAutoCommit(false);\n String[] selfDefinePath = getSelfDefinePath(site.getPath(), \"1\", connection, preparedStatement, resultSet);\n selfDefineDelete(selfDefinePath, connection, preparedStatement);\n preparedStatement = connection.prepareStatement(chkSql);\n preparedStatement.setString(1, site.getPath());\n resultSet = preparedStatement.executeQuery();\n if (resultSet.next()) {\n throw new Exception(\"ɾ��ʧ�ܣ�\" + site.getName() + \"���Ѿ����ĵ����ڣ�\");\n } else {\n String sqlStr = \"delete from t_ip_site where site_path=?\";\n dbo = createDBOperation();\n connection = dbo.getConnection();\n preparedStatement = connection.prepareStatement(sqlStr);\n preparedStatement.setString(1, site.getPath());\n preparedStatement.executeUpdate();\n }\n connection.commit();\n } catch (SQLException ex) {\n connection.rollback();\n throw ex;\n } finally {\n close(resultSet, null, preparedStatement, connection, dbo);\n }\n }\n", "label": 0} {"func1": " public void run() {\n try {\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.setRequestMethod(\"GET\");\n con.setDoInput(true);\n byte[] encodedPassword = (username + \":\" + password).getBytes();\n BASE64Encoder encoder = new BASE64Encoder();\n con.setRequestProperty(\"Authorization\", \"Basic \" + encoder.encode(encodedPassword));\n InputStream is = con.getInputStream();\n BufferedReader rd = new BufferedReader(new InputStreamReader(is));\n String line;\n StringBuffer response = new StringBuffer();\n while ((line = rd.readLine()) != null) {\n response.append(line);\n response.append('\\n');\n lastIteraction = System.currentTimeMillis();\n }\n rd.close();\n is.close();\n con.disconnect();\n result = response.toString();\n finish = true;\n } catch (Throwable e) {\n this.e = e;\n }\n }\n", "func2": " private void loadDynamically(File result, String extraPath) {\n URL url = null;\n InputStream is = null;\n FileOutputStream fos = null;\n try {\n url = new URL(homeServerUrl + extraPath);\n is = url.openStream();\n fos = new FileOutputStream(result);\n byte[] buff = new byte[8192];\n int nbRead;\n while ((nbRead = is.read(buff)) > 0) fos.write(buff, 0, nbRead);\n } catch (IOException e) {\n throw new StellariumException(\"Cannot dynamically load \" + result + \" from \" + url);\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n e.printStackTrace(System.out);\n }\n }\n if (fos != null) {\n try {\n fos.close();\n } catch (IOException e) {\n e.printStackTrace(System.out);\n }\n }\n }\n }\n", "label": 0} {"func1": " public static void copyFromTo(File srcFile, File destFile) {\n FileChannel in = null, out = null;\n FileInputStream fis = null;\n FileOutputStream fos = null;\n try {\n fis = new FileInputStream(srcFile);\n } catch (FileNotFoundException fnfe) {\n System.out.println(\"File: \" + srcFile.toString());\n System.out.println(\"file does not exist, \" + \"is a directory rather than a regular file, \" + \"or for some other reason cannot be opened for reading\");\n System.exit(-1);\n }\n try {\n fos = new FileOutputStream(destFile);\n } catch (FileNotFoundException fnfe) {\n System.out.println(\"File: \" + destFile.toString());\n System.out.println(\"file exists but is a directory rather than a regular file, \" + \"does not exist but cannot be created, \" + \"or cannot be opened for any other reason\");\n System.exit(-1);\n }\n try {\n in = fis.getChannel();\n out = fos.getChannel();\n in.transferTo(0, in.size(), out);\n fos.flush();\n fos.close();\n out.close();\n fis.close();\n in.close();\n System.out.println(\"Completed copying \" + srcFile.toString() + \" to \" + destFile.toString());\n } catch (IOException ioe) {\n System.out.println(\"IOException copying file: \" + ioe.getMessage());\n System.exit(-1);\n }\n long srcModified = srcFile.lastModified();\n if (srcModified > 0L && destFile.exists()) {\n destFile.setLastModified(srcModified);\n }\n }\n", "func2": " private long getSize(String url) throws ClientProtocolException, IOException {\n url = normalizeUrl(url);\n Log.i(LOG_TAG, \"Head \" + url);\n HttpHead httpGet = new HttpHead(url);\n HttpResponse response = mHttpClient.execute(httpGet);\n if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {\n throw new IOException(\"Unexpected Http status code \" + response.getStatusLine().getStatusCode());\n }\n Header[] clHeaders = response.getHeaders(\"Content-Length\");\n if (clHeaders.length > 0) {\n Header header = clHeaders[0];\n return Long.parseLong(header.getValue());\n }\n return -1;\n }\n", "label": 0} {"func1": " protected void createSettingsIfNecessary() throws IOException {\n OutputStream out = null;\n try {\n final File fSettings = SettingsUtils.getSettingsFile();\n if (!fSettings.exists()) {\n fSettings.createNewFile();\n final Path src = new Path(\"mvn/settings.xml\");\n final InputStream in = FileLocator.openStream(getBundle(), src, false);\n out = new FileOutputStream(SettingsUtils.getSettings(), true);\n IOUtils.copy(in, out);\n } else {\n Logger.getLog().info(\"File settings.xml already exists at \" + fSettings);\n }\n } finally {\n if (out != null) {\n out.flush();\n out.close();\n }\n }\n }\n", "func2": " public File read() throws IOException {\n URLConnection conn = url.openConnection();\n conn.setConnectTimeout(5000);\n conn.setReadTimeout(5000);\n conn.connect();\n int length = conn.getContentLength();\n String tempDir = System.getProperty(\"java.io.tmpdir\");\n if (tempDir == null) {\n tempDir = \".\";\n }\n File tempFile = new File(tempDir + \"/\" + new GUID() + \".dat\");\n tempFile.deleteOnExit();\n InputStream in = null;\n OutputStream out = null;\n ProgressMonitor monitor = new ProgressMonitor(parentComponent, \"Downloading \" + url, null, 0, length);\n try {\n in = conn.getInputStream();\n out = new BufferedOutputStream(new FileOutputStream(tempFile));\n int buflen = 1024 * 30;\n int bytesRead = 0;\n byte[] buf = new byte[buflen];\n ;\n long start = System.currentTimeMillis();\n for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {\n if (monitor.isCanceled()) {\n return null;\n }\n bytesRead += nRead;\n out.write(buf, 0, nRead);\n monitor.setProgress(bytesRead);\n }\n } finally {\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n monitor.close();\n }\n return tempFile;\n }\n", "label": 0} {"func1": " public static String load(String id) {\n String xml = \"\";\n if (id.length() < 5) return \"\";\n try {\n working = true;\n URL url = new URL(\"http://pastebin.com/download.php?i=\" + id);\n URLConnection conn = url.openConnection();\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n xml = \"\";\n String str;\n while ((str = reader.readLine()) != null) {\n xml += str;\n }\n reader.close();\n working = false;\n return xml.toString();\n } catch (IOException ex) {\n JOptionPane.showMessageDialog(null, \" Load error\");\n }\n working = false;\n return xml;\n }\n", "func2": " public static void copyFile(File source, File destination) throws IOException {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(source).getChannel();\n out = new FileOutputStream(destination).getChannel();\n in.transferTo(0, in.size(), out);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "label": 0} {"func1": " protected void onlyFileCopy(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n int maxCount = (1024 * 1024 * 64) - (1024 * 32);\n long size = inChannel.size();\n long pos = 0;\n while (pos < size) {\n pos += inChannel.transferTo(pos, maxCount, outChannel);\n }\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " public static String digest(String algorithm, String text) {\n MessageDigest mDigest = null;\n try {\n mDigest = MessageDigest.getInstance(algorithm);\n mDigest.update(text.getBytes(ENCODING));\n } catch (NoSuchAlgorithmException nsae) {\n _log.error(nsae, nsae);\n } catch (UnsupportedEncodingException uee) {\n _log.error(uee, uee);\n }\n byte[] raw = mDigest.digest();\n BASE64Encoder encoder = new BASE64Encoder();\n return encoder.encode(raw);\n }\n", "label": 0} {"func1": " protected byte[] getHashedID(String ID) {\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n md5.update(ID.getBytes());\n byte[] digest = md5.digest();\n byte[] bytes = new byte[WLDB_ID_SIZE];\n for (int i = 0; i < bytes.length; i++) {\n bytes[i] = digest[i];\n }\n return bytes;\n } catch (NoSuchAlgorithmException exception) {\n System.err.println(\"Java VM is not compatible\");\n exit();\n return null;\n }\n }\n", "func2": " public static void CopyFile(String in, String out) throws Exception {\n FileChannel sourceChannel = new FileInputStream(new File(in)).getChannel();\n FileChannel destinationChannel = new FileOutputStream(new File(out)).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n }\n", "label": 0} {"func1": " public static String hashPasswordForOldMD5(String password) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(password.getBytes(\"UTF-8\"));\n byte messageDigest[] = md.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n String hex = Integer.toHexString(0xFF & messageDigest[i]);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException nsae) {\n throw new IllegalStateException(nsae.getMessage());\n } catch (UnsupportedEncodingException uee) {\n throw new IllegalStateException(uee.getMessage());\n }\n }\n", "func2": " public HttpResponseExchange execute() throws Exception {\n HttpResponseExchange forwardResponse = null;\n int fetchSizeLimit = Config.getInstance().getFetchLimitSize();\n while (null != lastContentRange) {\n forwardRequest.setBody(new byte[0]);\n ContentRangeHeaderValue old = lastContentRange;\n long sendSize = fetchSizeLimit;\n if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {\n sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);\n }\n if (sendSize <= 0) {\n break;\n }\n lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);\n forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));\n forwardResponse = syncFetch(forwardRequest);\n if (sendSize < fetchSizeLimit) {\n lastContentRange = null;\n }\n }\n return forwardResponse;\n }\n", "label": 0} {"func1": " public void testJPEGRaster() throws MalformedURLException, IOException {\n System.out.println(\"JPEGCodec RasterImage:\");\n long start = Calendar.getInstance().getTimeInMillis();\n for (int i = 0; i < images.length; i++) {\n String url = Constants.getDefaultURIMediaConnectorBasePath() + \"albums/hund/\" + images[i];\n InputStream istream = (new URL(url)).openStream();\n JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);\n Raster raster = dec.decodeAsRaster();\n int width = raster.getWidth();\n int height = raster.getHeight();\n istream.close();\n System.out.println(\"w: \" + width + \" - h: \" + height);\n }\n long stop = Calendar.getInstance().getTimeInMillis();\n System.out.println(\"zeit: \" + (stop - start));\n }\n", "func2": " protected boolean copyFile(File sourceFile, File destinationFile) {\n try {\n FileChannel srcChannel = new FileInputStream(sourceFile).getChannel();\n FileChannel dstChannel = new FileOutputStream(destinationFile).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n return true;\n }\n", "label": 0} {"func1": " private int[] sortRows(int[] rows) {\n for (int i = 0; i < rows.length; i++) {\n for (int j = 0; j < rows.length - 1; j++) {\n if (rows[j] > rows[j + 1]) {\n int temp = rows[j];\n rows[j] = rows[j + 1];\n rows[j + 1] = temp;\n }\n }\n }\n return rows;\n }\n", "func2": " public int update(BusinessObject o) throws DAOException {\n int update = 0;\n Bill bill = (Bill) o;\n try {\n PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery(\"UPDATE_BILL\"));\n pst.setInt(1, bill.getId());\n update = pst.executeUpdate();\n if (update <= 0) {\n connection.rollback();\n throw new DAOException(\"Number of rows <= 0\");\n } else if (update > 1) {\n connection.rollback();\n throw new DAOException(\"Number of rows > 1\");\n }\n connection.commit();\n } catch (SQLException e) {\n Log.write(e.getMessage());\n throw new DAOException(\"A SQLException has occured\");\n } catch (NullPointerException npe) {\n Log.write(npe.getMessage());\n throw new DAOException(\"Connection null\");\n }\n return update;\n }\n", "label": 0} {"func1": " public static void polishOff(IProgressMonitor monitor, String from, String to, String renameTo) {\n if (monitor != null && monitor.isCanceled()) {\n return;\n }\n try {\n ftpClient = new FTPClient();\n ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST)));\n ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT));\n ftpClient.connect();\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD)));\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if (from != null) {\n FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, false);\n synchedSet.add(ftpHolder);\n }\n JobHandler.aquireFTPLock();\n for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) {\n if (monitor != null && monitor.isCanceled()) {\n JobHandler.releaseFTPLock();\n ftpClient.quit();\n return;\n }\n Thread.yield();\n FTPHolder element = (FTPHolder) iter.next();\n ftpClient.setType(FTPTransferType.ASCII);\n ftpClient.put(element.from, element.to);\n if (element.renameTo != null) {\n try {\n ftpClient.delete(element.renameTo);\n } catch (Exception e) {\n }\n ftpClient.rename(element.to, element.renameTo);\n log.info(\"RENAME: \" + element.to + \"To: \" + element.renameTo);\n }\n }\n JobHandler.releaseFTPLock();\n ftpClient.quit();\n } catch (UnknownHostException e) {\n e.printStackTrace();\n } catch (FTPException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n synchedSet.clear();\n }\n", "func2": " public void write() throws IOException {\n JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);\n if (includeJars != null) {\n HashSet allEntries = new HashSet(includeJars);\n if (!ignoreDependencies) expandSet(allEntries);\n for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {\n JarFile jar = getJarFile(iterator.next());\n Enumeration jarEntries = jar.entries();\n while (jarEntries.hasMoreElements()) {\n ZipEntry o1 = (ZipEntry) jarEntries.nextElement();\n if (o1.getName().equalsIgnoreCase(\"META-INF/MANIFEST.MF\") || o1.getSize() <= 0) continue;\n jarOut.putNextEntry(o1);\n InputStream entryStream = jar.getInputStream(o1);\n IOUtils.copy(entryStream, jarOut);\n jarOut.closeEntry();\n }\n }\n }\n jarOut.finish();\n jarOut.close();\n }\n", "label": 0} {"func1": " public void doBody(JWebLiteRequestWrapper req, JWebLiteResponseWrapper resp) throws SkipException {\n BufferedInputStream bis = null;\n BufferedOutputStream bos = null;\n try {\n bis = new BufferedInputStream(new FileInputStream(this.loadData(req)));\n bos = new BufferedOutputStream(resp.getOutputStream());\n IOUtils.copy(bis, bos);\n bos.flush();\n } catch (Exception e) {\n _cat.warn(\"Write data failed!\", e);\n } finally {\n IOUtils.closeQuietly(bis);\n IOUtils.closeQuietly(bos);\n }\n }\n", "func2": " private boolean checkHashBack(Facade facade, HttpServletRequest req) {\n String txtTransactionID = req.getParameter(\"txtTransactionID\");\n String txtOrderTotal = req.getParameter(\"txtOrderTotal\");\n String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);\n String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);\n String txtHashBack = req.getParameter(\"txtHashBack\");\n String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);\n String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;\n MessageDigest digest;\n try {\n digest = java.security.MessageDigest.getInstance(\"MD5\");\n digest.update(securityValue.getBytes());\n byte[] array = digest.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n String hash = sb.toString();\n System.out.println(\"com.eshop.http.servlets.PaymentController.checkHashBack: \" + hash + \" \" + txtHashBack);\n if (txtHashBack.equals(hash)) {\n return true;\n }\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n return false;\n }\n", "label": 0} {"func1": " public TableDirectory(RandomAccessFile raf) throws IOException {\n version = raf.readInt();\n numTables = raf.readShort();\n searchRange = raf.readShort();\n entrySelector = raf.readShort();\n rangeShift = raf.readShort();\n entries = new DirectoryEntry[numTables];\n for (int i = 0; i < numTables; i++) {\n entries[i] = new DirectoryEntry(raf);\n }\n boolean modified = true;\n while (modified) {\n modified = false;\n for (int i = 0; i < numTables - 1; i++) {\n if (entries[i].getOffset() > entries[i + 1].getOffset()) {\n DirectoryEntry temp = entries[i];\n entries[i] = entries[i + 1];\n entries[i + 1] = temp;\n modified = true;\n }\n }\n }\n }\n", "func2": " public void importSequences() {\n names = new ArrayList();\n sequences = new ArrayList();\n try {\n InputStream is = urls[urlComboBox.getSelectedIndex()].openStream();\n ImportHelper helper = new ImportHelper(new InputStreamReader(is));\n int ch = helper.read();\n while (ch != '>') {\n ch = helper.read();\n }\n do {\n String line = helper.readLine();\n StringTokenizer tokenizer = new StringTokenizer(line, \" \\t\");\n String name = tokenizer.nextToken();\n StringBuffer seq = new StringBuffer();\n helper.readSequence(seq, \">\", Integer.MAX_VALUE, \"-\", \"?\", \"\", null);\n ch = helper.getLastDelimiter();\n names.add(name);\n sequences.add(seq.toString());\n } while (ch == '>');\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (EOFException e) {\n } catch (IOException e) {\n }\n }\n", "label": 0} {"func1": " private void download(String address, String localFileName) throws UrlNotFoundException, Exception {\n String ext = G_File.getExtensao(address);\n if (ext.equals(\"jsp\")) {\n throw new Exception(\"Erro ao baixar pagina JSP, tipo negado.\" + address);\n }\n File temp = new File(localFileName + \".tmp\");\n if (temp.exists()) temp.delete();\n OutputStream out = null;\n URLConnection conn = null;\n InputStream in = null;\n try {\n try {\n URL url = new URL(address);\n conn = url.openConnection();\n in = conn.getInputStream();\n } catch (FileNotFoundException e2) {\n throw new UrlNotFoundException();\n }\n out = new BufferedOutputStream(new FileOutputStream(temp));\n byte[] buffer = new byte[1024];\n int numRead;\n long numWritten = 0;\n while ((numRead = in.read(buffer)) != -1) {\n out.write(buffer, 0, numRead);\n numWritten += numRead;\n }\n } catch (UrlNotFoundException exception) {\n throw exception;\n } catch (Exception exception) {\n throw exception;\n } finally {\n try {\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n } catch (IOException ioe) {\n }\n }\n File oldArq = new File(localFileName);\n if (oldArq.exists()) {\n oldArq.delete();\n }\n oldArq = null;\n File nomeFinal = new File(localFileName);\n temp.renameTo(nomeFinal);\n }\n", "func2": " public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "label": 0} {"func1": " public static String connRemote(JSONObject jsonObject, String OPCode) {\n String retSrc = \"\";\n try {\n HttpClient httpClient = new DefaultHttpClient();\n HttpPost httpPost = new HttpPost(AZConstants.validateURL);\n HttpParams httpParams = new BasicHttpParams();\n List nameValuePair = new ArrayList();\n nameValuePair.add(new BasicNameValuePair(AZConstants.ACTION_TYPE, OPCode));\n nameValuePair.add(new BasicNameValuePair(AZConstants.PARAM, jsonObject.toString()));\n httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));\n httpPost.setParams(httpParams);\n HttpResponse response = httpClient.execute(httpPost);\n retSrc = EntityUtils.toString(response.getEntity());\n } catch (Exception e) {\n Log.e(TAG, e.toString());\n }\n return retSrc;\n }\n", "func2": " public void init(ConnectionManager mgr, Hashtable cfg, Socket sock) throws RemoteException {\n _cman = mgr;\n _sock = sock;\n for (int i = 0; i < 256; i++) {\n String key = Integer.toHexString(i);\n if (key.length() < 2) key = \"0\" + key;\n availcmd.push(key);\n commands.put(key, null);\n }\n try {\n _sout = new PrintWriter(_sock.getOutputStream(), true);\n _sinp = new BufferedReader(new InputStreamReader(_sock.getInputStream()));\n String seed = \"\";\n Random rand = new Random();\n for (int i = 0; i < 16; i++) {\n String hex = Integer.toHexString(rand.nextInt(256));\n if (hex.length() < 2) hex = \"0\" + hex;\n seed += hex.substring(hex.length() - 2);\n }\n String pass = _mpsw + seed + _spsw;\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n md5.update(pass.getBytes());\n String hash = hash2hex(md5.digest()).toLowerCase();\n String banner = \"INIT \" + \"servername\" + \" \" + hash + \" \" + seed;\n sendLine(banner);\n String txt = readLine(5);\n if (txt == null) {\n throw new IOException(\"Slave did not send banner !!\");\n }\n String sname = \"\";\n String spass = \"\";\n String sseed = \"\";\n try {\n String[] items = txt.split(\" \");\n sname = items[1].trim();\n spass = items[2].trim();\n sseed = items[3].trim();\n } catch (Exception e) {\n AsyncSlaveListener.invalidSlave(\"INITFAIL BadKey\", _sock);\n }\n pass = _spsw + sseed + _mpsw;\n md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n md5.update(pass.getBytes());\n hash = hash2hex(md5.digest()).toLowerCase();\n if (!sname.equals(_name)) {\n AsyncSlaveListener.invalidSlave(\"INITFAIL Unknown\", _sock);\n }\n if (!spass.toLowerCase().equals(hash.toLowerCase())) {\n AsyncSlaveListener.invalidSlave(\"INITFAIL BadKey\", _sock);\n }\n _cman.getSlaveManager().addSlave(_name, this, getSlaveStatus(), -1);\n start();\n } catch (IOException e) {\n if (e instanceof ConnectIOException && e.getCause() instanceof EOFException) {\n logger.info(\"Check slaves.xml on the master that you are allowed to connect.\");\n }\n logger.info(\"IOException: \" + e.toString());\n try {\n sock.close();\n } catch (Exception e1) {\n }\n } catch (Exception e) {\n logger.warn(\"Exception: \" + e.toString());\n try {\n sock.close();\n } catch (Exception e2) {\n }\n }\n System.gc();\n }\n", "label": 0} {"func1": " public static String SHA1(String text) {\n byte[] sha1hash = new byte[40];\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n sha1hash = md.digest();\n } catch (UnsupportedEncodingException ex) {\n Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);\n } catch (NoSuchAlgorithmException ex) {\n Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);\n }\n return convertToHex(sha1hash);\n }\n", "func2": " private void Submit2URL(URL url) throws Exception {\n HttpURLConnection urlc = null;\n try {\n urlc = (HttpURLConnection) url.openConnection();\n urlc.setRequestMethod(\"GET\");\n urlc.setDoOutput(true);\n urlc.setDoInput(true);\n urlc.setUseCaches(false);\n urlc.setAllowUserInteraction(false);\n if (urlc.getResponseCode() != 200) {\n InputStream in = null;\n Reader reader = null;\n try {\n in = urlc.getInputStream();\n reader = new InputStreamReader(in, \"UTF-8\");\n int read = 0;\n char[] buf = new char[1024];\n String error = null;\n while ((read = reader.read(buf)) >= 0) {\n if (error == null) error = new String(buf, 0, read); else error += new String(buf, 0, read);\n }\n throw new NpsException(error, ErrorHelper.SYS_UNKOWN);\n } finally {\n if (reader != null) try {\n reader.close();\n } catch (Exception e1) {\n }\n if (in != null) try {\n in.close();\n } catch (Exception e1) {\n }\n }\n }\n } finally {\n if (urlc != null) try {\n urlc.disconnect();\n } catch (Exception e1) {\n }\n }\n }\n", "label": 0} {"func1": " private static InputStream getCMSResultAsStream(String rqlQuery) throws RQLException {\n OutputStreamWriter osr = null;\n try {\n URL url = new URL(\"http\", HOST, FILE);\n URLConnection conn = url.openConnection();\n conn.setDoOutput(true);\n osr = new OutputStreamWriter(conn.getOutputStream());\n osr.write(rqlQuery);\n osr.flush();\n return conn.getInputStream();\n } catch (IOException ioe) {\n throw new RQLException(\"IO Exception reading result from server\", ioe);\n } finally {\n if (osr != null) {\n try {\n osr.close();\n } catch (IOException ioe) {\n }\n }\n }\n }\n", "func2": " public static InputStream getStreamFromSystemIdentifier(String systemId, EntityResolver resolver) throws Exception {\n InputSource source = null;\n InputStream stream = null;\n if (resolver != null) {\n try {\n source = resolver.resolveEntity(null, systemId);\n } catch (Exception e) {\n LogService.instance().log(LogService.ERROR, \"DocumentFactory: Unable to resolve '\" + systemId + \"'\");\n LogService.instance().log(LogService.ERROR, e);\n }\n }\n if (source != null) {\n try {\n stream = source.getByteStream();\n } catch (Exception e) {\n LogService.instance().log(LogService.ERROR, \"DocumentFactory: Unable to get bytestream from '\" + source.getSystemId() + \"'\");\n LogService.instance().log(LogService.ERROR, e);\n }\n }\n if (stream == null) {\n URL url = new URL(systemId);\n stream = url.openStream();\n }\n return stream;\n }\n", "label": 0} {"func1": " private static byte[] baseHash(String name, String password) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"MD5\");\n digest.reset();\n digest.update(name.toLowerCase().getBytes());\n digest.update(password.getBytes());\n return digest.digest();\n } catch (NoSuchAlgorithmException ex) {\n d(\"MD5 algorithm not found!\");\n throw new RuntimeException(\"MD5 algorithm not found! Unable to authenticate\");\n }\n }\n", "func2": " @Override\n public List search(String query, SortOrder order, int maxResults) throws Exception {\n if (query == null) {\n return null;\n }\n String encodedQuery = \"\";\n try {\n encodedQuery = URLEncoder.encode(query, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw e;\n }\n final int startAt = 0;\n final int pageNr = (startAt - 1) / 30;\n final String url = String.format(QUERYURL, encodedQuery, String.valueOf(pageNr), (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));\n HttpParams httpparams = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);\n HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);\n DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);\n httpclient.getParams().setParameter(\"http.useragent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2\");\n HttpGet httpget = new HttpGet(url);\n HttpResponse response = httpclient.execute(httpget);\n InputStream instream = response.getEntity().getContent();\n String html = HttpHelper.ConvertStreamToString(instream);\n instream.close();\n return parseHtml(html);\n }\n", "label": 0} {"func1": " public void executeUpdateTransaction(List queries) throws SQLException {\n assert connection != null;\n boolean autoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n try {\n Iterator iterator = queries.iterator();\n while (iterator.hasNext()) {\n String query = (String) iterator.next();\n Statement statement = connection.createStatement();\n statement.executeUpdate(query);\n }\n connection.commit();\n connection.setAutoCommit(autoCommit);\n } catch (SQLException e) {\n connection.rollback();\n throw new SQLException(e.getMessage());\n }\n }\n", "func2": " public static String retrieveData(URL url) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setRequestProperty(\"User-agent\", \"MZmine 2\");\n InputStream is = connection.getInputStream();\n if (is == null) {\n throw new IOException(\"Could not establish a connection to \" + url);\n }\n StringBuffer buffer = new StringBuffer();\n try {\n InputStreamReader reader = new InputStreamReader(is, \"UTF-8\");\n char[] cb = new char[1024];\n int amtRead = reader.read(cb);\n while (amtRead > 0) {\n buffer.append(cb, 0, amtRead);\n amtRead = reader.read(cb);\n }\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n is.close();\n return buffer.toString();\n }\n", "label": 0} {"func1": " public String storeImage(InputStream inStream, String fileName, boolean resize) throws Exception {\n Calendar rightNow = Calendar.getInstance();\n String dayNamedFolderName = \"\" + rightNow.get(Calendar.YEAR) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.MONTH) + 1) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.DATE));\n String uploadDirRoot = props.getProperty(\"uploaded.files.root\");\n File file = new File(uploadDirRoot + System.getProperty(\"file.separator\") + dayNamedFolderName);\n if (!file.exists()) file.mkdirs();\n String extension = FilenameUtils.getExtension(fileName);\n String outFileName;\n if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEORIGINALFILENAME, \"true\"))) {\n outFileName = StringUtil.removeSpecChars(StringUtil.unaccent(FilenameUtils.getBaseName(fileName)));\n } else {\n outFileName = StringUtil.hash(fileName + Long.toString(System.currentTimeMillis()));\n }\n if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEEXTENSION, \"true\"))) {\n outFileName = outFileName + DOT + extension;\n }\n String outPathAndName = uploadDirRoot + System.getProperty(\"file.separator\") + dayNamedFolderName + System.getProperty(\"file.separator\") + props.getProperty(\"uploaded.files.prefix\") + outFileName;\n File uploadedFile = new File(outPathAndName);\n _logger.info(\"uploadedFile.getAbsolutePath() = {}\", uploadedFile.getAbsolutePath());\n uploadedFile.createNewFile();\n OutputStream outStream = new FileOutputStream(outPathAndName);\n IOUtils.copyLarge(inStream, outStream);\n IOUtils.closeQuietly(inStream);\n outStream.close();\n if (resize) {\n writeResizedImage(outPathAndName, extension, \"imgSize_xs\");\n writeResizedImage(outPathAndName, extension, \"imgSize_s\");\n writeResizedImage(outPathAndName, extension, \"imgSize_m\");\n writeResizedImage(outPathAndName, extension, \"imgSize_l\");\n writeResizedImage(outPathAndName, extension, \"imgSize_xl\");\n }\n String retVal = dayNamedFolderName + \"/\" + props.getProperty(\"uploaded.files.prefix\") + outFileName;\n return retVal;\n }\n", "func2": " private BingResponse queryBing(BingRequest request) throws BingException {\n try {\n if (logger.isDebugEnabled()) {\n logger.debug(\"Searching through bing...\");\n }\n String query = request.getQuery();\n query = URLEncoder.encode(query, \"UTF-8\");\n URL url = new URL(\"http://api.bing.net/json.aspx?\" + \"AppId=\" + request.getAppId() + \"&Query=\" + query + \"&Sources=\" + request.getType().toString());\n URLConnection connection = null;\n if (useProxy) {\n if (proxyType == null) {\n throw new BingException(\"Please set a proxy first before trying to connect through a proxy\", new Throwable());\n }\n connection = ProxyWrapper.getURLConnection(url.toString(), proxyType.toString(), proxyHost, proxyPort);\n } else {\n connection = new URL(url.toString()).openConnection();\n }\n String line;\n StringBuilder builder = new StringBuilder();\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n while ((line = reader.readLine()) != null) {\n builder.append(line);\n }\n String response = builder.toString();\n ResponseParser parser = new ResponseParser();\n parser.getError(response);\n return parser.getResults(response);\n } catch (MalformedURLException e) {\n logger.error(e);\n throw new ConnectionException(\"Could not connect to host\", e);\n } catch (IOException e) {\n logger.error(e);\n throw new ConnectionException(\"Could not connect to host\", e);\n }\n }\n", "label": 0} {"func1": " public static URLConnection openProxiedConnection(URL url) throws IOException {\n if (proxyHost != null) {\n System.getProperties().put(\"proxySet\", \"true\");\n System.getProperties().put(\"proxyHost\", proxyHost);\n System.getProperties().put(\"proxyPort\", proxyPort);\n }\n URLConnection cnx = url.openConnection();\n if (proxyUsername != null) {\n cnx.setRequestProperty(\"Proxy-Authorization\", proxyEncodedPassword);\n }\n return cnx;\n }\n", "func2": " private void startScript(wabclient.Attributes prop) throws SAXException {\n dialog.beginScript();\n String url = prop.getValue(\"src\");\n if (url.length() > 0) {\n try {\n BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream()));\n String buffer;\n while (true) {\n buffer = r.readLine();\n if (buffer == null) break;\n dialog.script += buffer + \"\\n\";\n }\n r.close();\n dialog.endScript();\n } catch (IOException ioe) {\n System.err.println(\"[IOError] \" + ioe.getMessage());\n System.exit(0);\n }\n }\n }\n", "label": 0} {"func1": " boolean checkIfUserExists(String username) throws IOException {\n try {\n URL url = new URL(WS_URL + \"/user/\" + URLEncoder.encode(username, \"UTF-8\") + \"/profile.xml\");\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.connect();\n InputStream is = conn.getInputStream();\n is.close();\n return true;\n } catch (FileNotFoundException e) {\n return false;\n }\n }\n", "func2": " protected void innerProcess(ProcessorURI curi) throws InterruptedException {\n Pattern regexpr = curi.get(this, STRIP_REG_EXPR);\n ReplayCharSequence cs = null;\n try {\n cs = curi.getRecorder().getReplayCharSequence();\n } catch (Exception e) {\n curi.getNonFatalFailures().add(e);\n logger.warning(\"Failed get of replay char sequence \" + curi.toString() + \" \" + e.getMessage() + \" \" + Thread.currentThread().getName());\n return;\n }\n MessageDigest digest = null;\n try {\n try {\n digest = MessageDigest.getInstance(SHA1);\n } catch (NoSuchAlgorithmException e1) {\n e1.printStackTrace();\n return;\n }\n digest.reset();\n String s = null;\n if (regexpr != null) {\n s = cs.toString();\n } else {\n Matcher m = regexpr.matcher(cs);\n s = m.replaceAll(\" \");\n }\n digest.update(s.getBytes());\n byte[] newDigestValue = digest.digest();\n curi.setContentDigest(SHA1, newDigestValue);\n } finally {\n if (cs != null) {\n try {\n cs.close();\n } catch (IOException ioe) {\n logger.warning(TextUtils.exceptionToString(\"Failed close of ReplayCharSequence.\", ioe));\n }\n }\n }\n }\n", "label": 0} {"func1": " @Test\n public void test01_ok_failed_500_no_logo() throws Exception {\n DefaultHttpClient client = new DefaultHttpClient();\n try {\n HttpPost post = new HttpPost(xlsURL);\n HttpResponse response = client.execute(post);\n assertEquals(\"failed code for \", 500, response.getStatusLine().getStatusCode());\n } finally {\n client.getConnectionManager().shutdown();\n }\n }\n", "func2": " public void extractImage(String input, String output, DjatokaDecodeParam params, IWriter w) throws DjatokaException {\n File in = null;\n String dest = output;\n if (input.equals(STDIN)) {\n try {\n in = File.createTempFile(\"tmp\", \".jp2\");\n input = in.getAbsolutePath();\n in.deleteOnExit();\n IOUtils.copyFile(new File(STDIN), in);\n } catch (IOException e) {\n logger.error(\"Unable to process image from \" + STDIN + \": \" + e.getMessage());\n throw new DjatokaException(e);\n }\n }\n BufferedImage bi = extractImpl.process(input, params);\n if (bi != null) {\n if (params.getScalingFactor() != 1.0 || params.getScalingDimensions() != null) bi = applyScaling(bi, params);\n if (params.getTransform() != null) bi = params.getTransform().run(bi);\n try {\n BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(dest)));\n w.write(bi, os);\n os.close();\n } catch (FileNotFoundException e) {\n logger.error(\"Requested file was not found: \" + dest);\n throw new DjatokaException(e);\n } catch (IOException e) {\n logger.error(\"Error attempting to close: \" + dest);\n throw new DjatokaException(e);\n }\n }\n if (in != null) in.delete();\n }\n", "label": 0} {"func1": " @Override\n public InputStream getInputStream() {\n try {\n String url = webBrowserObject.resourcePath;\n File file = Utils.getLocalFile(url);\n if (file != null) {\n url = webBrowserObject.getLocalFileURL(file);\n }\n url = url.substring(0, url.lastIndexOf('/')) + \"/\" + resource;\n return new URL(url).openStream();\n } catch (Exception e) {\n }\n return null;\n }\n", "func2": " public static InputStream getConfigIs(String path, String name) throws ProgrammerException, DesignerException, UserException {\n InputStream is = null;\n try {\n URL url = getConfigResource(new MonadUri(path).append(name));\n if (url != null) {\n is = url.openStream();\n }\n } catch (IOException e) {\n throw new ProgrammerException(e);\n }\n return is;\n }\n", "label": 0} {"func1": " @Override\n public void update(String mail, String email, String pwd, String firstname, String lastname) throws NamingException, NoSuchAlgorithmException, UnsupportedEncodingException {\n jndiManagerConnection connection = new jndiManagerConnection();\n Attributes attrs = new BasicAttributes();\n attrs.put(\"sn\", lastname);\n attrs.put(\"givenName\", firstname);\n attrs.put(\"cn\", firstname + \" \" + lastname);\n if (!pwd.isEmpty()) {\n MessageDigest sha = MessageDigest.getInstance(\"md5\");\n sha.reset();\n sha.update(pwd.getBytes(\"utf-8\"));\n byte[] digest = sha.digest();\n String hash = Base64.encodeBase64String(digest);\n attrs.put(\"userPassword\", \"{MD5}\" + hash);\n }\n DirContext ctx = connection.getLDAPDirContext();\n ctx.modifyAttributes(\"mail=\" + mail + \",\" + dn, DirContext.REPLACE_ATTRIBUTE, attrs);\n if (!mail.equals(email)) {\n String newName = \"mail=\" + email + \",\" + dn;\n String oldName = \"mail=\" + mail + \",\" + dn;\n ctx.rename(oldName, newName);\n }\n }\n", "func2": " @Override\n public void respondGet(HttpServletResponse resp) throws IOException {\n setHeaders(resp);\n final OutputStream os;\n if (willDeflate()) {\n resp.setHeader(\"Content-Encoding\", \"gzip\");\n os = new GZIPOutputStream(resp.getOutputStream(), bufferSize);\n } else os = resp.getOutputStream();\n transferStreams(url.openStream(), os);\n }\n", "label": 0} {"func1": " @SuppressWarnings(\"unchecked\")\n private ReaderFeed processEntrys(String urlStr, String currentFlag) throws UnsupportedEncodingException, IOException, JDOMException {\n String key = \"processEntrys@\" + urlStr + \"_\" + currentFlag;\n if (cache.containsKey(key)) {\n return (ReaderFeed) cache.get(key);\n }\n List postList = new ArrayList();\n URL url = new URL(urlStr);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Cookie\", \"SID=\" + sid);\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), \"UTF-8\"));\n SAXBuilder builder = new SAXBuilder(false);\n Document doc = builder.build(reader);\n Element root = doc.getRootElement();\n Namespace grNamespace = root.getNamespace(\"gr\");\n Namespace namespace = root.getNamespace();\n String newflag = root.getChildText(\"continuation\", grNamespace);\n String title = root.getChildText(\"title\", namespace);\n String subTitle = root.getChildText(\"subtitle\", namespace);\n List entryList = root.getChildren(\"entry\", namespace);\n DateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n for (Element e : entryList) {\n Post post = new Post();\n post.setTitle(e.getChildText(\"title\", namespace));\n try {\n post.setDate(sdf.parse(e.getChildText(\"published\", namespace)));\n } catch (ParseException e1) {\n }\n post.setUrl(e.getChild(\"link\", namespace).getAttributeValue(\"href\"));\n post.setSauthor(e.getChild(\"author\", namespace).getChildText(\"name\", namespace));\n String content = e.getChildText(\"content\", namespace);\n if (StringUtils.isEmpty(content)) {\n content = e.getChildText(\"description\", namespace);\n }\n if (StringUtils.isEmpty(content)) {\n content = e.getChildText(\"summary\", namespace);\n }\n post.setContent(content);\n postList.add(post);\n }\n ReaderFeed readerFeed = new ReaderFeed();\n readerFeed.setTitle(title);\n readerFeed.setSubTitle(subTitle);\n readerFeed.setFlag(newflag);\n readerFeed.setPostList(postList);\n cache.put(key, readerFeed);\n return readerFeed;\n }\n", "func2": " static void populateResources() throws BasicException {\n try {\n List templates = DatabaseValidator.listResources(\"/net/adrianromero/templates/\" + Locale.getDefault().getLanguage());\n if (templates.size() == 0) {\n templates = DatabaseValidator.listResources(\"/net/adrianromero/templates/en\");\n }\n for (URL url : templates) {\n String fileName = url.getFile();\n fileName = fileName.substring(fileName.lastIndexOf('/') + 1);\n if (fileName.endsWith(\".xml\") || fileName.endsWith(\".txt\")) {\n Resource templateResource = new Resource(fileName.substring(0, fileName.length() - 4));\n InputStream is = url.openStream();\n StringBuffer strBuff = new StringBuffer();\n BufferedReader br = new BufferedReader(new InputStreamReader(is));\n String str;\n while ((str = br.readLine()) != null) {\n strBuff.append(str + \"\\n\");\n }\n templateResource.setText(strBuff.toString());\n templateResource.save();\n }\n }\n } catch (MalformedURLException e1) {\n logger.error(\"Unable to load templates\", e1);\n } catch (IOException e1) {\n logger.error(\"Unable to load templates\", e1);\n }\n String[][] images = new String[][] { { \"default.user\", \"yast_sysadmin.png\" }, { \"default.product\", \"colorize.png\" }, { \"Window.Logo\", \"windowlogo.png\" }, { \"Image.Backarrow\", \"3backarrow.png\" } };\n for (int i = 0; i < images.length; i++) {\n Image img = new Image();\n img.setBufferedImage(ImageUtils.readImage(DatabaseValidator.class.getResource(\"/net/adrianromero/images/\" + images[i][1])));\n img.save();\n Property imgProperty = new Property(images[i][0]);\n imgProperty.setValue(\"\" + img.getId());\n imgProperty.save();\n }\n }\n", "label": 0} {"func1": " private String encode(String str) {\n StringBuffer buf = new StringBuffer();\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(str.getBytes());\n byte bytes[] = md5.digest();\n for (int i = 0; i < bytes.length; i++) {\n String s = Integer.toHexString(bytes[i] & 0xff);\n if (s.length() == 1) {\n buf.append(\"0\");\n }\n buf.append(s);\n }\n } catch (Exception ex) {\n }\n return buf.toString();\n }\n", "func2": " public static void copyFile(File source, File dest) throws IOException {\n if (!dest.exists()) {\n dest.createNewFile();\n }\n FileChannel from = null;\n FileChannel to = null;\n try {\n from = new FileInputStream(source).getChannel();\n to = new FileOutputStream(dest).getChannel();\n to.transferFrom(from, 0, from.size());\n } finally {\n if (from != null) {\n from.close();\n }\n if (to != null) {\n to.close();\n }\n }\n }\n", "label": 0} {"func1": " @Override\n public void makeRead(final String user, final long databaseID, final long time) throws SQLException {\n final String query = \"insert into fs.read_post (post, user, read_date) values (?, ?, ?)\";\n ensureConnection();\n final PreparedStatement statement = m_connection.prepareStatement(query);\n try {\n statement.setLong(1, databaseID);\n statement.setString(2, user);\n statement.setTimestamp(3, new Timestamp(time));\n final int count = statement.executeUpdate();\n if (0 == count) {\n throw new SQLException(\"Nothing updated.\");\n }\n m_connection.commit();\n } catch (final SQLException e) {\n m_connection.rollback();\n throw e;\n } finally {\n statement.close();\n }\n }\n", "func2": " public static void main(String args[]) throws IOException {\n BufferedReader in = new BufferedReader(new FileReader(args[0]));\n Writer out = new FileWriter(args[1]);\n out = new WrapFilter(new BufferedWriter(out), 40);\n out = new TitleCaseFilter(out);\n String line;\n while ((line = in.readLine()) != null) out.write(line + \"\\n\");\n out.close();\n in.close();\n }\n", "label": 0} {"func1": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n System.out.println(\"Error: \" + e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n System.out.println(\"Error:\" + e);\n }\n }\n", "func2": " public static String load(String id) {\n String xml = \"\";\n if (id.length() < 5) return \"\";\n try {\n working = true;\n URL url = new URL(\"http://pastebin.com/download.php?i=\" + id);\n URLConnection conn = url.openConnection();\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n xml = \"\";\n String str;\n while ((str = reader.readLine()) != null) {\n xml += str;\n }\n reader.close();\n working = false;\n return xml.toString();\n } catch (IOException ex) {\n JOptionPane.showMessageDialog(null, \" Load error\");\n }\n working = false;\n return xml;\n }\n", "label": 0} {"func1": " public static byte[] openHttpResult(String urlPath, boolean retry) throws IOException {\n AQUtility.debug(\"net\", urlPath);\n URL url = new URL(urlPath);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setUseCaches(false);\n connection.setInstanceFollowRedirects(true);\n connection.setConnectTimeout(NET_TIMEOUT);\n int code = connection.getResponseCode();\n if (code == 307 && retry) {\n String redirect = connection.getHeaderField(\"Location\");\n return openHttpResult(redirect, false);\n }\n if (code == -1 && retry) {\n return openHttpResult(urlPath, false);\n }\n AQUtility.debug(\"response\", code);\n if (code == -1 || code < 200 || code >= 300) {\n throw new IOException();\n }\n byte[] result = AQUtility.toBytes(connection.getInputStream());\n return result;\n }\n", "func2": " @Test\n public void test_blueprintTypeByTypeID() throws Exception {\n URL url = new URL(baseUrl + \"/blueprintTypeByTypeID/20188\");\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Accept\", \"application/json\");\n assertThat(connection.getResponseCode(), equalTo(200));\n assertThat(getResponse(connection), equalTo(\"{\\\"blueprintTypeID\\\":20188,\\\"blueprintTypeName\\\":\\\"Obelisk Blueprint\\\",\\\"productTypeID\\\":20187,\\\"productTypeName\\\":\\\"Obelisk\\\",\\\"productCategoryID\\\":6,\\\"techLevel\\\":1,\\\"productionTime\\\":1280000,\\\"researchProductivityTime\\\":7680000,\\\"researchMaterialTime\\\":5120000,\\\"researchCopyTime\\\":2560000,\\\"researchTechTime\\\":500000,\\\"productivityModifier\\\":256000,\\\"wasteFactor\\\":10,\\\"maxProductionLimit\\\":1,\\\"productVolume\\\":\\\"17550000\\\",\\\"productPortionSize\\\":1,\\\"dumpVersion\\\":\\\"cru16\\\"}\"));\n assertThat(connection.getHeaderField(\"Content-Type\"), equalTo(\"application/json; charset=utf-8\"));\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Accept\", \"application/xml\");\n assertThat(connection.getResponseCode(), equalTo(200));\n assertThat(getResponse(connection), equalTo(\"20188Obelisk Blueprintcru1616120187Obelisk175500001280000256000256000051200007680000500000110\"));\n assertThat(connection.getHeaderField(\"Content-Type\"), equalTo(\"application/xml; charset=utf-8\"));\n }\n", "label": 0} {"func1": " private void doFinishLoadAttachment(long attachmentId) {\n if (attachmentId != mLoadAttachmentId) {\n return;\n }\n Attachment attachment = Attachment.restoreAttachmentWithId(MessageView.this, attachmentId);\n Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);\n Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(getContentResolver(), attachmentUri);\n if (mLoadAttachmentSave) {\n try {\n File file = createUniqueFile(Environment.getExternalStorageDirectory(), attachment.mFileName);\n InputStream in = getContentResolver().openInputStream(contentUri);\n OutputStream out = new FileOutputStream(file);\n IOUtils.copy(in, out);\n out.flush();\n out.close();\n in.close();\n Toast.makeText(MessageView.this, String.format(getString(R.string.message_view_status_attachment_saved), file.getName()), Toast.LENGTH_LONG).show();\n new MediaScannerNotifier(this, file, mHandler);\n } catch (IOException ioe) {\n Toast.makeText(MessageView.this, getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show();\n }\n } else {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(contentUri);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n startActivity(intent);\n } catch (ActivityNotFoundException e) {\n mHandler.attachmentViewError();\n }\n }\n }\n", "func2": " public int updateuser(User u) {\n int i = 0;\n Connection conn = null;\n PreparedStatement pm = null;\n try {\n conn = Pool.getConnection();\n conn.setAutoCommit(false);\n pm = conn.prepareStatement(\"update user set username=?,passwd=?,existstate=?,management=? where userid=?\");\n pm.setString(1, u.getUsername());\n pm.setString(2, u.getPasswd());\n pm.setInt(3, u.getExiststate());\n pm.setInt(4, u.getManagement());\n pm.setString(5, u.getUserid());\n i = pm.executeUpdate();\n conn.commit();\n Pool.close(pm);\n Pool.close(conn);\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n Pool.close(pm);\n Pool.close(conn);\n } finally {\n Pool.close(pm);\n Pool.close(conn);\n }\n return i;\n }\n", "label": 0} {"func1": " public void executeUpdateTransaction(List queries) throws SQLException {\n assert connection != null;\n boolean autoCommit = connection.getAutoCommit();\n connection.setAutoCommit(false);\n try {\n Iterator iterator = queries.iterator();\n while (iterator.hasNext()) {\n String query = (String) iterator.next();\n Statement statement = connection.createStatement();\n statement.executeUpdate(query);\n }\n connection.commit();\n connection.setAutoCommit(autoCommit);\n } catch (SQLException e) {\n connection.rollback();\n throw new SQLException(e.getMessage());\n }\n }\n", "func2": " private void unzip(File filename) throws ZipException, IOException {\n ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(filename)));\n ZipEntry entry = null;\n boolean first_entry = true;\n while ((entry = in.getNextEntry()) != null) {\n if (first_entry) {\n if (!entry.isDirectory()) {\n File subdir = new File(dir + File.separator + filename.getName().substring(0, filename.getName().length() - SUFFIX_ZIP.length()));\n if (!subdir.exists()) {\n subdir.mkdir();\n dir = subdir;\n }\n }\n first_entry = false;\n }\n if (entry.isDirectory()) {\n FileUtils.forceMkdir(new File(dir + File.separator + entry.getName()));\n } else {\n File outfile = new File(dir + File.separator + entry.getName());\n File outdir = new File(outfile.getAbsolutePath().substring(0, outfile.getAbsolutePath().length() - outfile.getName().length()));\n if (!outdir.exists()) FileUtils.forceMkdir(outdir);\n FileOutputStream fo = new FileOutputStream(outfile);\n BufferedOutputStream bos = new BufferedOutputStream(fo, BUFFER);\n int read;\n byte data[] = new byte[BUFFER];\n while ((read = in.read(data, 0, BUFFER)) != -1) {\n read_position++;\n bos.write(data, 0, read);\n }\n bos.flush();\n bos.close();\n }\n }\n in.close();\n }\n", "label": 0} {"func1": " private void download(String address, String localFileName) throws UrlNotFoundException, Exception {\n String ext = G_File.getExtensao(address);\n if (ext.equals(\"jsp\")) {\n throw new Exception(\"Erro ao baixar pagina JSP, tipo negado.\" + address);\n }\n File temp = new File(localFileName + \".tmp\");\n if (temp.exists()) temp.delete();\n OutputStream out = null;\n URLConnection conn = null;\n InputStream in = null;\n try {\n try {\n URL url = new URL(address);\n conn = url.openConnection();\n in = conn.getInputStream();\n } catch (FileNotFoundException e2) {\n throw new UrlNotFoundException();\n }\n out = new BufferedOutputStream(new FileOutputStream(temp));\n byte[] buffer = new byte[1024];\n int numRead;\n long numWritten = 0;\n while ((numRead = in.read(buffer)) != -1) {\n out.write(buffer, 0, numRead);\n numWritten += numRead;\n }\n } catch (UrlNotFoundException exception) {\n throw exception;\n } catch (Exception exception) {\n throw exception;\n } finally {\n try {\n if (in != null) {\n in.close();\n }\n if (out != null) {\n out.close();\n }\n } catch (IOException ioe) {\n }\n }\n File oldArq = new File(localFileName);\n if (oldArq.exists()) {\n oldArq.delete();\n }\n oldArq = null;\n File nomeFinal = new File(localFileName);\n temp.renameTo(nomeFinal);\n }\n", "func2": " public void testAutoCommit() throws Exception {\n Connection con = getConnectionOverrideProperties(new Properties());\n try {\n Statement stmt = con.createStatement();\n assertEquals(0, stmt.executeUpdate(\"create table #testAutoCommit (i int)\"));\n con.setAutoCommit(false);\n assertEquals(1, stmt.executeUpdate(\"insert into #testAutoCommit (i) values (0)\"));\n con.setAutoCommit(false);\n con.rollback();\n assertEquals(1, stmt.executeUpdate(\"insert into #testAutoCommit (i) values (1)\"));\n con.setAutoCommit(true);\n con.setAutoCommit(false);\n con.rollback();\n con.setAutoCommit(true);\n ResultSet rs = stmt.executeQuery(\"select i from #testAutoCommit\");\n assertTrue(rs.next());\n assertEquals(1, rs.getInt(1));\n assertFalse(rs.next());\n rs.close();\n stmt.close();\n } finally {\n con.close();\n }\n }\n", "label": 0} {"func1": " public static byte[] getJarEntry(String jarName, String entry, int port) {\n byte[] b = null;\n try {\n String codebase = System.getProperty(\"java.rmi.server.codebase\", InetAddress.getLocalHost().getHostName());\n String protocol = \"http://\";\n int x = codebase.indexOf(protocol) + protocol.length();\n String s2 = codebase.substring(x);\n int x2 = s2.indexOf('/');\n String downloadHost = s2.substring(0, x2);\n if (downloadHost.indexOf(':') == -1) {\n downloadHost += \":\" + port;\n }\n URL url = new URL(\"jar:http://\" + downloadHost + \"/\" + jarName + \"!/\" + entry);\n JarURLConnection jurl = (JarURLConnection) url.openConnection();\n JarEntry je = jurl.getJarEntry();\n InputStream is = jurl.getInputStream();\n BufferedInputStream bis = new BufferedInputStream(is);\n int size = (int) je.getSize();\n b = new byte[size];\n int rb = 0;\n int chunk = 0;\n while ((size - rb) > 0) {\n chunk = bis.read(b, rb, size - rb);\n if (chunk == -1) {\n break;\n }\n rb += chunk;\n }\n bis.close();\n is.close();\n bis = null;\n is = null;\n url = null;\n jurl = null;\n } catch (UnknownHostException e) {\n e.printStackTrace();\n return null;\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n return b;\n }\n", "func2": " KeyStore getKeyStore() throws JarSignerException {\n if (keyStore == null) {\n KeyStore store = null;\n if (providerName == null) {\n try {\n store = KeyStore.getInstance(this.storeType);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n }\n } else {\n try {\n store = KeyStore.getInstance(storeType, providerName);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n } catch (NoSuchProviderException e) {\n e.printStackTrace();\n }\n }\n if (storeURI == null) {\n throw new JarSignerException(\"Cannot load the keystore \" + \" error con el keystore\");\n }\n try {\n storeURI = storeURI.replace(File.separatorChar, '/');\n URL url = null;\n try {\n url = new URL(storeURI);\n } catch (java.net.MalformedURLException e) {\n url = new File(storeURI).toURI().toURL();\n }\n InputStream is = null;\n try {\n is = url.openStream();\n store.load(is, storePass);\n } finally {\n if (is != null) {\n is.close();\n }\n }\n } catch (Exception e) {\n throw new JarSignerException(\"Cannot load the keystore \" + storeURI, e);\n }\n keyStore = store;\n }\n return keyStore;\n }\n", "label": 0} {"func1": " @Test\n public void test01_ok_failed_500_no_logo() throws Exception {\n DefaultHttpClient client = new DefaultHttpClient();\n try {\n HttpPost post = new HttpPost(xlsURL);\n HttpResponse response = client.execute(post);\n assertEquals(\"failed code for \", 500, response.getStatusLine().getStatusCode());\n } finally {\n client.getConnectionManager().shutdown();\n }\n }\n", "func2": " public String uploadFile(String url, int port, String uname, String upass, InputStream input) {\n String serverPath = config.getServerPath() + DateUtil.getSysmonth();\n FTPClient ftp = new FTPClient();\n try {\n int replyCode;\n ftp.connect(url, port);\n ftp.login(uname, upass);\n replyCode = ftp.getReplyCode();\n if (!FTPReply.isPositiveCompletion(replyCode)) {\n ftp.disconnect();\n return config.getServerPath();\n }\n if (!ftp.changeWorkingDirectory(serverPath)) {\n ftp.makeDirectory(DateUtil.getSysmonth());\n ftp.changeWorkingDirectory(serverPath);\n }\n ftp.storeFile(getFileName(), input);\n input.close();\n ftp.logout();\n } catch (Exception e) {\n e.printStackTrace();\n }\n return serverPath;\n }\n", "label": 0} {"func1": " public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {\n URLConnection connection = url.openConnection();\n connection.setConnectTimeout(timeout);\n connection.setReadTimeout(timeout);\n BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());\n return loadXml(buffInputStream, xmlType);\n }\n", "func2": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n log.error(\"Failed to load the MD5 MessageDigest. \" + \"Jive will be unable to function normally.\", nsae);\n }\n }\n try {\n digest.update(data.getBytes(\"utf-8\"));\n } catch (UnsupportedEncodingException e) {\n log.error(e);\n }\n return encodeHex(digest.digest());\n }\n", "label": 0} {"func1": " protected Control createDialogArea(Composite parent) {\n Composite composite = (Composite) super.createDialogArea(parent);\n setTitle(DialogsMessages.getString(\"LicenseDialog.Caption\"));\n setMessage(DialogsMessages.getString(\"LicenseDialog.Explanation\"));\n Composite content = new Composite(composite, SWT.NONE);\n content.setLayoutData(new GridData(GridData.FILL_BOTH));\n final int ncol = 1;\n GridLayout layout = new GridLayout(1, false);\n layout.numColumns = ncol;\n content.setLayout(layout);\n Browser browser = null;\n Text text = null;\n try {\n browser = new Browser(content, SWT.NONE);\n browser.setLayoutData(new GridData(GridData.FILL_BOTH));\n } catch (Throwable t) {\n text = new Text(content, SWT.MULTI | SWT.WRAP | SWT.VERTICAL);\n text.setLayoutData(new GridData(GridData.FILL_BOTH));\n }\n URL url = PalobrowserPlugin.getDefault().getBundle().getResource(browser != null ? \"license.html\" : \"license.txt\");\n InputStream in = null;\n BufferedReader r = null;\n StringBuffer sb = new StringBuffer();\n try {\n in = url.openStream();\n r = new BufferedReader(new InputStreamReader(in, \"ISO-8859-1\"));\n String line;\n while ((line = r.readLine()) != null) sb.append(line).append(\"\\r\\n\");\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (r != null) {\n try {\n r.close();\n } catch (IOException e) {\n }\n }\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n }\n }\n }\n if (browser != null) browser.setText(sb.toString()); else text.setText(sb.toString());\n return composite;\n }\n", "func2": " public static void main(String args[]) {\n int temp;\n int[] a1 = { 6, 2, -3, 7, -1, 8, 9, 0 };\n for (int j = 0; j < (a1.length * a1.length); j++) {\n for (int i = 0; i < a1.length - 1; i++) {\n if (a1[i] > a1[i + 1]) {\n temp = a1[i];\n a1[i] = a1[i + 1];\n a1[i + 1] = temp;\n }\n }\n }\n for (int i = 0; i < a1.length; i++) {\n System.out.print(\" \" + a1[i]);\n }\n }\n", "label": 0} {"func1": " public static String getUniqueKey() {\n String digest = \"\";\n try {\n final MessageDigest md = MessageDigest.getInstance(\"MD5\");\n final String timeVal = \"\" + (System.currentTimeMillis() + 1);\n String localHost = \"\";\n try {\n localHost = InetAddress.getLocalHost().toString();\n } catch (UnknownHostException e) {\n println(\"Warn: getUniqueKey(), Error trying to get localhost\" + e.getMessage());\n }\n final String randVal = \"\" + new Random().nextInt();\n final String val = timeVal + localHost + randVal;\n md.reset();\n md.update(val.getBytes());\n digest = toHexString(md.digest());\n } catch (NoSuchAlgorithmException e) {\n println(\"Warn: getUniqueKey() \" + e);\n }\n return digest;\n }\n", "func2": " KeyStore getKeyStore() throws JarSignerException {\n if (keyStore == null) {\n KeyStore store = null;\n if (providerName == null) {\n try {\n store = KeyStore.getInstance(this.storeType);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n }\n } else {\n try {\n store = KeyStore.getInstance(storeType, providerName);\n } catch (KeyStoreException e) {\n e.printStackTrace();\n } catch (NoSuchProviderException e) {\n e.printStackTrace();\n }\n }\n if (storeURI == null) {\n throw new JarSignerException(\"Cannot load the keystore \" + \" error con el keystore\");\n }\n try {\n storeURI = storeURI.replace(File.separatorChar, '/');\n URL url = null;\n try {\n url = new URL(storeURI);\n } catch (java.net.MalformedURLException e) {\n url = new File(storeURI).toURI().toURL();\n }\n InputStream is = null;\n try {\n is = url.openStream();\n store.load(is, storePass);\n } finally {\n if (is != null) {\n is.close();\n }\n }\n } catch (Exception e) {\n throw new JarSignerException(\"Cannot load the keystore \" + storeURI, e);\n }\n keyStore = store;\n }\n return keyStore;\n }\n", "label": 0} {"func1": " @Override\n public void actionPerformed(ActionEvent e) {\n try {\n Pattern delim = Pattern.compile(\"[ ]\");\n BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(\"/home/lindenb/jeter.txt.gz\"))));\n String line = null;\n URL url = new URL(\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi\");\n URLConnection conn = url.openConnection();\n conn.setDoOutput(true);\n OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());\n wr.write(\"db=snp&retmode=xml\");\n while ((line = r.readLine()) != null) {\n String tokens[] = delim.split(line, 2);\n if (!tokens[0].startsWith(\"rs\")) continue;\n wr.write(\"&id=\" + tokens[0].substring(2).trim());\n }\n wr.flush();\n r.close();\n InputStream in = conn.getInputStream();\n IOUtils.copyTo(in, System.err);\n in.close();\n wr.close();\n } catch (IOException err) {\n err.printStackTrace();\n }\n }\n", "func2": " public static Model downloadModel(String url) {\n Model model = ModelFactory.createDefaultModel();\n try {\n URLConnection connection = new URL(url).openConnection();\n if (connection instanceof HttpURLConnection) {\n HttpURLConnection httpConnection = (HttpURLConnection) connection;\n httpConnection.setRequestProperty(\"Accept\", \"application/rdf+xml, */*;q=.1\");\n httpConnection.setRequestProperty(\"Accept-Language\", \"en\");\n }\n InputStream in = connection.getInputStream();\n model.read(in, url);\n in.close();\n return model;\n } catch (MalformedURLException e) {\n cat.debug(\"Unable to download model from \" + url, e);\n throw new RuntimeException(e);\n } catch (IOException e) {\n cat.debug(\"Unable to download model from \" + url, e);\n throw new RuntimeException(e);\n }\n }\n", "label": 0} {"func1": " protected int deleteBitstreamInfo(int id, Connection conn) {\n PreparedStatement stmt = null;\n int numDeleted = 0;\n try {\n stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO);\n stmt.setInt(1, id);\n numDeleted = stmt.executeUpdate();\n if (numDeleted > 1) {\n conn.rollback();\n throw new IllegalStateException(\"Too many rows deleted! Number of rows deleted: \" + numDeleted + \" only one row should be deleted for bitstream id \" + id);\n }\n } catch (SQLException e) {\n LOG.error(\"Problem deleting bitstream. \" + e.getMessage(), e);\n throw new RuntimeException(\"Problem deleting bitstream. \" + e.getMessage(), e);\n } finally {\n cleanup(stmt);\n }\n return numDeleted;\n }\n", "func2": " public DocumentSummary parseDocument(URL url) throws IOException, DocumentHandlerException {\n InputStream inputStream = null;\n try {\n inputStream = url.openStream();\n POIOLE2TextExtractor extractor = createExtractor(inputStream);\n SummaryInformation info = extractor.getSummaryInformation();\n DocumentSummary docSummary = new DocumentSummary();\n docSummary.authors = DocSummaryPOIFSReaderListener.getAuthors(info);\n docSummary.contentReader = new StringReader(extractor.getText());\n docSummary.creationDate = info.getCreateDateTime();\n docSummary.keywords = new ArrayList();\n docSummary.keywords.add(info.getKeywords());\n docSummary.modificationDate = new Date(info.getEditTime());\n docSummary.title = info.getTitle();\n return docSummary;\n } catch (IOException e) {\n if (e.getMessage().startsWith(\"Unable to read entire header\")) {\n throw new DocumentHandlerException(\"Couldn't process document\", e);\n } else {\n throw e;\n }\n } finally {\n if (inputStream != null) {\n inputStream.close();\n }\n }\n }\n", "label": 0} {"func1": " public static String md5String(String str) {\n try {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] hash = md.digest();\n final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n StringBuffer res = new StringBuffer();\n for (int i = 0; i < hash.length; i++) {\n res.append(hexChars[(0xF0 & hash[i]) >> 4]);\n res.append(hexChars[0x0F & hash[i]]);\n }\n return res.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n }\n", "func2": " @Override\n public List search(String query, SortOrder order, int maxResults) throws Exception {\n if (query == null) {\n return null;\n }\n String encodedQuery = \"\";\n try {\n encodedQuery = URLEncoder.encode(query, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw e;\n }\n final int startAt = 0;\n final int pageNr = (startAt - 1) / 30;\n final String url = String.format(QUERYURL, encodedQuery, String.valueOf(pageNr), (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));\n HttpParams httpparams = new BasicHttpParams();\n HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);\n HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);\n DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);\n httpclient.getParams().setParameter(\"http.useragent\", \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2\");\n HttpGet httpget = new HttpGet(url);\n HttpResponse response = httpclient.execute(httpget);\n InputStream instream = response.getEntity().getContent();\n String html = HttpHelper.ConvertStreamToString(instream);\n instream.close();\n return parseHtml(html);\n }\n", "label": 0} {"func1": " @Override\n public void writeData(byte[] data, byte[] options, boolean transferMetaData) throws Throwable {\n long startTime = System.currentTimeMillis();\n long transferredBytesNum = 0;\n long elapsedTime = 0;\n Properties opts = PropertiesUtils.deserializeProperties(options);\n String server = opts.getProperty(TRANSFER_OPTION_SERVER);\n String username = opts.getProperty(TRANSFER_OPTION_USERNAME);\n String password = opts.getProperty(TRANSFER_OPTION_PASSWORD);\n String filePath = opts.getProperty(TRANSFER_OPTION_FILEPATH);\n if (transferMetaData) {\n int idx = filePath.lastIndexOf(PATH_SEPARATOR);\n if (idx != -1) {\n String fileName = filePath.substring(idx + 1) + META_DATA_FILE_SUFIX;\n filePath = filePath.substring(0, idx);\n filePath = filePath + PATH_SEPARATOR + fileName;\n } else {\n filePath += META_DATA_FILE_SUFIX;\n }\n }\n URL url = new URL(PROTOCOL_PREFIX + username + \":\" + password + \"@\" + server + filePath + \";type=i\");\n URLConnection urlc = url.openConnection(BackEnd.getProxy(Proxy.Type.SOCKS));\n urlc.setConnectTimeout(Preferences.getInstance().preferredTimeOut * 1000);\n urlc.setReadTimeout(Preferences.getInstance().preferredTimeOut * 1000);\n OutputStream os = urlc.getOutputStream();\n ByteArrayInputStream bis = new ByteArrayInputStream(data);\n byte[] buffer = new byte[1024];\n int br;\n while ((br = bis.read(buffer)) > 0) {\n os.write(buffer, 0, br);\n if (!transferMetaData) {\n transferredBytesNum += br;\n elapsedTime = System.currentTimeMillis() - startTime;\n fireOnProgressEvent(transferredBytesNum, elapsedTime);\n }\n }\n bis.close();\n os.close();\n }\n", "func2": " public Set getAvailableRoles() {\n if (availableRoles == null) {\n availableRoles = new HashSet();\n try {\n Enumeration resources = org.springframework.util.ClassUtils.getDefaultClassLoader().getResources(ROLE_FILE_LOCATION);\n while (resources.hasMoreElements()) {\n URL url = resources.nextElement();\n InputStream is = null;\n try {\n URLConnection con = url.openConnection();\n con.setUseCaches(false);\n is = con.getInputStream();\n List lines = IOUtils.readLines(is, \"ISO-8859-1\");\n if (lines != null) {\n for (String line : lines) {\n availableRoles.add(line.trim());\n }\n }\n } finally {\n if (is != null) {\n is.close();\n }\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n return availableRoles;\n }\n", "label": 0} {"func1": " public static void main(String[] args) throws FileNotFoundException {\n if (args.length < 2) throw new IllegalArgumentException();\n String fnOut = args[args.length - 1];\n PrintWriter writer = new PrintWriter(fnOut);\n for (int i = 0; i < args.length - 1; i++) {\n File fInput = new File(args[i]);\n Scanner in = new Scanner(fInput);\n while (in.hasNext()) {\n writer.println(in.nextLine());\n }\n }\n writer.close();\n }\n", "func2": " public static void main(String[] args) {\n try {\n URL url = new URL(args[0]);\n HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();\n httpCon.setDoOutput(true);\n httpCon.setRequestMethod(\"PUT\");\n OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());\n out.write(\"fatal error\");\n out.close();\n System.out.println(\"end\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " public void exportNotesToServer() {\n boolean uploaded = true;\n try {\n File f = new File(UserSettings.getInstance().getNotesFile());\n FileInputStream fis = new FileInputStream(f);\n String urlString = protocol + \"://\" + UserSettings.getInstance().getServerAddress() + UserSettings.getInstance().getServerDir() + f.getName();\n setDefaultAuthenticator();\n URL url = new URL(urlString);\n HttpURLConnection urlc = (HttpURLConnection) url.openConnection();\n urlc.setDoOutput(true);\n urlc.setRequestMethod(\"PUT\");\n OutputStream os = urlc.getOutputStream();\n int nextByte = fis.read();\n while (nextByte != -1) {\n os.write(nextByte);\n nextByte = fis.read();\n }\n fis.close();\n os.close();\n if (urlc.getResponseCode() != HttpURLConnection.HTTP_CREATED && urlc.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT) {\n uploaded = false;\n }\n } catch (SSLHandshakeException e) {\n JOptionPane.showMessageDialog(null, I18N.getInstance().getString(\"error.sslcertificateerror\"), I18N.getInstance().getString(\"error.title\"), JOptionPane.ERROR_MESSAGE);\n uploaded = false;\n } catch (Exception e) {\n uploaded = false;\n }\n if (uploaded) {\n JOptionPane.showMessageDialog(null, I18N.getInstance().getString(\"info.notesfileuploaded\"), I18N.getInstance().getString(\"info.title\"), JOptionPane.INFORMATION_MESSAGE);\n } else {\n JOptionPane.showMessageDialog(null, I18N.getInstance().getString(\"error.notesfilenotuploaded\"), I18N.getInstance().getString(\"error.title\"), JOptionPane.ERROR_MESSAGE);\n }\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 0} {"func1": " private static String encrypt(String algorithm, String password, Long digestSeed) {\n try {\n MessageDigest digest = MessageDigest.getInstance(algorithm);\n digest.reset();\n digest.update(password.getBytes(\"UTF-8\"));\n digest.update(digestSeed.toString().getBytes(\"UTF-8\"));\n byte[] messageDigest = digest.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4));\n hexString.append(Integer.toHexString(0x0f & messageDigest[i]));\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n } catch (NullPointerException e) {\n return new StringBuffer().toString();\n }\n }\n", "func2": " public static void main(String[] args) {\n String logFileName = args[0];\n int extractLineEvery = new Integer(args[1]).intValue();\n String filterToken = \"P0\";\n if (args.length > 2) {\n filterToken = args[2];\n }\n try {\n BufferedReader br = new BufferedReader(new FileReader(logFileName));\n BufferedWriter bw = new BufferedWriter(new FileWriter(new File(logFileName + \".trim\")));\n String readLine;\n int x = 0;\n while ((readLine = br.readLine()) != null) {\n if ((x++ % extractLineEvery == 0) && readLine.startsWith(filterToken)) {\n bw.write(readLine + \"\\n\");\n }\n }\n bw.flush();\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n", "label": 0} {"func1": " static HttpURLConnection connect(String url, String method, String contentType, String content, int timeoutMillis) throws ProtocolException, IOException, MalformedURLException, UnsupportedEncodingException {\n HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());\n conn.setRequestMethod(method);\n conn.setConnectTimeout(timeoutMillis);\n byte[] bContent = null;\n if (content != null && content.length() > 0) {\n conn.setDoOutput(true);\n conn.setRequestProperty(\"Content-Type\", contentType);\n bContent = content.getBytes(\"UTF-8\");\n conn.setFixedLengthStreamingMode(bContent.length);\n }\n conn.connect();\n if (bContent != null) {\n OutputStream os = conn.getOutputStream();\n os.write(bContent);\n os.flush();\n os.close();\n }\n return conn;\n }\n", "func2": " public static String getMessageDigest(String[] inputs) {\n if (inputs.length == 0) return null;\n try {\n MessageDigest sha = MessageDigest.getInstance(\"SHA-1\");\n for (String input : inputs) sha.update(input.getBytes());\n byte[] hash = sha.digest();\n String CPass = \"\";\n int h = 0;\n String s = \"\";\n for (int i = 0; i < 20; i++) {\n h = hash[i];\n if (h < 0) h += 256;\n s = Integer.toHexString(h);\n if (s.length() < 2) CPass = CPass.concat(\"0\");\n CPass = CPass.concat(s);\n }\n CPass = CPass.toUpperCase();\n return CPass;\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(e.getMessage());\n }\n }\n", "label": 0} {"func1": " public List extractUrlList(String url) throws IOException, XPathExpressionException {\n LinkedList list = new LinkedList();\n HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();\n Tidy tidy = new Tidy();\n tidy.setErrout(new NullPrintWriter());\n Document doc = tidy.parseDOM(conn.getInputStream(), null);\n int len = conn.getContentLength();\n if (len <= 0) len = 32000;\n ByteArrayOutputStream bout = new ByteArrayOutputStream(len);\n PrintStream ps = new PrintStream(bout);\n tidy.pprint(doc, ps);\n ps.flush();\n String content = bout.toString();\n Pattern p = Pattern.compile(\"(http://[\\\\w\\\\\\\\\\\\./=&?;-]+)\");\n Matcher m = p.matcher(content);\n while (m.find()) {\n list.add(m.group());\n }\n return list;\n }\n", "func2": " public static void unzip(File file, ZipFile zipFile, File targetDirectory) throws BusinessException {\n LOG.info(\"Unzipping zip file '\" + file.getAbsolutePath() + \"' to directory '\" + targetDirectory.getAbsolutePath() + \"'.\");\n assert (file.exists() && file.isFile());\n if (targetDirectory.exists() == false) {\n LOG.debug(\"Creating target directory.\");\n if (targetDirectory.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + targetDirectory.getAbsolutePath() + \"'!\");\n }\n }\n ZipInputStream zipin = null;\n try {\n zipin = new ZipInputStream(new FileInputStream(file));\n ZipEntry entry = null;\n while ((entry = zipin.getNextEntry()) != null) {\n LOG.debug(\"Unzipping entry '\" + entry.getName() + \"'.\");\n if (entry.isDirectory()) {\n LOG.debug(\"Skipping directory.\");\n continue;\n }\n final File targetFile = new File(targetDirectory, entry.getName());\n final File parentTargetFile = targetFile.getParentFile();\n if (parentTargetFile.exists() == false) {\n LOG.debug(\"Creating directory '\" + parentTargetFile.getAbsolutePath() + \"'.\");\n if (parentTargetFile.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + parentTargetFile.getAbsolutePath() + \"'!\");\n }\n }\n InputStream input = null;\n FileOutputStream output = null;\n try {\n input = zipFile.getInputStream(entry);\n if (targetFile.createNewFile() == false) {\n throw new BusinessException(\"Could not create target file '\" + targetFile.getAbsolutePath() + \"'!\");\n }\n output = new FileOutputStream(targetFile);\n int readBytes = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n while ((readBytes = input.read(buffer, 0, buffer.length)) > 0) {\n output.write(buffer, 0, readBytes);\n }\n } finally {\n FileUtil.closeCloseable(input);\n FileUtil.closeCloseable(output);\n }\n }\n } catch (IOException e) {\n throw new BusinessException(\"Could not unzip file '\" + file.getAbsolutePath() + \"'!\", e);\n } finally {\n FileUtil.closeCloseable(zipin);\n }\n }\n", "label": 0} {"func1": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String version = null;\n String build = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".version\")) version = line.substring(8).trim(); else if (line.startsWith(\".build\")) build = line.substring(6).trim();\n }\n bin.close();\n if (version != null && build != null) {\n if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else {\n GUIUtilities.message(view, \"version-check\" + \".up-to-date\", new String[0]);\n }\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "func2": " public void testReadHelloWorldTxt() throws Exception {\n final InputStream helloWorldIS = this.getClass().getClassLoader().getResourceAsStream(BASE_DIR + \"/HelloWorld.txt\");\n FileUtils.forceMkdir(new File(this.testDir.getAbsolutePath() + \"/org/settings4j/contentresolver\"));\n final String helloWorldPath = this.testDir.getAbsolutePath() + \"/org/settings4j/contentresolver/HelloWorld.txt\";\n final FileOutputStream fileOutputStream = new FileOutputStream(new File(helloWorldPath));\n IOUtils.copy(helloWorldIS, fileOutputStream);\n IOUtils.closeQuietly(helloWorldIS);\n IOUtils.closeQuietly(fileOutputStream);\n LOG.info(\"helloWorldPath: \" + helloWorldPath);\n final FSContentResolver contentResolver = new FSContentResolver();\n contentResolver.setRootFolderPath(this.testDir.getAbsolutePath());\n byte[] content = contentResolver.getContent(\"org/settings4j/contentresolver/HelloWorld.txt\");\n assertNotNull(content);\n assertEquals(\"Hello World\", new String(content, \"UTF-8\"));\n content = contentResolver.getContent(\"file:org/settings4j/contentresolver/HelloWorld.txt\");\n assertNotNull(content);\n assertEquals(\"Hello World\", new String(content, \"UTF-8\"));\n content = contentResolver.getContent(\"file:/org/settings4j/contentresolver/HelloWorld.txt\");\n assertNotNull(content);\n assertEquals(\"Hello World\", new String(content, \"UTF-8\"));\n content = contentResolver.getContent(\"file:laksjdhalksdhfa\");\n assertNull(content);\n content = contentResolver.getContent(\"/org/settings4j/contentresolver/HelloWorld.txt\");\n assertNotNull(content);\n assertEquals(\"Hello World\", new String(content, \"UTF-8\"));\n }\n", "label": 0} {"func1": " protected void createSettingsIfNecessary() throws IOException {\n OutputStream out = null;\n try {\n final File fSettings = SettingsUtils.getSettingsFile();\n if (!fSettings.exists()) {\n fSettings.createNewFile();\n final Path src = new Path(\"mvn/settings.xml\");\n final InputStream in = FileLocator.openStream(getBundle(), src, false);\n out = new FileOutputStream(SettingsUtils.getSettings(), true);\n IOUtils.copy(in, out);\n } else {\n Logger.getLog().info(\"File settings.xml already exists at \" + fSettings);\n }\n } finally {\n if (out != null) {\n out.flush();\n out.close();\n }\n }\n }\n", "func2": " public static void testMapSource(MapSource mapSource, EastNorthCoordinate coordinate) {\n try {\n System.out.println(\"Testing \" + mapSource.toString());\n int zoom = mapSource.getMinZoom() + ((mapSource.getMaxZoom() - mapSource.getMinZoom()) / 2);\n MapSpace mapSpace = mapSource.getMapSpace();\n int tilex = mapSpace.cLonToX(coordinate.lon, zoom) / mapSpace.getTileSize();\n int tiley = mapSpace.cLatToY(coordinate.lat, zoom) / mapSpace.getTileSize();\n url = new URL(mapSource.getTileUrl(zoom, tilex, tiley));\n System.out.println(\"Sample url: \" + url);\n c = (HttpURLConnection) url.openConnection();\n System.out.println(\"Connecting...\");\n c.connect();\n System.out.println(\"Connection established - response HTTP \" + c.getResponseCode());\n if (c.getResponseCode() != 200) return;\n String contentType = c.getContentType();\n System.out.print(\"Image format : \");\n if (\"image/png\".equals(contentType)) System.out.println(\"png\"); else if (\"image/jpeg\".equals(contentType)) System.out.println(\"jpg\"); else System.out.println(\"unknown\");\n String eTag = c.getHeaderField(\"ETag\");\n boolean eTagSupported = (eTag != null);\n if (eTagSupported) {\n System.out.println(\"eTag : \" + eTag);\n testIfNoneMatch();\n } else System.out.println(\"eTag : -\");\n long date = c.getDate();\n if (date == 0) System.out.println(\"Date time : -\"); else System.out.println(\"Date time : \" + new Date(date));\n long exp = c.getExpiration();\n if (exp == 0) System.out.println(\"Expiration time : -\"); else System.out.println(\"Expiration time : \" + new Date(exp));\n long modified = c.getLastModified();\n if (modified == 0) System.out.println(\"Last modified time : not set\"); else System.out.println(\"Last modified time : \" + new Date(modified));\n testIfModified();\n } catch (Exception e) {\n e.printStackTrace();\n }\n System.out.println(\"\\n\");\n }\n", "label": 0} {"func1": " public void readFile(URL url) throws PedroException, IOException, ParserConfigurationException, SAXException {\n this.zipFileName = url.toString();\n URLConnection urlConnection = url.openConnection();\n InputStream inputStream = urlConnection.getInputStream();\n unzipNativeFormatFile(inputStream);\n parseAlertFiles();\n deleteAlertFiles();\n }\n", "func2": " public void testHttpsConnection_Not_Found_Response() throws Throwable {\n setUpStoreProperties();\n try {\n SSLContext ctx = getContext();\n ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);\n TestHostnameVerifier hnv = new TestHostnameVerifier();\n HttpsURLConnection.setDefaultHostnameVerifier(hnv);\n URL url = new URL(\"https://localhost:\" + ss.getLocalPort());\n HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\n try {\n doInteraction(connection, ss, NOT_FOUND_CODE);\n fail(\"Expected exception was not thrown.\");\n } catch (FileNotFoundException e) {\n if (DO_LOG) {\n System.out.println(\"Expected exception was thrown: \" + e.getMessage());\n }\n }\n connection.connect();\n } finally {\n tearDownStoreProperties();\n }\n }\n", "label": 0} {"func1": " private static void setMembers() {\n try {\n URL url = new URL(getTracUrl() + \"newticket\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n String buffer = reader.readLine();\n while (buffer != null) {\n if (buffer.contains(\"\")) {\n Pattern pattern = Pattern.compile(\">[^<]+?<\");\n Matcher matcher = pattern.matcher(buffer);\n Vector erg = new Vector();\n int start = 0;\n while (matcher.find(start)) {\n int von = matcher.start() + 1;\n int bis = matcher.end() - 1;\n erg.add(Recoder.recode(buffer.substring(von, bis), \"UTF-8\", Recoder.getDefaultEncoding()));\n start = bis;\n }\n m_strPriorities = new String[erg.size()];\n erg.toArray(m_strPriorities);\n }\n buffer = reader.readLine();\n }\n } catch (MalformedURLException e) {\n System.out.println(\"e1\");\n } catch (IOException e) {\n System.out.println(e);\n }\n }\n", "func2": " public static void copyFile(File src, File dest) throws IOException {\n FileInputStream fis = new FileInputStream(src);\n FileOutputStream fos = new FileOutputStream(dest);\n java.nio.channels.FileChannel channelSrc = fis.getChannel();\n java.nio.channels.FileChannel channelDest = fos.getChannel();\n channelSrc.transferTo(0, channelSrc.size(), channelDest);\n fis.close();\n fos.close();\n }\n", "label": 0} {"func1": " public boolean import_hints(String filename) {\n int pieceId;\n int i, col, row;\n int rotation;\n int number;\n boolean byurl = true;\n e2piece temppiece;\n String lineread;\n StringTokenizer tok;\n BufferedReader entree;\n try {\n if (byurl == true) {\n URL url = new URL(baseURL, filename);\n InputStream in = url.openStream();\n entree = new BufferedReader(new InputStreamReader(in));\n } else {\n entree = new BufferedReader(new FileReader(filename));\n }\n pieceId = 0;\n lineread = entree.readLine();\n tok = new StringTokenizer(lineread, \" \");\n number = Integer.parseInt(tok.nextToken());\n for (i = 0; i < number; i++) {\n lineread = entree.readLine();\n if (lineread == null) {\n break;\n }\n tok = new StringTokenizer(lineread, \" \");\n pieceId = Integer.parseInt(tok.nextToken());\n col = Integer.parseInt(tok.nextToken()) - 1;\n row = Integer.parseInt(tok.nextToken()) - 1;\n rotation = Integer.parseInt(tok.nextToken());\n System.out.println(\"placing hint piece : \" + pieceId);\n place_piece_at(pieceId, col, row, 0);\n temppiece = board.get_piece_at(col, row);\n temppiece.reset_rotation();\n temppiece.rotate(rotation);\n temppiece.set_as_hint();\n }\n return true;\n } catch (IOException err) {\n return false;\n }\n }\n", "func2": " public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"SHA-1\");\n byte[] sha1hash = new byte[40];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n sha1hash = md.digest();\n return convertToHex(sha1hash);\n }\n", "label": 0} {"func1": " private static boolean copyFile(File in, File out) {\n boolean ok = true;\n InputStream is = null;\n OutputStream os = null;\n try {\n is = new FileInputStream(in);\n os = new FileOutputStream(out);\n byte[] buffer = new byte[0xFFFF];\n for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len);\n } catch (IOException e) {\n System.err.println(e);\n ok = false;\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n System.err.println(e);\n }\n }\n if (os != null) {\n try {\n os.close();\n } catch (IOException e) {\n System.err.println(e);\n }\n }\n }\n return ok;\n }\n", "func2": " public static synchronized String getMD5_Base64(String input) {\n MessageDigest msgDigest = null;\n try {\n msgDigest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(\"System doesn't support MD5 algorithm.\");\n }\n try {\n msgDigest.update(input.getBytes(\"UTF-8\"));\n } catch (java.io.UnsupportedEncodingException ex) {\n throw new IllegalStateException(\"System doesn't support your EncodingException.\");\n }\n byte[] rawData = msgDigest.digest();\n byte[] encoded = Base64.encode(rawData);\n String retValue = new String(encoded);\n return retValue;\n }\n", "label": 0} {"func1": " private void loadBinaryStream(String streamName, InputStream streamToLoad, long sz, HttpServletRequest req, HttpServletResponse resp) throws IOException {\n resp.setContentType(getContentType(req, streamName));\n resp.setHeader(\"Content-Disposition\", \"inline;filename=\" + streamName);\n resp.setContentLength((int) sz);\n OutputStream out = resp.getOutputStream();\n BufferedOutputStream bos = new BufferedOutputStream(out, 2048);\n try {\n IOUtils.copy(streamToLoad, bos);\n } finally {\n IOUtils.closeQuietly(streamToLoad);\n IOUtils.closeQuietly(bos);\n }\n getCargo().put(GWT_ENTRY_POINT_PAGE_PARAM, null);\n }\n", "func2": " private static void setMembers() {\n try {\n URL url = new URL(getTracUrl() + \"newticket\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n String buffer = reader.readLine();\n while (buffer != null) {\n if (buffer.contains(\"\")) {\n Pattern pattern = Pattern.compile(\">[^<]+?<\");\n Matcher matcher = pattern.matcher(buffer);\n Vector erg = new Vector();\n int start = 0;\n while (matcher.find(start)) {\n int von = matcher.start() + 1;\n int bis = matcher.end() - 1;\n erg.add(Recoder.recode(buffer.substring(von, bis), \"UTF-8\", Recoder.getDefaultEncoding()));\n start = bis;\n }\n m_strPriorities = new String[erg.size()];\n erg.toArray(m_strPriorities);\n }\n buffer = reader.readLine();\n }\n } catch (MalformedURLException e) {\n System.out.println(\"e1\");\n } catch (IOException e) {\n System.out.println(e);\n }\n }\n", "label": 0} {"func1": " public static boolean existsURL(String urlStr) {\n try {\n URL url = ProxyURLFactory.createHttpUrl(urlStr);\n HttpURLConnection con = (HttpURLConnection) url.openConnection();\n con.connect();\n int responseCode = con.getResponseCode();\n con.disconnect();\n return !(responseCode == HttpURLConnection.HTTP_NOT_FOUND);\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n }\n", "func2": " public String md5(String plainText) throws NoSuchAlgorithmException {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(plainText.getBytes());\n byte[] digest = md.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < digest.length; i++) {\n plainText = Integer.toHexString(0xFF & digest[i]);\n if (plainText.length() < 2) {\n plainText = \"0\" + plainText;\n }\n hexString.append(plainText);\n }\n return hexString.toString();\n }\n", "label": 0} {"func1": " private void downloadFile(File target, String s3key) throws IOException, S3ServiceException {\n InputStream in = downloadData(s3key);\n if (in == null) {\n throw new IOException(\"No data found\");\n }\n in = new InflaterInputStream(new CryptInputStream(in, cipher, getDataEncryptionKey()));\n File temp = File.createTempFile(\"dirsync\", null);\n FileOutputStream fout = new FileOutputStream(temp);\n try {\n IOUtils.copy(in, fout);\n if (target.exists()) {\n target.delete();\n }\n IOUtils.closeQuietly(fout);\n IOUtils.closeQuietly(in);\n FileUtils.moveFile(temp, target);\n } catch (IOException e) {\n fetchStream(in);\n throw e;\n } finally {\n IOUtils.closeQuietly(fout);\n IOUtils.closeQuietly(in);\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) throws Exception {\n if (args.length != 2) {\n System.out.println(\"usage: \" + EvaluatorHelper.class.getName() + \" \");\n System.exit(1);\n }\n Helper helper = Helper.getHelper(args[1]);\n Dataset dataset = helper.read(args[1]);\n ZipFile zip = new ZipFile(new File(args[0]), ZipFile.OPEN_READ);\n Enumeration entries = zip.entries();\n Unit[] performance = new Unit[LIMIT];\n int index = 0;\n while (entries.hasMoreElements()) {\n ZipEntry entry = (ZipEntry) entries.nextElement();\n if (entry.getName().endsWith(\".out\")) {\n File temp = File.createTempFile(\"PARSER\", \".zip\");\n temp.deleteOnExit();\n PrintStream writer = new PrintStream(new FileOutputStream(temp));\n BufferedInputStream reader = new BufferedInputStream(zip.getInputStream(entry));\n byte[] buffer = new byte[4096];\n int read = -1;\n while ((read = reader.read(buffer)) != -1) {\n writer.write(buffer, 0, read);\n }\n writer.close();\n reader.close();\n BufferedReader outfile = new BufferedReader(new FileReader(temp));\n String line = null;\n RuleParser parser = new RuleParser();\n ProbabilisticRuleList list = new ProbabilisticRuleList();\n while ((line = outfile.readLine()) != null) {\n if (line.startsWith(\"IF\")) {\n ProbabilisticRule rule = new ProbabilisticRule(dataset.getMetadata());\n list.add(fill(dataset.getMetadata(), rule, parser.parse(line)));\n }\n }\n outfile.close();\n PooledPRCurveMeasure measure = new PooledPRCurveMeasure();\n performance[index] = measure.evaluate(dataset, list);\n System.out.println(entry.getName() + \": \" + performance[index]);\n index++;\n if (index >= LIMIT) {\n break;\n }\n }\n }\n System.out.println(UnitAveragingMode.get(Double.class).average(performance));\n }\n", "func2": " public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException {\n FileChannel inputChannel = new FileInputStream(inputFile).getChannel();\n FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();\n try {\n inputChannel.transferTo(0, inputChannel.size(), outputChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inputChannel != null) inputChannel.close();\n if (outputChannel != null) outputChannel.close();\n }\n }\n", "label": 1} {"func1": " public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {\n String name = metadata.get(Metadata.RESOURCE_NAME_KEY);\n if (name != null && wanted.containsKey(name)) {\n FileOutputStream out = new FileOutputStream(wanted.get(name));\n IOUtils.copy(stream, out);\n out.close();\n } else {\n if (downstreamParser != null) {\n downstreamParser.parse(stream, handler, metadata, context);\n }\n }\n }\n", "func2": " public static void fileCopy(String from_name, String to_name) throws IOException {\n File fromFile = new File(from_name);\n File toFile = new File(to_name);\n if (fromFile.equals(toFile)) abort(\"cannot copy on itself: \" + from_name);\n if (!fromFile.exists()) abort(\"no such currentSourcepartName file: \" + from_name);\n if (!fromFile.isFile()) abort(\"can't copy directory: \" + from_name);\n if (!fromFile.canRead()) abort(\"currentSourcepartName file is unreadable: \" + from_name);\n if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());\n if (toFile.exists()) {\n if (!toFile.canWrite()) abort(\"destination file is unwriteable: \" + to_name);\n } else {\n String parent = toFile.getParent();\n if (parent == null) abort(\"destination directory doesn't exist: \" + parent);\n File dir = new File(parent);\n if (!dir.exists()) abort(\"destination directory doesn't exist: \" + parent);\n if (dir.isFile()) abort(\"destination is not a directory: \" + parent);\n if (!dir.canWrite()) abort(\"destination directory is unwriteable: \" + parent);\n }\n FileInputStream from = null;\n FileOutputStream to = null;\n try {\n from = new FileInputStream(fromFile);\n to = new FileOutputStream(toFile);\n byte[] buffer = new byte[4096];\n int bytes_read;\n while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read);\n } finally {\n if (from != null) try {\n from.close();\n } catch (IOException e) {\n ;\n }\n if (to != null) try {\n to.close();\n } catch (IOException e) {\n ;\n }\n }\n }\n", "label": 1} {"func1": " private void copyFileTo(File destination) throws IOException {\n logger.fine(\"Copying from \" + destination + \"...\");\n FileChannel srcChannel = new FileInputStream(getAbsolutePath()).getChannel();\n logger.fine(\"...got source channel \" + srcChannel + \"...\");\n FileChannel destChannel = new FileOutputStream(new File(destination.getAbsolutePath())).getChannel();\n logger.fine(\"...got destination channel \" + destChannel + \"...\");\n logger.fine(\"...Got channels...\");\n destChannel.transferFrom(srcChannel, 0, srcChannel.size());\n logger.fine(\"...transferred.\");\n srcChannel.close();\n destChannel.close();\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public void serialize(OutputStream out) throws IOException, BadIMSCPException {\n ensureParsed();\n ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser();\n parser.setContentPackage(cp);\n if (on_disk != null) on_disk.delete();\n on_disk = createTemporaryFile();\n parser.serialize(on_disk);\n InputStream in = new FileInputStream(on_disk);\n IOUtils.copy(in, out);\n }\n", "func2": " public static void main(String[] args) throws Exception {\n String linesep = System.getProperty(\"line.separator\");\n FileOutputStream fos = new FileOutputStream(new File(\"lib-licenses.txt\"));\n fos.write(new String(\"JCP contains the following libraries. Please read this for comments on copyright etc.\" + linesep + linesep).getBytes());\n fos.write(new String(\"Chemistry Development Kit, master version as of \" + new Date().toString() + \" (http://cdk.sf.net)\" + linesep).getBytes());\n fos.write(new String(\"Copyright 1997-2009 The CDK Development Team\" + linesep).getBytes());\n fos.write(new String(\"License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)\" + linesep).getBytes());\n fos.write(new String(\"Download: https://sourceforge.net/projects/cdk/files/\" + linesep).getBytes());\n fos.write(new String(\"Source available at: http://sourceforge.net/scm/?type=git&group_id=20024\" + linesep + linesep).getBytes());\n File[] files = new File(args[0]).listFiles(new JarFileFilter());\n for (int i = 0; i < files.length; i++) {\n if (new File(files[i].getPath() + \".meta\").exists()) {\n Map> metaprops = readProperties(new File(files[i].getPath() + \".meta\"));\n Iterator itsect = metaprops.keySet().iterator();\n while (itsect.hasNext()) {\n String section = itsect.next();\n fos.write(new String(metaprops.get(section).get(\"Library\") + \" \" + metaprops.get(section).get(\"Version\") + \" (\" + metaprops.get(section).get(\"Homepage\") + \")\" + linesep).getBytes());\n fos.write(new String(\"Copyright \" + metaprops.get(section).get(\"Copyright\") + linesep).getBytes());\n fos.write(new String(\"License: \" + metaprops.get(section).get(\"License\") + \" (\" + metaprops.get(section).get(\"LicenseURL\") + \")\" + linesep).getBytes());\n fos.write(new String(\"Download: \" + metaprops.get(section).get(\"Download\") + linesep).getBytes());\n fos.write(new String(\"Source available at: \" + metaprops.get(section).get(\"SourceCode\") + linesep + linesep).getBytes());\n }\n }\n if (new File(files[i].getPath() + \".extra\").exists()) {\n fos.write(new String(\"The author says:\" + linesep).getBytes());\n FileInputStream in = new FileInputStream(new File(files[i].getPath() + \".extra\"));\n int len;\n byte[] buf = new byte[1024];\n while ((len = in.read(buf)) > 0) {\n fos.write(buf, 0, len);\n }\n }\n fos.write(linesep.getBytes());\n }\n fos.close();\n }\n", "label": 1} {"func1": " public static void unzipModel(String filename, String tempdir) throws EDITSException {\n try {\n BufferedOutputStream dest = null;\n FileInputStream fis = new FileInputStream(filename);\n int BUFFER = 2048;\n ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));\n ZipEntry entry;\n while ((entry = zis.getNextEntry()) != null) {\n int count;\n byte data[] = new byte[BUFFER];\n FileOutputStream fos = new FileOutputStream(tempdir + entry.getName());\n dest = new BufferedOutputStream(fos, BUFFER);\n while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count);\n dest.flush();\n dest.close();\n }\n zis.close();\n } catch (Exception e) {\n throw new EDITSException(\"Can not expand model in \\\"\" + tempdir + \"\\\" because:\\n\" + e.getMessage());\n }\n }\n", "func2": " private void copyFile(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "label": 1} {"func1": " public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "func2": " public static synchronized String getMD5_Base64(String input) {\n MessageDigest msgDigest = null;\n try {\n msgDigest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(\"System doesn't support MD5 algorithm.\");\n }\n try {\n msgDigest.update(input.getBytes(\"UTF-8\"));\n } catch (java.io.UnsupportedEncodingException ex) {\n throw new IllegalStateException(\"System doesn't support your EncodingException.\");\n }\n byte[] rawData = msgDigest.digest();\n byte[] encoded = Base64.encode(rawData);\n String retValue = new String(encoded);\n return retValue;\n }\n", "label": 1} {"func1": " public static Body decodeBody(InputStream in, String contentTransferEncoding) throws IOException {\n if (contentTransferEncoding != null) {\n contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null);\n if (\"quoted-printable\".equalsIgnoreCase(contentTransferEncoding)) {\n in = new QuotedPrintableInputStream(in);\n } else if (\"base64\".equalsIgnoreCase(contentTransferEncoding)) {\n in = new Base64InputStream(in);\n }\n }\n BinaryTempFileBody tempBody = new BinaryTempFileBody();\n OutputStream out = tempBody.getOutputStream();\n IOUtils.copy(in, out);\n out.close();\n return tempBody;\n }\n", "func2": " public static void main(String[] args) {\n String logFileName = args[0];\n int extractLineEvery = new Integer(args[1]).intValue();\n String filterToken = \"P0\";\n if (args.length > 2) {\n filterToken = args[2];\n }\n try {\n BufferedReader br = new BufferedReader(new FileReader(logFileName));\n BufferedWriter bw = new BufferedWriter(new FileWriter(new File(logFileName + \".trim\")));\n String readLine;\n int x = 0;\n while ((readLine = br.readLine()) != null) {\n if ((x++ % extractLineEvery == 0) && readLine.startsWith(filterToken)) {\n bw.write(readLine + \"\\n\");\n }\n }\n bw.flush();\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n", "label": 1} {"func1": " @Override\n public String transformSingleFile(X3DEditorSupport.X3dEditor xed) {\n Node[] node = xed.getActivatedNodes();\n X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject();\n FileObject mySrc = dob.getPrimaryFile();\n File mySrcF = FileUtil.toFile(mySrc);\n File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + \".x3dv.gz\");\n TransformListener co = TransformListener.getInstance();\n co.message(NbBundle.getMessage(getClass(), \"Gzip_compression_starting\"));\n co.message(NbBundle.getMessage(getClass(), \"Saving_as_\") + myOutF.getAbsolutePath());\n co.moveToFront();\n co.setNode(node[0]);\n try {\n String x3dvFile = ExportClassicVRMLAction.instance.transformSingleFile(xed);\n FileInputStream fis = new FileInputStream(new File(x3dvFile));\n GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF));\n byte[] buf = new byte[4096];\n int ret;\n while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret);\n gzos.close();\n } catch (Exception ex) {\n co.message(NbBundle.getMessage(getClass(), \"Exception:__\") + ex.getLocalizedMessage());\n return null;\n }\n co.message(NbBundle.getMessage(getClass(), \"Gzip_compression_complete\"));\n return myOutF.getAbsolutePath();\n }\n", "func2": " private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {\n if (destFile.exists() && destFile.isDirectory()) {\n throw new IOException(\"Destination '\" + destFile + \"' exists but is a directory\");\n }\n FileChannel input = new FileInputStream(srcFile).getChannel();\n try {\n FileChannel output = new FileOutputStream(destFile).getChannel();\n try {\n output.transferFrom(input, 0, input.size());\n } finally {\n IOUtil.closeQuietly(output);\n }\n } finally {\n IOUtil.closeQuietly(input);\n }\n if (srcFile.length() != destFile.length()) {\n throw new IOException(\"Failed to copy full contents from '\" + srcFile + \"' to '\" + destFile + \"'\");\n }\n if (preserveFileDate) {\n destFile.setLastModified(srcFile.lastModified());\n }\n }\n", "label": 1} {"func1": " @Override\n public void trainClassifier(File dir, String... args) throws Exception {\n String[] command = new String[args.length + 3];\n command[0] = this.getCommand();\n System.arraycopy(args, 0, command, 1, args.length);\n command[command.length - 2] = new File(dir, \"training-data.libsvm\").getPath();\n command[command.length - 1] = new File(dir, this.getModelName()).getPath();\n Process process = Runtime.getRuntime().exec(command);\n IOUtils.copy(process.getInputStream(), System.out);\n IOUtils.copy(process.getErrorStream(), System.err);\n process.waitFor();\n }\n", "func2": " public static void copy(File from, File to) {\n boolean result;\n if (from.isDirectory()) {\n File[] subFiles = from.listFiles();\n for (int i = 0; i < subFiles.length; i++) {\n File newDir = new File(to, subFiles[i].getName());\n result = false;\n if (subFiles[i].isDirectory()) {\n if (newDir.exists()) result = true; else result = newDir.mkdirs();\n } else if (subFiles[i].isFile()) {\n try {\n result = newDir.createNewFile();\n } catch (IOException e) {\n log.error(\"unable to create new file: \" + newDir, e);\n result = false;\n }\n }\n if (result) copy(subFiles[i], newDir);\n }\n } else if (from.isFile()) {\n FileInputStream in = null;\n FileOutputStream out = null;\n try {\n in = new FileInputStream(from);\n out = new FileOutputStream(to);\n int fileLength = (int) from.length();\n char charBuff[] = new char[fileLength];\n int len;\n int oneChar;\n while ((oneChar = in.read()) != -1) {\n out.write(oneChar);\n }\n } catch (FileNotFoundException e) {\n log.error(\"File not found!\", e);\n } catch (IOException e) {\n log.error(\"Unable to read from file!\", e);\n } finally {\n try {\n if (in != null) in.close();\n if (out != null) out.close();\n } catch (IOException e1) {\n log.error(\"Error closing file reader/writer\", e1);\n }\n }\n }\n }\n", "label": 1} {"func1": " public void serialize(OutputStream out) throws IOException, BadIMSCPException {\n ensureParsed();\n ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser();\n parser.setContentPackage(cp);\n if (on_disk != null) on_disk.delete();\n on_disk = createTemporaryFile();\n parser.serialize(on_disk);\n InputStream in = new FileInputStream(on_disk);\n IOUtils.copy(in, out);\n }\n", "func2": " public static void CopyFile(String in, String out) throws Exception {\n FileChannel sourceChannel = new FileInputStream(new File(in)).getChannel();\n FileChannel destinationChannel = new FileOutputStream(new File(out)).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n }\n", "label": 1} {"func1": " private void handleNodeRegainedService(long eventID, long nodeID, String ipAddr, long serviceID, String eventTime) {\n Category log = ThreadCategory.getInstance(OutageWriter.class);\n if (eventID == -1 || nodeID == -1 || ipAddr == null || serviceID == -1) {\n log.warn(EventConstants.NODE_REGAINED_SERVICE_EVENT_UEI + \" ignored - info incomplete - eventid/nodeid/ip/svc: \" + eventID + \"/\" + nodeID + \"/\" + ipAddr + \"/\" + serviceID);\n return;\n }\n Connection dbConn = null;\n try {\n dbConn = DatabaseConnectionFactory.getInstance().getConnection();\n if (openOutageExists(dbConn, nodeID, ipAddr, serviceID)) {\n try {\n dbConn.setAutoCommit(false);\n } catch (SQLException sqle) {\n log.error(\"Unable to change database AutoCommit to FALSE\", sqle);\n return;\n }\n PreparedStatement outageUpdater = dbConn.prepareStatement(OutageConstants.DB_UPDATE_OUTAGE_FOR_SERVICE);\n outageUpdater.setLong(1, eventID);\n outageUpdater.setTimestamp(2, convertEventTimeIntoTimestamp(eventTime));\n outageUpdater.setLong(3, nodeID);\n outageUpdater.setString(4, ipAddr);\n outageUpdater.setLong(5, serviceID);\n outageUpdater.executeUpdate();\n outageUpdater.close();\n try {\n dbConn.commit();\n if (log.isDebugEnabled()) log.debug(\"nodeRegainedService: closed outage for nodeid/ip/service \" + nodeID + \"/\" + ipAddr + \"/\" + serviceID + \" in DB\");\n } catch (SQLException se) {\n log.warn(\"Rolling back transaction, nodeRegainedService could not be recorded for nodeId/ipAddr/service: \" + nodeID + \"/\" + ipAddr + \"/\" + serviceID, se);\n try {\n dbConn.rollback();\n } catch (SQLException sqle) {\n log.warn(\"SQL exception during rollback, reason\", sqle);\n }\n }\n } else {\n log.warn(\"\\'\" + EventConstants.NODE_REGAINED_SERVICE_EVENT_UEI + \"\\' for \" + nodeID + \"/\" + ipAddr + \"/\" + serviceID + \" does not have open record.\");\n }\n } catch (SQLException se) {\n log.warn(\"SQL exception while handling \\'nodeRegainedService\\'\", se);\n } finally {\n try {\n if (dbConn != null) dbConn.close();\n } catch (SQLException e) {\n log.warn(\"Exception closing JDBC connection\", e);\n }\n }\n }\n", "func2": " public static void addRecipe(String name, String instructions, int categoryId, String[][] ainekset) throws Exception {\n PreparedStatement pst1 = null;\n PreparedStatement pst2 = null;\n ResultSet rs = null;\n int retVal = -1;\n try {\n pst1 = conn.prepareStatement(\"INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)\");\n pst1.setString(1, name);\n pst1.setString(2, instructions);\n pst1.setInt(3, categoryId);\n if (pst1.executeUpdate() > 0) {\n pst2 = conn.prepareStatement(\"SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?\");\n pst2.setString(1, name);\n pst2.setString(2, instructions);\n pst2.setInt(3, categoryId);\n rs = pst2.executeQuery();\n if (rs.next()) {\n int id = rs.getInt(1);\n System.out.println(\"Lis�t��n ainesosat\");\n String[] aines;\n for (int i = 0; i < ainekset.length; ++i) {\n aines = ainekset[i];\n addIngredient(id, aines[0], aines[1], Integer.parseInt(aines[2]), Integer.parseInt(aines[3]));\n }\n retVal = id;\n } else {\n retVal = -1;\n }\n } else {\n retVal = -1;\n }\n conn.commit();\n } catch (Exception e) {\n conn.rollback();\n throw new Exception(\"Reseptin lis�ys ep�onnistui. Poikkeus: \" + e.getMessage());\n }\n }\n", "label": 1} {"func1": " private void copyParseFileToCodeFile() throws IOException {\n InputStream in = new FileInputStream(new File(filenameParse));\n OutputStream out = new FileOutputStream(new File(filenameMisc));\n byte[] buffer = new byte[1024];\n int length;\n while ((length = in.read(buffer)) > 0) out.write(buffer, 0, length);\n in.close();\n out.close();\n }\n", "func2": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 1} {"func1": " public static void main(String[] argv) {\n if (1 < argv.length) {\n File[] sources = Source(argv[0]);\n if (null != sources) {\n for (File src : sources) {\n File[] targets = Target(src, argv);\n if (null != targets) {\n final long srclen = src.length();\n try {\n FileChannel source = new FileInputStream(src).getChannel();\n try {\n for (File tgt : targets) {\n FileChannel target = new FileOutputStream(tgt).getChannel();\n try {\n source.transferTo(0L, srclen, target);\n } finally {\n target.close();\n }\n System.out.printf(\"Updated %s\\n\", tgt.getPath());\n File[] deletes = Delete(src, tgt);\n if (null != deletes) {\n for (File del : deletes) {\n if (SVN) {\n if (SvnDelete(del)) System.out.printf(\"Deleted %s\\n\", del.getPath()); else System.out.printf(\"Failed to delete %s\\n\", del.getPath());\n } else if (del.delete()) System.out.printf(\"Deleted %s\\n\", del.getPath()); else System.out.printf(\"Failed to delete %s\\n\", del.getPath());\n }\n }\n if (SVN) SvnAdd(tgt);\n }\n } finally {\n source.close();\n }\n } catch (Exception exc) {\n exc.printStackTrace();\n System.exit(1);\n }\n }\n }\n System.exit(0);\n } else {\n System.err.printf(\"Source file(s) not found in '%s'\\n\", argv[0]);\n System.exit(1);\n }\n } else {\n usage();\n System.exit(1);\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " protected String downloadURLtoString(URL url) throws IOException {\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n StringBuffer sb = new StringBuffer(100 * 1024);\n String str;\n while ((str = in.readLine()) != null) {\n sb.append(str);\n }\n in.close();\n return sb.toString();\n }\n", "func2": " @Override\n public void run() {\n try {\n BufferedReader in = new BufferedReader(new InputStreamReader(new URL(urlInfo).openStream()));\n String ligneEnCours;\n int i = 0;\n informations = \"\";\n while ((ligneEnCours = in.readLine()) != null) {\n switch(i) {\n case 0:\n version = ligneEnCours;\n break;\n case 1:\n url = ligneEnCours;\n break;\n default:\n informations += ligneEnCours + '\\n';\n break;\n }\n i++;\n }\n in.close();\n erreur = false;\n } catch (IOException e) {\n erreur = true;\n texteErreur = e.getMessage();\n if (texteErreur.equals(\"Network is unreachable\")) {\n texteErreur = \"Pas de réseau\";\n numErreur = 1;\n }\n if (e instanceof FileNotFoundException) {\n texteErreur = \"Problème paramétrage\";\n numErreur = 2;\n }\n e.printStackTrace();\n } finally {\n for (ActionListener al : listeners) {\n al.actionPerformed(null);\n }\n }\n }\n", "label": 1} {"func1": " public static int save(byte[] bytes, File outputFile) throws IOException {\n InputStream in = new ByteArrayInputStream(bytes);\n outputFile.getParentFile().mkdirs();\n OutputStream out = new FileOutputStream(outputFile);\n try {\n return IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(in);\n IOUtils.closeQuietly(out);\n try {\n out.close();\n } catch (IOException ioe) {\n ioe.getMessage();\n }\n try {\n in.close();\n } catch (IOException ioe) {\n ioe.getMessage();\n }\n }\n }\n", "func2": " private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {\n if (entry.isDirectory()) {\n createDir(new File(outputDir, entry.getName()));\n return;\n }\n File outputFile = new File(outputDir, entry.getName());\n if (!outputFile.getParentFile().exists()) {\n createDir(outputFile.getParentFile());\n }\n BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));\n BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));\n try {\n IOUtils.copy(inputStream, outputStream);\n } finally {\n outputStream.close();\n inputStream.close();\n }\n }\n", "label": 1} {"func1": " public void hyperlinkUpdate(HyperlinkEvent e) {\n if (e.getEventType() == EventType.ACTIVATED) {\n try {\n URL url = e.getURL();\n InputStream stream = url.openStream();\n try {\n StringWriter writer = new StringWriter();\n IOUtils.copy(stream, writer, \"UTF-8\");\n JEditorPane editor = new JEditorPane(\"text/plain\", writer.toString());\n editor.setEditable(false);\n editor.setBackground(Color.WHITE);\n editor.setCaretPosition(0);\n editor.setPreferredSize(new Dimension(600, 400));\n String name = url.toString();\n name = name.substring(name.lastIndexOf('/') + 1);\n JDialog dialog = new JDialog(this, \"内容解析: \" + name);\n dialog.add(new JScrollPane(editor));\n dialog.pack();\n dialog.setVisible(true);\n } finally {\n stream.close();\n }\n } catch (IOException exception) {\n exception.printStackTrace();\n }\n }\n }\n", "func2": " public void execute(File sourceFile, File destinationFile, String conversionType, Properties java2HtmlConfig) {\n FileReader reader = null;\n Writer writer = null;\n try {\n reader = new FileReader(sourceFile);\n logger.info(\"Using source file: \" + trimPath(userDir, sourceFile));\n if (!destinationFile.getParentFile().exists()) {\n createDirectory(destinationFile.getParentFile());\n }\n writer = new FileWriter(destinationFile);\n logger.info(\"Destination file: \" + trimPath(userDir, destinationFile));\n execute(reader, writer, conversionType, java2HtmlConfig);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (writer != null) {\n try {\n writer.close();\n writer = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (reader != null) {\n try {\n reader.close();\n reader = null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n", "label": 1} {"func1": " static void copy(String src, String dest) throws IOException {\n File ifp = new File(src);\n File ofp = new File(dest);\n if (ifp.exists() == false) {\n throw new IOException(\"file '\" + src + \"' does not exist\");\n }\n FileInputStream fis = new FileInputStream(ifp);\n FileOutputStream fos = new FileOutputStream(ofp);\n byte[] b = new byte[1024];\n while (fis.read(b) > 0) fos.write(b);\n fis.close();\n fos.close();\n }\n", "func2": " public static void copy(File source, File dest) throws IOException {\n FileChannel in = null, out = null;\n try {\n in = new FileInputStream(source).getChannel();\n out = new FileOutputStream(dest).getChannel();\n long size = in.size();\n MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);\n out.write(buf);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "label": 1} {"func1": " public static String md5String(String str) {\n try {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] hash = md.digest();\n final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n StringBuffer res = new StringBuffer();\n for (int i = 0; i < hash.length; i++) {\n res.append(hexChars[(0xF0 & hash[i]) >> 4]);\n res.append(hexChars[0x0F & hash[i]]);\n }\n return res.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n }\n", "func2": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n System.err.println(\"Failed to load the MD5 MessageDigest. \" + \"unable to function normally.\");\n nsae.printStackTrace();\n }\n }\n digest.update(data.getBytes());\n return encodeHex(digest.digest());\n }\n", "label": 1} {"func1": " public static boolean copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf) throws IOException {\n if (srcFS.getFileStatus(src).isDir()) {\n if (!dst.mkdirs()) {\n return false;\n }\n FileStatus contents[] = srcFS.listStatus(src);\n for (int i = 0; i < contents.length; i++) {\n copy(srcFS, contents[i].getPath(), new File(dst, contents[i].getPath().getName()), deleteSource, conf);\n }\n } else if (srcFS.isFile(src)) {\n InputStream in = srcFS.open(src);\n IOUtils.copyBytes(in, new FileOutputStream(dst), conf);\n } else {\n throw new IOException(src.toString() + \": No such file or directory\");\n }\n if (deleteSource) {\n return srcFS.delete(src, true);\n } else {\n return true;\n }\n }\n", "func2": " public void patch() throws IOException {\n if (mods.isEmpty()) {\n return;\n }\n IOUtils.copy(new FileInputStream(Paths.getMinecraftJarPath()), new FileOutputStream(new File(Paths.getMinecraftBackupPath())));\n JarFile mcjar = new JarFile(Paths.getMinecraftJarPath());\n }\n", "label": 1} {"func1": " private JSONObject executeHttpGet(String uri) throws Exception {\n HttpGet req = new HttpGet(uri);\n HttpClient client = new DefaultHttpClient();\n HttpResponse resLogin = client.execute(req);\n BufferedReader r = new BufferedReader(new InputStreamReader(resLogin.getEntity().getContent()));\n StringBuilder sb = new StringBuilder();\n String s = null;\n while ((s = r.readLine()) != null) {\n sb.append(s);\n }\n return new JSONObject(sb.toString());\n }\n", "func2": " public static void doVersionCheck(View view) {\n view.showWaitCursor();\n try {\n URL url = new URL(jEdit.getProperty(\"version-check.url\"));\n InputStream in = url.openStream();\n BufferedReader bin = new BufferedReader(new InputStreamReader(in));\n String line;\n String develBuild = null;\n String stableBuild = null;\n while ((line = bin.readLine()) != null) {\n if (line.startsWith(\".build\")) develBuild = line.substring(6).trim(); else if (line.startsWith(\".stablebuild\")) stableBuild = line.substring(12).trim();\n }\n bin.close();\n if (develBuild != null && stableBuild != null) {\n doVersionCheck(view, stableBuild, develBuild);\n }\n } catch (IOException e) {\n String[] args = { jEdit.getProperty(\"version-check.url\"), e.toString() };\n GUIUtilities.error(view, \"read-error\", args);\n }\n view.hideWaitCursor();\n }\n", "label": 1} {"func1": " public static void unzipModel(String filename, String tempdir) throws EDITSException {\n try {\n BufferedOutputStream dest = null;\n FileInputStream fis = new FileInputStream(filename);\n int BUFFER = 2048;\n ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));\n ZipEntry entry;\n while ((entry = zis.getNextEntry()) != null) {\n int count;\n byte data[] = new byte[BUFFER];\n FileOutputStream fos = new FileOutputStream(tempdir + entry.getName());\n dest = new BufferedOutputStream(fos, BUFFER);\n while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count);\n dest.flush();\n dest.close();\n }\n zis.close();\n } catch (Exception e) {\n throw new EDITSException(\"Can not expand model in \\\"\" + tempdir + \"\\\" because:\\n\" + e.getMessage());\n }\n }\n", "func2": " public static void save(String packageName, ArrayList fileContents, ArrayList fileNames) throws Exception {\n String dirBase = Util.JAVA_DIR + File.separator + packageName;\n File packageDir = new File(dirBase);\n if (!packageDir.exists()) {\n boolean created = packageDir.mkdir();\n if (!created) {\n File currentPath = new File(\".\");\n throw new Exception(\"Directory \" + packageName + \" could not be created. Current directory: \" + currentPath.getAbsolutePath());\n }\n }\n for (int i = 0; i < fileContents.size(); i++) {\n File file = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n FileOutputStream fos = new FileOutputStream(file);\n fos.write(fileContents.get(i));\n fos.flush();\n fos.close();\n }\n for (int i = 0; i < fileNames.size(); i++) {\n File fileSrc = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));\n File fileDst = new File(dirBase + File.separator + fileNames.get(i));\n BufferedReader reader = new BufferedReader(new FileReader(fileSrc));\n BufferedWriter writer = new BufferedWriter(new FileWriter(fileDst));\n writer.append(\"package \" + packageName + \";\\n\");\n String line = \"\";\n while ((line = reader.readLine()) != null) writer.append(line + \"\\n\");\n writer.flush();\n writer.close();\n reader.close();\n }\n }\n", "label": 1} {"func1": " public static void copy(File srcPath, File dstPath) throws IOException {\n if (srcPath.isDirectory()) {\n if (!dstPath.exists()) {\n boolean result = dstPath.mkdir();\n if (!result) throw new IOException(\"Unable to create directoy: \" + dstPath);\n }\n String[] files = srcPath.list();\n for (String file : files) {\n copy(new File(srcPath, file), new File(dstPath, file));\n }\n } else {\n if (srcPath.exists()) {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(srcPath).getChannel();\n out = new FileOutputStream(dstPath).getChannel();\n long size = in.size();\n MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);\n out.write(buf);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n }\n }\n", "func2": " public static void unzip(File file, ZipFile zipFile, File targetDirectory) throws BusinessException {\n LOG.info(\"Unzipping zip file '\" + file.getAbsolutePath() + \"' to directory '\" + targetDirectory.getAbsolutePath() + \"'.\");\n assert (file.exists() && file.isFile());\n if (targetDirectory.exists() == false) {\n LOG.debug(\"Creating target directory.\");\n if (targetDirectory.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + targetDirectory.getAbsolutePath() + \"'!\");\n }\n }\n ZipInputStream zipin = null;\n try {\n zipin = new ZipInputStream(new FileInputStream(file));\n ZipEntry entry = null;\n while ((entry = zipin.getNextEntry()) != null) {\n LOG.debug(\"Unzipping entry '\" + entry.getName() + \"'.\");\n if (entry.isDirectory()) {\n LOG.debug(\"Skipping directory.\");\n continue;\n }\n final File targetFile = new File(targetDirectory, entry.getName());\n final File parentTargetFile = targetFile.getParentFile();\n if (parentTargetFile.exists() == false) {\n LOG.debug(\"Creating directory '\" + parentTargetFile.getAbsolutePath() + \"'.\");\n if (parentTargetFile.mkdirs() == false) {\n throw new BusinessException(\"Could not create target directory at '\" + parentTargetFile.getAbsolutePath() + \"'!\");\n }\n }\n InputStream input = null;\n FileOutputStream output = null;\n try {\n input = zipFile.getInputStream(entry);\n if (targetFile.createNewFile() == false) {\n throw new BusinessException(\"Could not create target file '\" + targetFile.getAbsolutePath() + \"'!\");\n }\n output = new FileOutputStream(targetFile);\n int readBytes = 0;\n byte[] buffer = new byte[BUFFER_SIZE];\n while ((readBytes = input.read(buffer, 0, buffer.length)) > 0) {\n output.write(buffer, 0, readBytes);\n }\n } finally {\n FileUtil.closeCloseable(input);\n FileUtil.closeCloseable(output);\n }\n }\n } catch (IOException e) {\n throw new BusinessException(\"Could not unzip file '\" + file.getAbsolutePath() + \"'!\", e);\n } finally {\n FileUtil.closeCloseable(zipin);\n }\n }\n", "label": 1} {"func1": " public void createFile(File src, String filename) throws IOException {\n try {\n FileInputStream fis = new FileInputStream(src);\n OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);\n IOUtils.copy(fis, fos);\n fos.close();\n fis.close();\n } catch (ResourceManagerException e) {\n LOGGER.error(e);\n }\n }\n", "func2": " private void copy(File source, File destinationDirectory) throws IOException {\n if (source.isDirectory()) {\n File newDir = new File(destinationDirectory, source.getName());\n newDir.mkdir();\n File[] children = source.listFiles();\n for (int i = 0; i < children.length; i++) {\n if (children[i].getName().equals(\".svn\")) {\n continue;\n }\n copy(children[i], newDir);\n }\n } else {\n File newFile = new File(destinationDirectory, source.getName());\n if (newFile.exists() && source.lastModified() == newFile.lastModified()) {\n return;\n }\n FileOutputStream output = new FileOutputStream(newFile);\n FileInputStream input = new FileInputStream(source);\n byte[] buff = new byte[2048];\n int read = 0;\n while ((read = input.read(buff)) > 0) {\n output.write(buff, 0, read);\n }\n output.flush();\n output.close();\n input.close();\n }\n }\n", "label": 1} {"func1": " public void copy(File s, File t) throws IOException {\n FileChannel in = (new FileInputStream(s)).getChannel();\n FileChannel out = (new FileOutputStream(t)).getChannel();\n in.transferTo(0, s.length(), out);\n in.close();\n out.close();\n }\n", "func2": " public void testReadPerMemberSixSmall() throws IOException {\n GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(sixsmall_gz));\n gzin.setEofEachMember(true);\n for (int i = 0; i < 3; i++) {\n int count2 = IOUtils.copy(gzin, new NullOutputStream());\n assertEquals(\"wrong 1-byte member count\", 1, count2);\n gzin.nextMember();\n int count3 = IOUtils.copy(gzin, new NullOutputStream());\n assertEquals(\"wrong 5-byte member count\", 5, count3);\n gzin.nextMember();\n }\n int countEnd = IOUtils.copy(gzin, new NullOutputStream());\n assertEquals(\"wrong eof count\", 0, countEnd);\n }\n", "label": 1} {"func1": " public synchronized String encrypt(String plaintext) throws Exception {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"MD5\");\n } catch (Exception e) {\n }\n try {\n md.update(plaintext.getBytes(\"UTF-8\"));\n } catch (Exception e) {\n }\n byte raw[] = md.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "func2": " public static String md5(String data) {\n try {\n MessageDigest md = MessageDigest.getInstance(MD);\n md.update(data.getBytes(UTF8));\n return encodeHex(md.digest());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n", "label": 1} {"func1": " private void loadBinaryStream(String streamName, InputStream streamToLoad, long sz, HttpServletRequest req, HttpServletResponse resp) throws IOException {\n resp.setContentType(getContentType(req, streamName));\n resp.setHeader(\"Content-Disposition\", \"inline;filename=\" + streamName);\n resp.setContentLength((int) sz);\n OutputStream out = resp.getOutputStream();\n BufferedOutputStream bos = new BufferedOutputStream(out, 2048);\n try {\n IOUtils.copy(streamToLoad, bos);\n } finally {\n IOUtils.closeQuietly(streamToLoad);\n IOUtils.closeQuietly(bos);\n }\n getCargo().put(GWT_ENTRY_POINT_PAGE_PARAM, null);\n }\n", "func2": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 1} {"func1": " private void createButtonCopyToClipboard() {\n buttonCopyToClipboard = new Button(shell, SWT.PUSH);\n buttonCopyToClipboard.setText(\"Co&py to Clipboard\");\n buttonCopyToClipboard.setLayoutData(SharedStyle.relativeToBottomRight(buttonClose));\n buttonCopyToClipboard.addSelectionListener(new SelectionAdapter() {\n\n @Override\n public void widgetSelected(final SelectionEvent event) {\n IOUtils.copyToClipboard(Version.getEnvironmentReport());\n }\n });\n }\n", "func2": " public static void copyFile(File in, File out) {\n try {\n FileChannel inChannel = null, outChannel = null;\n try {\n out.getParentFile().mkdirs();\n inChannel = new FileInputStream(in).getChannel();\n outChannel = new FileOutputStream(out).getChannel();\n outChannel.transferFrom(inChannel, 0, inChannel.size());\n } finally {\n if (inChannel != null) {\n inChannel.close();\n }\n if (outChannel != null) {\n outChannel.close();\n }\n }\n } catch (Exception e) {\n ObjectUtils.throwAsError(e);\n }\n }\n", "label": 1} {"func1": " @Test\n public void testCopy_readerToOutputStream_Encoding() throws Exception {\n InputStream in = new ByteArrayInputStream(inData);\n in = new YellOnCloseInputStreamTest(in);\n Reader reader = new InputStreamReader(in, \"US-ASCII\");\n ByteArrayOutputStream baout = new ByteArrayOutputStream();\n OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);\n IOUtils.copy(reader, out, \"UTF16\");\n byte[] bytes = baout.toByteArray();\n bytes = new String(bytes, \"UTF16\").getBytes(\"US-ASCII\");\n assertTrue(\"Content differs\", Arrays.equals(inData, bytes));\n }\n", "func2": " @Override\n public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {\n if (query == null) {\n throw new NotConnectedException();\n }\n ArrayList recipients = query.getUserManager().getTecMail();\n Mail mail = new Mail(recipients);\n try {\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(\"log/ossobooklog.zip\"));\n FileInputStream fis = new FileInputStream(\"log/ossobook.log\");\n ZipEntry entry = new ZipEntry(\"ossobook.log\");\n zos.putNextEntry(entry);\n byte[] buffer = new byte[8192];\n int read = 0;\n while ((read = fis.read(buffer, 0, 1024)) != -1) {\n zos.write(buffer, 0, read);\n }\n zos.closeEntry();\n fis.close();\n zos.close();\n mail.sendErrorMessage(message, new File(\"log/ossobooklog.zip\"), getUserName());\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "label": 1} {"func1": " public static void main(String[] args) throws Exception {\n if (args.length != 2) {\n System.out.println(\"arguments: sourcefile destfile\");\n System.exit(1);\n }\n FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel();\n ByteBuffer buffer = ByteBuffer.allocate(BSIZE);\n while (in.read(buffer) != -1) {\n buffer.flip();\n out.write(buffer);\n buffer.clear();\n }\n }\n", "func2": " protected static void copyDeleting(File source, File dest) throws IOException {\n byte[] buf = new byte[8 * 1024];\n FileInputStream in = new FileInputStream(source);\n try {\n FileOutputStream out = new FileOutputStream(dest);\n try {\n int count;\n while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);\n } finally {\n out.close();\n }\n } finally {\n in.close();\n }\n }\n", "label": 1} {"func1": " public ByteBuffer[] write(ByteBuffer[] byteBuffers) {\n if (!m_sslInitiated) {\n return m_writer.write(byteBuffers);\n }\n if (m_engine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {\n if (!NIOUtils.isEmpty(byteBuffers)) {\n m_initialOutBuffer = NIOUtils.concat(m_initialOutBuffer, m_writer.write(byteBuffers));\n byteBuffers = new ByteBuffer[0];\n }\n ByteBuffer buffer = SSL_BUFFER.get();\n ByteBuffer[] buffers = null;\n try {\n SSLEngineResult result = null;\n while (m_engine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {\n buffer.clear();\n result = m_engine.wrap(byteBuffers, buffer);\n buffer.flip();\n buffers = NIOUtils.concat(buffers, NIOUtils.copy(buffer));\n }\n if (result == null) return null;\n if (result.getStatus() != SSLEngineResult.Status.OK) throw new SSLException(\"Unexpectedly not ok wrapping handshake data, was \" + result.getStatus());\n reactToHandshakeStatus(result.getHandshakeStatus());\n } catch (SSLException e) {\n throw new RuntimeException(e);\n }\n return buffers;\n }\n ByteBuffer buffer = SSL_BUFFER.get();\n buffer.clear();\n if (NIOUtils.isEmpty(byteBuffers)) {\n if (m_initialOutBuffer == null) return null;\n } else {\n byteBuffers = m_writer.write(byteBuffers);\n }\n if (m_initialOutBuffer != null) {\n byteBuffers = NIOUtils.concat(m_initialOutBuffer, byteBuffers);\n m_initialOutBuffer = null;\n }\n ByteBuffer[] encrypted = null;\n while (!NIOUtils.isEmpty(byteBuffers)) {\n buffer.clear();\n try {\n m_engine.wrap(byteBuffers, buffer);\n } catch (SSLException e) {\n throw new RuntimeException(e);\n }\n buffer.flip();\n encrypted = NIOUtils.concat(encrypted, NIOUtils.copy(buffer));\n }\n return encrypted;\n }\n", "func2": " public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException {\n logger.info(\"copyFile(File src=\" + src + \", File dest=\" + dest + \", int bufSize=\" + bufSize + \", boolean force=\" + force + \") - start\");\n File f = new File(Configuration.getArchiveDir());\n if (!f.exists()) {\n f.mkdir();\n }\n if (dest.exists()) {\n if (force) {\n dest.delete();\n } else {\n throw new IOException(\"Cannot overwrite existing file: \" + dest);\n }\n }\n byte[] buffer = new byte[bufSize];\n int read = 0;\n InputStream in = null;\n OutputStream out = null;\n try {\n in = new FileInputStream(src);\n out = new FileOutputStream(dest);\n while (true) {\n read = in.read(buffer);\n if (read == -1) {\n break;\n }\n out.write(buffer, 0, read);\n }\n } finally {\n if (in != null) {\n try {\n in.close();\n } finally {\n if (out != null) {\n out.close();\n }\n }\n }\n }\n logger.debug(\"copyFile(File, File, int, boolean) - end\");\n }\n", "label": 1} {"func1": " public synchronized String encrypt(String plaintext) {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n try {\n md.update(plaintext.getBytes(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n byte raw[] = md.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "func2": " public String generateToken(String code) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA1\");\n md.update(code.getBytes());\n byte[] bytes = md.digest();\n return toHex(bytes);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"SHA1 missing\");\n }\n }\n", "label": 1} {"func1": " public static void copyFileTo(String src, String dest) throws FileNotFoundException, IOException {\n File destFile = new File(dest);\n InputStream in = new FileInputStream(new File(src));\n OutputStream out = new FileOutputStream(destFile);\n byte buf[] = new byte[1024];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n }\n", "func2": " public static int save(byte[] bytes, File outputFile) throws IOException {\n InputStream in = new ByteArrayInputStream(bytes);\n outputFile.getParentFile().mkdirs();\n OutputStream out = new FileOutputStream(outputFile);\n try {\n return IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(in);\n IOUtils.closeQuietly(out);\n try {\n out.close();\n } catch (IOException ioe) {\n ioe.getMessage();\n }\n try {\n in.close();\n } catch (IOException ioe) {\n ioe.getMessage();\n }\n }\n }\n", "label": 1} {"func1": " private void copyFile(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " private void compress(String outputFile, ArrayList inputFiles, PrintWriter log, boolean compress) throws Exception {\n String absPath = getAppConfig().getPathConfig().getAbsoluteServerPath();\n log.println(\"Concat files into: \" + outputFile);\n OutputStream out = new FileOutputStream(absPath + outputFile);\n byte[] buffer = new byte[4096];\n int readBytes;\n for (String file : inputFiles) {\n log.println(\" Read: \" + file);\n InputStream in = new FileInputStream(absPath + file);\n while ((readBytes = in.read(buffer)) != -1) {\n out.write(buffer, 0, readBytes);\n }\n in.close();\n }\n out.close();\n if (compress) {\n long normalSize = new File(absPath + outputFile).length();\n ProcessBuilder builder = new ProcessBuilder(\"java\", \"-jar\", \"WEB-INF/yuicompressor.jar\", outputFile, \"-o\", outputFile, \"--line-break\", \"4000\");\n builder.directory(new File(absPath));\n Process process = builder.start();\n process.waitFor();\n long minSize = new File(absPath + outputFile).length();\n long diff = normalSize - minSize;\n double percentage = Math.floor((double) diff / normalSize * 1000.0) / 10.0;\n double diffSize = (Math.floor(diff / 1024.0 * 10.0) / 10.0);\n log.println(\"Result: \" + percentage + \" % (\" + diffSize + \" KB)\");\n }\n }\n", "label": 1} {"func1": " public static void copyFile(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " public static void copy(File source, File dest) throws IOException {\n FileChannel in = null, out = null;\n try {\n in = new FileInputStream(source).getChannel();\n out = new FileOutputStream(dest).getChannel();\n long size = in.size();\n MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);\n out.write(buf);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "label": 1} {"func1": " public void createFile(File src, String filename) throws IOException {\n try {\n FileInputStream fis = new FileInputStream(src);\n OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);\n IOUtils.copy(fis, fos);\n fos.close();\n fis.close();\n } catch (ResourceManagerException e) {\n LOGGER.error(e);\n }\n }\n", "func2": " static File copy(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n return out;\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "label": 1} {"func1": " public static void compressWithZip(Vector fileList, String zipFileName) throws IOException {\n if (fileList == null || fileList.size() == 0) return;\n FileOutputStream fos = new FileOutputStream(zipFileName);\n ZipOutputStream zos = new ZipOutputStream(fos);\n Iterator iter = fileList.iterator();\n while (iter.hasNext()) {\n String fileName = (String) iter.next();\n int ind = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\\\'));\n String shortName = \"unknown\";\n if (ind < fileName.length() - 1) shortName = fileName.substring(ind + 1);\n zos.putNextEntry(new ZipEntry(shortName));\n FileInputStream fis = new FileInputStream(fileName);\n byte[] buf = new byte[10000];\n int bytesRead;\n while ((bytesRead = fis.read(buf)) > 0) zos.write(buf, 0, bytesRead);\n fis.close();\n zos.closeEntry();\n }\n zos.close();\n }\n", "func2": " public static void main(String args[]) throws IOException {\n String inFileName = args[0];\n String outFileName = args[1];\n long position = 0L;\n try {\n position = Long.parseLong(args[2]);\n } catch (NumberFormatException nfex1) {\n try {\n position = Long.parseLong(args[2], 16);\n } catch (NumberFormatException nfex2) {\n System.err.println(\"Wrong offset\");\n System.exit(0);\n }\n }\n if (position < 1L) {\n System.err.println(\"Wrong offset. Must be more than 0\");\n System.exit(0);\n }\n System.out.println(\"Copying input: \" + inFileName);\n System.out.println(\" output: \" + outFileName);\n System.out.println(\" from: \" + position);\n BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFileName));\n BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFileName));\n bis.skip(position);\n for (byte[] b = new byte[1]; bis.read(b) > 0; bos.write(b)) ;\n bis.close();\n bos.close();\n }\n", "label": 1} {"func1": " @Test\n public void testCopy_readerToWriter_nullIn() throws Exception {\n ByteArrayOutputStream baout = new ByteArrayOutputStream();\n OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);\n Writer writer = new OutputStreamWriter(baout, \"US-ASCII\");\n try {\n IOUtils.copy((Reader) null, writer);\n fail();\n } catch (NullPointerException ex) {\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public static void main(String[] args) {\n if (args.length != 1) {\n System.out.println(\"Usage: GZip source\");\n return;\n }\n String zipname = args[0] + \".gz\";\n GZIPOutputStream zipout;\n try {\n FileOutputStream out = new FileOutputStream(zipname);\n zipout = new GZIPOutputStream(out);\n } catch (IOException e) {\n System.out.println(\"Couldn't create \" + zipname + \".\");\n return;\n }\n byte[] buffer = new byte[sChunk];\n try {\n FileInputStream in = new FileInputStream(args[0]);\n int length;\n while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length);\n in.close();\n } catch (IOException e) {\n System.out.println(\"Couldn't compress \" + args[0] + \".\");\n }\n try {\n zipout.close();\n } catch (IOException e) {\n }\n }\n", "func2": " public void cpFile(File source, File target, boolean replace, int bufferSize) throws IOException {\n if (!source.exists()) throw new IOException(\"source file not exists\");\n if (!source.isFile()) throw new IOException(\"source file not exists(is a directory)\");\n InputStream src = new FileInputStream(source);\n File tarn = target;\n if (target.isDirectory() || !(!(target.exists()) || replace)) {\n String tardir = target.isDirectory() ? target.getPath() : target.getParent();\n tarn = new File(tardir + File.separator + source.getName());\n int n = 1;\n while (!(!tarn.exists() || replace)) {\n tarn = new File(tardir + File.separator + String.valueOf(n) + \" copy of \" + source.getName());\n n++;\n }\n }\n if (source.getPath().equals(tarn.getPath()) && replace) return;\n OutputStream tar = new FileOutputStream(tarn);\n byte[] bytes = new byte[bufferSize];\n int readn = -1;\n while ((readn = src.read(bytes)) > 0) {\n tar.write(bytes, 0, readn);\n }\n tar.flush();\n tar.close();\n src.close();\n }\n", "label": 1} {"func1": " public static String eventHash(String eventstr) {\n try {\n if (md == null) {\n md = MessageDigest.getInstance(\"MD5\");\n }\n md.update(eventstr.getBytes(\"utf-8\"));\n byte[] theDigest = md.digest();\n return new BASE64Encoder().encode(theDigest);\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " public static String getMD5(String _pwd) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(_pwd.getBytes());\n return toHexadecimal(new String(md.digest()).getBytes());\n } catch (NoSuchAlgorithmException x) {\n x.printStackTrace();\n return \"\";\n }\n }\n", "label": 1} {"func1": " public static String doCrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"SHA-1\");\n byte[] sha1hash = new byte[40];\n md.update(text.getBytes(\"UTF-8\"), 0, text.length());\n sha1hash = md.digest();\n return convertToHex(sha1hash);\n }\n", "func2": " public static String md5String(String str) {\n try {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] hash = md.digest();\n final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n StringBuffer res = new StringBuffer();\n for (int i = 0; i < hash.length; i++) {\n res.append(hexChars[(0xF0 & hash[i]) >> 4]);\n res.append(hexChars[0x0F & hash[i]]);\n }\n return res.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n }\n", "label": 1} {"func1": " protected void innerProcess(CrawlURI curi) throws InterruptedException {\n if (!curi.isHttpTransaction()) {\n return;\n }\n if (!TextUtils.matches(\"^text.*$\", curi.getContentType())) {\n return;\n }\n long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue();\n try {\n maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue();\n } catch (AttributeNotFoundException e) {\n logger.severe(\"Missing max-size-bytes attribute when processing \" + curi.getURIString());\n }\n if (maxsize < curi.getContentSize() && maxsize > -1) {\n return;\n }\n String regexpr = \"\";\n try {\n regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR);\n } catch (AttributeNotFoundException e2) {\n logger.severe(\"Missing strip-reg-exp when processing \" + curi.getURIString());\n return;\n }\n ReplayCharSequence cs = null;\n try {\n cs = curi.getHttpRecorder().getReplayCharSequence();\n } catch (Exception e) {\n curi.addLocalizedError(this.getName(), e, \"Failed get of replay char sequence \" + curi.toString() + \" \" + e.getMessage());\n logger.warning(\"Failed get of replay char sequence \" + curi.toString() + \" \" + e.getMessage() + \" \" + Thread.currentThread().getName());\n return;\n }\n MessageDigest digest = null;\n try {\n digest = MessageDigest.getInstance(\"SHA1\");\n } catch (NoSuchAlgorithmException e1) {\n e1.printStackTrace();\n return;\n }\n digest.reset();\n String s = null;\n if (regexpr.length() == 0) {\n s = cs.toString();\n } else {\n Matcher m = TextUtils.getMatcher(regexpr, cs);\n s = m.replaceAll(\" \");\n }\n digest.update(s.getBytes());\n byte[] newDigestValue = digest.digest();\n if (logger.isLoggable(Level.FINEST)) {\n logger.finest(\"Recalculated content digest for \" + curi.getURIString() + \" old: \" + Base32.encode((byte[]) curi.getContentDigest()) + \", new: \" + Base32.encode(newDigestValue));\n }\n curi.setContentDigest(newDigestValue);\n }\n", "func2": " public static String md5(String str) {\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - start\");\n }\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] b = md.digest();\n StringBuffer sb = new StringBuffer();\n for (int i = 0; i < b.length; i++) {\n int v = (int) b[i];\n v = v < 0 ? 0x100 + v : v;\n String cc = Integer.toHexString(v);\n if (cc.length() == 1) sb.append('0');\n sb.append(cc);\n }\n String returnString = sb.toString();\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - end\");\n }\n return returnString;\n } catch (Exception e) {\n logger.warn(\"md5(String) - exception ignored\", e);\n }\n if (logger.isDebugEnabled()) {\n logger.debug(\"md5(String) - end\");\n }\n return \"\";\n }\n", "label": 1} {"func1": " private void getRandomGUID(boolean secure) {\n MessageDigest md5 = null;\n StringBuffer sbValueBeforeMD5 = new StringBuffer();\n try {\n md5 = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException e) {\n logger.error(\"At RandomGUID !!!\", e);\n }\n try {\n long time = System.currentTimeMillis();\n long rand = 0;\n if (secure) {\n rand = mySecureRand.nextLong();\n } else {\n rand = myRand.nextLong();\n }\n sbValueBeforeMD5.append(s_id);\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(time));\n sbValueBeforeMD5.append(\":\");\n sbValueBeforeMD5.append(Long.toString(rand));\n valueBeforeMD5 = sbValueBeforeMD5.toString();\n md5.update(valueBeforeMD5.getBytes());\n byte[] array = md5.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n valueAfterMD5 = sb.toString();\n } catch (Exception e) {\n logger.error(\"At RandomGUID !!!\", e);\n }\n }\n", "func2": " public synchronized String encryptPassword(String passwordString) throws Exception {\n MessageDigest digest = null;\n digest = MessageDigest.getInstance(\"SHA\");\n digest.update(passwordString.getBytes(\"UTF-8\"));\n byte raw[] = digest.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "label": 1} {"func1": " private static void copyFile(File in, File out) {\n try {\n FileChannel sourceChannel = new FileInputStream(in).getChannel();\n FileChannel destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " private void downloadFile(File target, String s3key) throws IOException, S3ServiceException {\n InputStream in = downloadData(s3key);\n if (in == null) {\n throw new IOException(\"No data found\");\n }\n in = new InflaterInputStream(new CryptInputStream(in, cipher, getDataEncryptionKey()));\n File temp = File.createTempFile(\"dirsync\", null);\n FileOutputStream fout = new FileOutputStream(temp);\n try {\n IOUtils.copy(in, fout);\n if (target.exists()) {\n target.delete();\n }\n IOUtils.closeQuietly(fout);\n IOUtils.closeQuietly(in);\n FileUtils.moveFile(temp, target);\n } catch (IOException e) {\n fetchStream(in);\n throw e;\n } finally {\n IOUtils.closeQuietly(fout);\n IOUtils.closeQuietly(in);\n }\n }\n", "func2": " private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {\n if (entry.isDirectory()) {\n createDir(new File(outputDir, entry.getName()));\n return;\n }\n File outputFile = new File(outputDir, entry.getName());\n if (!outputFile.getParentFile().exists()) {\n createDir(outputFile.getParentFile());\n }\n BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));\n BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));\n try {\n IOUtils.copy(inputStream, outputStream);\n } finally {\n outputStream.close();\n inputStream.close();\n }\n }\n", "label": 1} {"func1": " public static void saveAttachmentBody(Context context, Part part, Attachment localAttachment, long accountId) throws MessagingException, IOException {\n if (part.getBody() != null) {\n long attachmentId = localAttachment.mId;\n InputStream in = part.getBody().getInputStream();\n File saveIn = AttachmentProvider.getAttachmentDirectory(context, accountId);\n if (!saveIn.exists()) {\n saveIn.mkdirs();\n }\n File saveAs = AttachmentProvider.getAttachmentFilename(context, accountId, attachmentId);\n saveAs.createNewFile();\n FileOutputStream out = new FileOutputStream(saveAs);\n long copySize = IOUtils.copy(in, out);\n in.close();\n out.close();\n String contentUriString = AttachmentProvider.getAttachmentUri(accountId, attachmentId).toString();\n localAttachment.mSize = copySize;\n localAttachment.mContentUri = contentUriString;\n ContentValues cv = new ContentValues();\n cv.put(AttachmentColumns.SIZE, copySize);\n cv.put(AttachmentColumns.CONTENT_URI, contentUriString);\n Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId);\n context.getContentResolver().update(uri, cv, null, null);\n }\n }\n", "func2": " public void hyperlinkUpdate(HyperlinkEvent e) {\n if (e.getEventType() == EventType.ACTIVATED) {\n try {\n URL url = e.getURL();\n InputStream stream = url.openStream();\n try {\n StringWriter writer = new StringWriter();\n IOUtils.copy(stream, writer, \"UTF-8\");\n JEditorPane editor = new JEditorPane(\"text/plain\", writer.toString());\n editor.setEditable(false);\n editor.setBackground(Color.WHITE);\n editor.setCaretPosition(0);\n editor.setPreferredSize(new Dimension(600, 400));\n String name = url.toString();\n name = name.substring(name.lastIndexOf('/') + 1);\n JDialog dialog = new JDialog(this, \"内容解析: \" + name);\n dialog.add(new JScrollPane(editor));\n dialog.pack();\n dialog.setVisible(true);\n } finally {\n stream.close();\n }\n } catch (IOException exception) {\n exception.printStackTrace();\n }\n }\n }\n", "label": 1} {"func1": " @Override\n public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {\n File dest = new File(this.realFile, name);\n if (allowedClient) {\n if (\".request\".equals(name) || \".tokens\".equals(name)) {\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n if (\".request\".equals(name)) {\n File request = new File(realFile.getAbsolutePath() + \"/\" + name);\n RequestManager.manageRequest(request, null, true);\n return new OverEncryptedFriendsFile(factory, folderPath + \"/.response\", allowedClient);\n }\n return new OverEncryptedFriendsFile(factory, folderPath + \"/\" + name, allowedClient);\n } else {\n return null;\n }\n } else {\n LOGGER.error(\"User isn't owner of this folder\");\n return null;\n }\n }\n", "func2": " private void copyJar(File src, File dst) throws IOException {\n FileChannel srcChannel = null;\n FileChannel dstChannel = null;\n try {\n srcChannel = new FileInputStream(src).getChannel();\n dstChannel = new FileOutputStream(dst).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } catch (IOException e) {\n fLog.log(Level.SEVERE, e.getMessage(), e);\n } finally {\n srcChannel.close();\n dstChannel.close();\n }\n }\n", "label": 1} {"func1": " public static void DecodeMapFile(String mapFile, String outputFile) throws Exception {\n byte magicKey = 0;\n byte[] buffer = new byte[2048];\n int nread;\n InputStream map;\n OutputStream output;\n try {\n map = new FileInputStream(mapFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n try {\n output = new FileOutputStream(outputFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n while ((nread = map.read(buffer, 0, 2048)) != 0) {\n for (int i = 0; i < nread; ++i) {\n buffer[i] ^= magicKey;\n magicKey += 43;\n }\n output.write(buffer, 0, nread);\n }\n map.close();\n output.close();\n }\n", "func2": " private void copyJar(File src, File dst) throws IOException {\n FileChannel srcChannel = null;\n FileChannel dstChannel = null;\n try {\n srcChannel = new FileInputStream(src).getChannel();\n dstChannel = new FileOutputStream(dst).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } catch (IOException e) {\n fLog.log(Level.SEVERE, e.getMessage(), e);\n } finally {\n srcChannel.close();\n dstChannel.close();\n }\n }\n", "label": 1} {"func1": " public String getmd5(String password) {\n String pwHash = \"\";\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(password.getBytes());\n byte[] b = md.digest();\n for (int i = 0; i < b.length; i++) {\n pwHash += Integer.toString((b[i] & 0xFF) + 0x100, 16).substring(1);\n }\n } catch (NoSuchAlgorithmException ex) {\n Logger.fatal(\"MD5 Hash Algorithm not found\", ex);\n }\n Logger.info(\"PWHash erzeugt und wird übergeben\");\n return pwHash;\n }\n", "func2": " private String encryptPassword(String password) throws NoSuchAlgorithmException {\n StringBuffer encryptedPassword = new StringBuffer();\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n md5.update(password.getBytes());\n byte digest[] = md5.digest();\n for (int i = 0; i < digest.length; i++) {\n String hex = Integer.toHexString(0xFF & digest[i]);\n if (hex.length() == 1) {\n encryptedPassword.append('0');\n }\n encryptedPassword.append(hex);\n }\n return encryptedPassword.toString();\n }\n", "label": 1} {"func1": " public static String plainToMD(LoggerCollection loggerCol, String input) {\n byte[] byteHash = null;\n MessageDigest md = null;\n StringBuilder md5result = new StringBuilder();\n try {\n md = MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(input.getBytes());\n byteHash = md.digest();\n for (int i = 0; i < byteHash.length; i++) {\n md5result.append(Integer.toHexString(0xFF & byteHash[i]));\n }\n } catch (NoSuchAlgorithmException ex) {\n loggerCol.logException(CLASSDEBUG, \"de.searchworkorange.lib.misc.hash.MD5Hash\", Level.FATAL, ex);\n }\n return (md5result.toString());\n }\n", "func2": " public static String hashPasswordForOldMD5(String password) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(password.getBytes(\"UTF-8\"));\n byte messageDigest[] = md.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n String hex = Integer.toHexString(0xFF & messageDigest[i]);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException nsae) {\n throw new IllegalStateException(nsae.getMessage());\n } catch (UnsupportedEncodingException uee) {\n throw new IllegalStateException(uee.getMessage());\n }\n }\n", "label": 1} {"func1": " public static void copyExternalResource(File sourceFile, File destFile) throws IOException {\n if (!destFile.exists()) {\n destFile.createNewFile();\n }\n FileChannel source = null;\n FileChannel destination = null;\n try {\n source = new FileInputStream(sourceFile).getChannel();\n destination = new FileOutputStream(destFile).getChannel();\n destination.transferFrom(source, 0, source.size());\n } finally {\n closeQuietly(source);\n closeQuietly(destination);\n }\n }\n", "func2": " public static void copyFile(String fromPath, String toPath) {\n try {\n File inputFile = new File(fromPath);\n String dirImg = (new File(toPath)).getParent();\n File tmp = new File(dirImg);\n if (!tmp.exists()) {\n tmp.mkdir();\n }\n File outputFile = new File(toPath);\n if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) {\n FileInputStream in = new FileInputStream(inputFile);\n FileOutputStream out = new FileOutputStream(outputFile);\n int c;\n while ((c = in.read()) != -1) out.write(c);\n in.close();\n out.close();\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n LogHandler.log(ex.getMessage(), Level.INFO, \"LOG_MSG\", isLoggingEnabled());\n }\n }\n", "label": 1} {"func1": " public boolean connectServer(String server, String user, String password) {\n boolean result = true;\n try {\n if (user.equals(\"\")) {\n user = \"anonymous\";\n password = \"anonymous\";\n }\n this.server = server;\n this.user = user;\n this.password = password;\n ftpClient = new FTPClient();\n ftpClient.setControlEncoding(encode);\n ftpClient.connect(server);\n ftpClient.setSoTimeout(1000 * 30);\n ftpClient.setDefaultTimeout(1000 * 30);\n ftpClient.setConnectTimeout(1000 * 30);\n ftpClient.enterLocalPassiveMode();\n ftpClient.login(user, password);\n if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {\n ftpClient.disconnect();\n return false;\n }\n queFilePath = \"data\\\\\" + this.server + \".que\";\n bufFilePath = \"data\\\\\" + this.server + \".buf\";\n startGetList();\n } catch (java.net.SocketTimeoutException e1) {\n errMsg = ftpClient.getReplyString();\n errCode = ftpClient.getReplyCode();\n result = false;\n setArrToFile(dirQueue, queFilePath);\n setArrToFile(fileList, bufFilePath);\n cn.imgdpu.util.CatException.getMethod().catException(e1, \"连接超时\");\n } catch (Exception e) {\n errMsg = ftpClient.getReplyString();\n errCode = ftpClient.getReplyCode();\n result = false;\n setArrToFile(dirQueue, queFilePath);\n setArrToFile(fileList, bufFilePath);\n cn.imgdpu.util.CatException.getMethod().catException(e, \"未知异常\");\n } finally {\n if (ftpClient.isConnected()) {\n try {\n ftpClient.disconnect();\n } catch (IOException ioe) {\n cn.imgdpu.util.CatException.getMethod().catException(ioe, \"IO异常\");\n }\n }\n }\n return result;\n }\n", "func2": " public static void main(String[] args) {\n FTPClient client = new FTPClient();\n String sFTP = \"ftp.miservidor.com\";\n String sUser = \"usuario\";\n String sPassword = \"password\";\n try {\n System.out.println(\"Conectandose a \" + sFTP);\n client.connect(sFTP);\n boolean login = client.login(sUser, sPassword);\n if (login) {\n System.out.println(\"Login correcto\");\n boolean logout = client.logout();\n if (logout) {\n System.out.println(\"Logout del servidor FTP\");\n }\n } else {\n System.out.println(\"Error en el login.\");\n }\n System.out.println(\"Desconectando.\");\n client.disconnect();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n", "label": 1} {"func1": " public void testSimpleQuery() throws Exception {\n JCRNodeSource dummySource = (JCRNodeSource) resolveSource(BASE_URL + \"users/alexander.klimetschek\");\n assertNotNull(dummySource);\n OutputStream os = ((ModifiableSource) dummySource).getOutputStream();\n assertNotNull(os);\n String dummyContent = \"alexandercyclrmindquarryTooLong\";\n os.write(dummyContent.getBytes());\n os.flush();\n os.close();\n JCRNodeSource source = (JCRNodeSource) resolveSource(BASE_URL + \"users/bastian\");\n assertNotNull(source);\n os = ((ModifiableSource) source).getOutputStream();\n assertNotNull(os);\n String content = \"bastianmindquarry\";\n os.write(content.getBytes());\n os.flush();\n os.close();\n QueryResultSource qResult = (QueryResultSource) resolveSource(BASE_URL + \"users?/*[.//user/teamspace='mindquarry']\");\n assertNotNull(qResult);\n Collection results = qResult.getChildren();\n assertEquals(1, results.size());\n Iterator it = results.iterator();\n JCRNodeSource rSrc = (JCRNodeSource) it.next();\n InputStream rSrcIn = rSrc.getInputStream();\n ByteArrayOutputStream actualOut = new ByteArrayOutputStream();\n IOUtils.copy(rSrcIn, actualOut);\n rSrcIn.close();\n assertEquals(content, actualOut.toString());\n actualOut.close();\n rSrc.delete();\n }\n", "func2": " private void _checkLanguagesFiles(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception {\n List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);\n for (int i = 0; i < list.size(); i++) {\n long langId = ((Language) list.get(i)).getId();\n try {\n String filePath = getGlobalVariablesPath() + \"cms_language_\" + langId + \".properties\";\n boolean copy = false;\n File from = new java.io.File(filePath);\n if (!from.exists()) {\n from.createNewFile();\n copy = true;\n }\n String tmpFilePath = getTemporyDirPath() + \"cms_language_\" + langId + \"_properties.tmp\";\n File to = new java.io.File(tmpFilePath);\n if (!to.exists()) {\n to.createNewFile();\n copy = true;\n }\n if (copy) {\n FileChannel srcChannel = new FileInputStream(from).getChannel();\n FileChannel dstChannel = new FileOutputStream(to).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n }\n } catch (IOException e) {\n Logger.error(this, \"_checkLanguagesFiles:Property File Copy Failed \" + e, e);\n }\n }\n }\n", "label": 1} {"func1": " @Override\n public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {\n File dest = new File(this.realFile, name);\n if (allowedClient) {\n if (\".request\".equals(name) || \".tokens\".equals(name)) {\n FileOutputStream out = null;\n try {\n out = new FileOutputStream(dest);\n IOUtils.copy(in, out);\n } finally {\n IOUtils.closeQuietly(out);\n }\n if (\".request\".equals(name)) {\n File request = new File(realFile.getAbsolutePath() + \"/\" + name);\n RequestManager.manageRequest(request, null, true);\n return new OverEncryptedFriendsFile(factory, folderPath + \"/.response\", allowedClient);\n }\n return new OverEncryptedFriendsFile(factory, folderPath + \"/\" + name, allowedClient);\n } else {\n return null;\n }\n } else {\n LOGGER.error(\"User isn't owner of this folder\");\n return null;\n }\n }\n", "func2": " public void descargarArchivo() {\n try {\n FileInputStream fis = new FileInputStream(resultados.elementAt(materialSelccionado).getRuta());\n FileOutputStream fos = new FileOutputStream(rutaDestinoDescarga);\n FileChannel inChannel = fis.getChannel();\n FileChannel outChannel = fos.getChannel();\n inChannel.transferTo(0, inChannel.size(), outChannel);\n fis.close();\n fos.close();\n } catch (IOException ioe) {\n System.err.println(\"Error al Generar Copia del Material\\n\" + ioe);\n }\n }\n", "label": 1} {"func1": " public void testNetworkHTTP() {\n Log.v(\"Test\", \"[*] testNetworkHTTP()\");\n URL url = null;\n HttpURLConnection urlConnection = null;\n try {\n url = new URL(\"http://code.google.com/p/droidbox/\");\n urlConnection = (HttpURLConnection) url.openConnection();\n BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n @SuppressWarnings(\"unused\") String line = \"\";\n while ((line = rd.readLine()) != null) ;\n url = new URL(\"http://pjlantz.com/imei.php?imei=\" + hashedImei);\n urlConnection = (HttpURLConnection) url.openConnection();\n rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n while ((line = rd.readLine()) != null) ;\n url = new URL(\"http://pjlantz.com/phone.php?phone=\" + phoneNbr);\n urlConnection = (HttpURLConnection) url.openConnection();\n rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n while ((line = rd.readLine()) != null) ;\n url = new URL(\"http://pjlantz.com/msg.php?msg=\" + msg.replace(\" \", \"+\"));\n urlConnection = (HttpURLConnection) url.openConnection();\n rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n url = new URL(\"http://pjlantz.com/file.php?file=\" + fileContent.replace(\" \", \"+\"));\n urlConnection = (HttpURLConnection) url.openConnection();\n rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n while ((line = rd.readLine()) != null) ;\n url = new URL(\"http://pjlantz.com/app.php?installed=\" + installedApps.replace(\" \", \"+\"));\n urlConnection = (HttpURLConnection) url.openConnection();\n rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\n while ((line = rd.readLine()) != null) ;\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n urlConnection.disconnect();\n }\n }\n", "func2": " public void init(ServletContext context) throws ScratchException {\n try {\n log.debug(\"Attempting to load Controllers from file: \" + REGISTRY_FILENAME);\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration urls = classLoader.getResources(REGISTRY_FILENAME);\n while (urls.hasMoreElements()) {\n URL url = urls.nextElement();\n log.debug(\"Found: \" + url);\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n String className = null;\n while ((className = reader.readLine()) != null) {\n className = className.trim();\n if (!\"\".equals(className) && !className.startsWith(\"#\")) {\n log.debug(\"Found class: \" + className);\n Class clazz = classLoader.loadClass(className);\n addClass(clazz);\n }\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n log.error(e);\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n log.error(e);\n }\n }\n", "label": 1} {"func1": " static void copy(String src, String dest) throws IOException {\n File ifp = new File(src);\n File ofp = new File(dest);\n if (ifp.exists() == false) {\n throw new IOException(\"file '\" + src + \"' does not exist\");\n }\n FileInputStream fis = new FileInputStream(ifp);\n FileOutputStream fos = new FileOutputStream(ofp);\n byte[] b = new byte[1024];\n while (fis.read(b) > 0) fos.write(b);\n fis.close();\n fos.close();\n }\n", "func2": " @Override\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {\n InputStream is = null;\n InputStream page = null;\n OutputStream os = null;\n String rootUrl = null;\n try {\n boolean isMultipart = ServletFileUpload.isMultipartContent(request);\n if (!isMultipart) {\n request.setAttribute(\"error\", \"Form isn't a multipart form\");\n RequestDispatcher rd = request.getRequestDispatcher(\"/WEB-INF/error.jsp\");\n rd.forward(request, response);\n }\n ServletFileUpload upload = new ServletFileUpload();\n String webUrl = null;\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n if (name.equals(\"webpage\")) {\n is = item.openStream();\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(is, baos);\n page = new ByteArrayInputStream(baos.toByteArray());\n } else if (name.equals(\"weburl\")) {\n InputStream wpIs = null;\n try {\n webUrl = Streams.asString(item.openStream());\n URL u = new URL(webUrl);\n wpIs = new BufferedInputStream(u.openStream());\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(wpIs, baos);\n page = new ByteArrayInputStream(baos.toByteArray());\n } finally {\n IOUtils.closeQuietly(wpIs);\n }\n } else if (name.equals(\"rooturl\")) {\n rootUrl = Streams.asString(item.openStream());\n }\n }\n if (page == null) {\n request.setAttribute(\"error\", \"Form doesn't have an html file\");\n RequestDispatcher rd = request.getRequestDispatcher(\"/WEB-INF/error.jsp\");\n rd.forward(request, response);\n }\n ToMailerDelegate delegate = new ToMailerDelegate(page, rootUrl);\n os = new BufferedOutputStream(response.getOutputStream());\n os.write(delegate.getMailer());\n os.flush();\n } catch (Exception e) {\n streamException(request, response, e);\n } finally {\n IOUtils.closeQuietly(page);\n IOUtils.closeQuietly(is);\n IOUtils.closeQuietly(os);\n }\n }\n", "label": 1} {"func1": " private boolean checkHashBack(Facade facade, HttpServletRequest req) {\n String txtTransactionID = req.getParameter(\"txtTransactionID\");\n String txtOrderTotal = req.getParameter(\"txtOrderTotal\");\n String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);\n String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);\n String txtHashBack = req.getParameter(\"txtHashBack\");\n String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);\n String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;\n MessageDigest digest;\n try {\n digest = java.security.MessageDigest.getInstance(\"MD5\");\n digest.update(securityValue.getBytes());\n byte[] array = digest.digest();\n StringBuffer sb = new StringBuffer();\n for (int j = 0; j < array.length; ++j) {\n int b = array[j] & 0xFF;\n if (b < 0x10) sb.append('0');\n sb.append(Integer.toHexString(b));\n }\n String hash = sb.toString();\n System.out.println(\"com.eshop.http.servlets.PaymentController.checkHashBack: \" + hash + \" \" + txtHashBack);\n if (txtHashBack.equals(hash)) {\n return true;\n }\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n return false;\n }\n", "func2": " private void generateDeviceUUID() {\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(deviceType.getBytes());\n md5.update(internalId.getBytes());\n md5.update(bindAddress.getHostName().getBytes());\n StringBuffer hexString = new StringBuffer();\n byte[] digest = md5.digest();\n for (int i = 0; i < digest.length; i++) {\n hexString.append(Integer.toHexString(0xFF & digest[i]));\n }\n uuid = hexString.toString().toUpperCase();\n } catch (Exception ex) {\n RuntimeException runTimeEx = new RuntimeException(\"Unexpected error during MD5 hash creation, check your JRE\");\n runTimeEx.initCause(ex);\n throw runTimeEx;\n }\n }\n", "label": 1} {"func1": " private void extractZipFile(String filename, JTextPane progressText) throws IOException {\n String destinationname = \"\";\n byte[] buf = new byte[1024];\n ZipInputStream zipinputstream = null;\n ZipEntry zipentry;\n zipinputstream = new ZipInputStream(new FileInputStream(filename));\n while ((zipentry = zipinputstream.getNextEntry()) != null) {\n String entryName = zipentry.getName();\n if (progressText != null) {\n progressText.setText(\"extracting \" + entryName);\n }\n int n;\n FileOutputStream fileoutputstream;\n if (zipentry.isDirectory()) {\n (new File(destinationname + entryName)).mkdir();\n continue;\n }\n fileoutputstream = new FileOutputStream(destinationname + entryName);\n while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n);\n fileoutputstream.close();\n zipinputstream.closeEntry();\n }\n if (progressText != null) {\n progressText.setText(\"Files extracted\");\n }\n zipinputstream.close();\n }\n", "func2": " public static void copyFile(File in, File out) throws Exception {\n FileChannel sourceChannel = null;\n FileChannel destinationChannel = null;\n try {\n sourceChannel = new FileInputStream(in).getChannel();\n destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n } finally {\n if (sourceChannel != null) sourceChannel.close();\n if (destinationChannel != null) destinationChannel.close();\n }\n }\n", "label": 1} {"func1": " public byte[] getDigest(OMAttribute attribute, String digestAlgorithm) throws OMException {\n byte[] digest = new byte[0];\n if (!(attribute.getLocalName().equals(\"xmlns\") || attribute.getLocalName().startsWith(\"xmlns:\"))) try {\n MessageDigest md = MessageDigest.getInstance(digestAlgorithm);\n md.update((byte) 0);\n md.update((byte) 0);\n md.update((byte) 0);\n md.update((byte) 2);\n md.update(getExpandedName(attribute).getBytes(\"UnicodeBigUnmarked\"));\n md.update((byte) 0);\n md.update((byte) 0);\n md.update(attribute.getAttributeValue().getBytes(\"UnicodeBigUnmarked\"));\n digest = md.digest();\n } catch (NoSuchAlgorithmException e) {\n throw new OMException(e);\n } catch (UnsupportedEncodingException e) {\n throw new OMException(e);\n }\n return digest;\n }\n", "func2": " public synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md = null;\n md = MessageDigest.getInstance(\"SHA\");\n md.update(plaintext.getBytes(\"UTF-8\"));\n byte raw[] = md.digest();\n String hash = (new BASE64Encoder()).encode(raw);\n return hash;\n }\n", "label": 1} {"func1": " private void copyFileTo(File destination) throws IOException {\n logger.fine(\"Copying from \" + destination + \"...\");\n FileChannel srcChannel = new FileInputStream(getAbsolutePath()).getChannel();\n logger.fine(\"...got source channel \" + srcChannel + \"...\");\n FileChannel destChannel = new FileOutputStream(new File(destination.getAbsolutePath())).getChannel();\n logger.fine(\"...got destination channel \" + destChannel + \"...\");\n logger.fine(\"...Got channels...\");\n destChannel.transferFrom(srcChannel, 0, srcChannel.size());\n logger.fine(\"...transferred.\");\n srcChannel.close();\n destChannel.close();\n }\n", "func2": " @Test\n public void testCopy_inputStreamToOutputStream() throws Exception {\n InputStream in = new ByteArrayInputStream(inData);\n in = new YellOnCloseInputStreamTest(in);\n ByteArrayOutputStream baout = new ByteArrayOutputStream();\n OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);\n int count = IOUtils.copy(in, out);\n assertTrue(\"Not all bytes were read\", in.available() == 0);\n assertEquals(\"Sizes differ\", inData.length, baout.size());\n assertTrue(\"Content differs\", Arrays.equals(inData, baout.toByteArray()));\n }\n", "label": 1} {"func1": " private void copyIconFiles(UmlClass clazz) {\n if (clazz.hasAnnotation(\"icon16\")) {\n String i16 = clazz.annotationValue(\"icon16\");\n String fileType = \".png\";\n if (i16.endsWith(\".jpg\")) fileType = \".jpg\";\n if (i16.endsWith(\".gif\")) fileType = \".gif\";\n String desti16 = output_dir + \"/../resources/images/\" + clazz.getName() + \"16\" + fileType;\n try {\n FileChannel src = new FileInputStream(i16).getChannel();\n FileChannel dst = new FileOutputStream(desti16).getChannel();\n dst.transferFrom(src, 0, src.size());\n src.close();\n dst.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n if (clazz.hasAnnotation(\"icon32\")) {\n String i32 = clazz.annotationValue(\"icon32\");\n String fileType = \".png\";\n if (i32.endsWith(\".jpg\")) fileType = \".jpg\";\n if (i32.endsWith(\".gif\")) fileType = \".gif\";\n String desti32 = output_dir + \"/../resources/images/\" + clazz.getName() + \"32\" + fileType;\n try {\n FileChannel src = new FileInputStream(i32).getChannel();\n FileChannel dst = new FileOutputStream(desti32).getChannel();\n dst.transferFrom(src, 0, src.size());\n src.close();\n dst.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n", "func2": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 1} {"func1": " public MotixFileItem(final InputStream is, final String name, final String contentType, final int index) throws IOException {\n this.name = name;\n this.contentType = contentType;\n this.index = index;\n this.extension = FilenameUtils.getExtension(this.name);\n this.isImage = ImageUtils.isImage(name);\n ArrayInputStream isAux = null;\n final ByteArrayOutputStream out = new ByteArrayOutputStream();\n try {\n IOUtils.copy(is, out);\n isAux = new ArrayInputStream(out.toByteArray());\n if (this.isImage) {\n this.bufferedImage = imaging.read(isAux);\n }\n } finally {\n IOUtils.closeQuietly(out);\n IOUtils.closeQuietly(isAux);\n }\n this.inputStream = new ArrayInputStream(out.toByteArray());\n }\n", "func2": " private void streamContains(String in, InputStream stream) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(stream, baos);\n byte[] bytes = baos.toByteArray();\n String cmp = new String(bytes, \"UTF-8\");\n assertTrue(cmp.contains(in));\n baos.close();\n }\n", "label": 1} {"func1": " public void hyperlinkUpdate(HyperlinkEvent e) {\n if (e.getEventType() == EventType.ACTIVATED) {\n try {\n URL url = e.getURL();\n InputStream stream = url.openStream();\n try {\n StringWriter writer = new StringWriter();\n IOUtils.copy(stream, writer, \"UTF-8\");\n JEditorPane editor = new JEditorPane(\"text/plain\", writer.toString());\n editor.setEditable(false);\n editor.setBackground(Color.WHITE);\n editor.setCaretPosition(0);\n editor.setPreferredSize(new Dimension(600, 400));\n String name = url.toString();\n name = name.substring(name.lastIndexOf('/') + 1);\n JDialog dialog = new JDialog(this, \"内容解析: \" + name);\n dialog.add(new JScrollPane(editor));\n dialog.pack();\n dialog.setVisible(true);\n } finally {\n stream.close();\n }\n } catch (IOException exception) {\n exception.printStackTrace();\n }\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " private static void copyFiles(String strPath, String dstPath) throws Exception {\n File src = new File(strPath);\n File dest = new File(dstPath);\n if (src.isDirectory()) {\n dest.mkdirs();\n String list[] = src.list();\n for (int i = 0; i < list.length; i++) {\n String dest1 = dest.getAbsolutePath() + \"\\\\\" + list[i];\n String src1 = src.getAbsolutePath() + \"\\\\\" + list[i];\n copyFiles(src1, dest1);\n }\n } else {\n FileChannel sourceChannel = new FileInputStream(src).getChannel();\n FileChannel targetChannel = new FileOutputStream(dest).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);\n sourceChannel.close();\n targetChannel.close();\n }\n }\n", "func2": " private void displayDiffResults() throws IOException {\n File outFile = File.createTempFile(\"diff\", \".htm\");\n outFile.deleteOnExit();\n FileOutputStream outStream = new FileOutputStream(outFile);\n BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream));\n out.write(\"LOC Differences\\n\" + SCRIPT + \"\\n\" + \"\\n\" + \"
\\n\");\n if (addedTable.length() > 0) {\n out.write(\"\" + \"\");\n out.write(addedTable.toString());\n out.write(\"
Files Added:AddType


\");\n }\n if (modifiedTable.length() > 0) {\n out.write(\"\" + \"\" + \"\");\n out.write(modifiedTable.toString());\n out.write(\"
Files Modified:BaseDelModAddTotalType


\");\n }\n if (deletedTable.length() > 0) {\n out.write(\"\" + \"\");\n out.write(deletedTable.toString());\n out.write(\"
Files Deleted:DelType


\");\n }\n out.write(\"\\n\");\n if (modifiedTable.length() > 0 || deletedTable.length() > 0) {\n out.write(\"\\n\\n\\n\\n\\n\");\n }\n out.write(\"\\n
Base: \");\n out.write(Long.toString(base));\n out.write(\"
Deleted: \");\n out.write(Long.toString(deleted));\n out.write(\"
Modified: \");\n out.write(Long.toString(modified));\n out.write(\"
Added: \");\n out.write(Long.toString(added));\n out.write(\"
New & Changed: \");\n out.write(Long.toString(added + modified));\n out.write(\"
Total: \");\n out.write(Long.toString(total));\n out.write(\"
\");\n redlinesOut.close();\n out.flush();\n InputStream redlines = new FileInputStream(redlinesTempFile);\n byte[] buffer = new byte[4096];\n int bytesRead;\n while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);\n outStream.write(\"\".getBytes());\n outStream.close();\n Browser.launch(outFile.toURL().toString());\n }\n", "label": 1} {"func1": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "func2": " public String execute() {\n String dir = \"E:\\\\ganymede_workspace\\\\training01\\\\web\\\\user_imgs\\\\\";\n HomeMap map = new HomeMap();\n map.setDescription(description);\n Integer id = homeMapDao.saveHomeMap(map);\n FileOutputStream fos;\n try {\n fos = new FileOutputStream(dir + id);\n IOUtils.copy(new FileInputStream(imageFile), fos);\n IOUtils.closeQuietly(fos);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return list();\n }\n", "label": 1} {"func1": " public PageLoader(String pageAddress) throws Exception {\n URL url = new URL(pageAddress);\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));\n inputLine = \"\";\n while (in.ready()) {\n inputLine = inputLine + in.readLine();\n }\n in.close();\n }\n", "func2": " private String getEncoding() throws IOException {\n BufferedReader reader = null;\n String encoding = null;\n try {\n URLConnection connection = url.openConnection();\n Map> header = connection.getHeaderFields();\n for (Map.Entry> entry : header.entrySet()) {\n if (entry.getKey().toLowerCase().equals(\"content-type\")) {\n String item = entry.getValue().toString().toLowerCase();\n if (item.contains(\"charset\")) {\n encoding = extractEncoding(item);\n if (encoding != null && !encoding.isEmpty()) return encoding;\n }\n }\n }\n reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.toLowerCase();\n if (line.contains(\"charset\") || line.contains(\"encoding\")) {\n encoding = extractEncoding(line);\n if (encoding != null && !encoding.isEmpty()) return encoding;\n }\n }\n return STANDARDENCODING;\n } finally {\n if (reader != null) reader.close();\n }\n }\n", "label": 1} {"func1": " public void createFile(File src, String filename) throws IOException {\n try {\n FileInputStream fis = new FileInputStream(src);\n OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);\n IOUtils.copy(fis, fos);\n fos.close();\n fis.close();\n } catch (ResourceManagerException e) {\n LOGGER.error(e);\n }\n }\n", "func2": " public String upload() {\n System.out.println(imgFile);\n String destDir = \"E:\\\\ganymede_workspace\\\\training01\\\\web\\\\user_imgs\\\\map_bg.jpg\";\n FileOutputStream fos;\n try {\n fos = new FileOutputStream(new File(destDir));\n IOUtils.copy(new FileInputStream(imgFile), fos);\n IOUtils.closeQuietly(fos);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"show\";\n }\n", "label": 1} {"func1": " public void createFile(File src, String filename) throws IOException {\n try {\n FileInputStream fis = new FileInputStream(src);\n OutputStream fos = this.fileResourceManager.writeResource(this.txId, filename);\n IOUtils.copy(fis, fos);\n fos.close();\n fis.close();\n } catch (ResourceManagerException e) {\n LOGGER.error(e);\n }\n }\n", "func2": " public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException {\n int k_blockSize = 1024;\n int byteCount;\n char[] buf = new char[k_blockSize];\n File ofp = new File(outFile);\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp));\n zos.setMethod(ZipOutputStream.DEFLATED);\n OutputStreamWriter osw = new OutputStreamWriter(zos, \"ISO-8859-1\");\n BufferedWriter bw = new BufferedWriter(osw);\n ZipEntry zot = null;\n File ifp = new File(inFile);\n ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp));\n InputStreamReader isr = new InputStreamReader(zis, \"ISO-8859-1\");\n BufferedReader br = new BufferedReader(isr);\n ZipEntry zit = null;\n while ((zit = zis.getNextEntry()) != null) {\n if (zit.getName().equals(\"content.xml\")) {\n continue;\n }\n zot = new ZipEntry(zit.getName());\n zos.putNextEntry(zot);\n while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount);\n bw.flush();\n zos.closeEntry();\n }\n zos.putNextEntry(new ZipEntry(\"content.xml\"));\n bw.flush();\n osw = new OutputStreamWriter(zos, \"UTF8\");\n bw = new BufferedWriter(osw);\n return bw;\n }\n", "label": 1} {"func1": " public String storeImage(InputStream inStream, String fileName, boolean resize) throws Exception {\n Calendar rightNow = Calendar.getInstance();\n String dayNamedFolderName = \"\" + rightNow.get(Calendar.YEAR) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.MONTH) + 1) + StringUtil.getPaddedIntWithZeros(2, rightNow.get(Calendar.DATE));\n String uploadDirRoot = props.getProperty(\"uploaded.files.root\");\n File file = new File(uploadDirRoot + System.getProperty(\"file.separator\") + dayNamedFolderName);\n if (!file.exists()) file.mkdirs();\n String extension = FilenameUtils.getExtension(fileName);\n String outFileName;\n if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEORIGINALFILENAME, \"true\"))) {\n outFileName = StringUtil.removeSpecChars(StringUtil.unaccent(FilenameUtils.getBaseName(fileName)));\n } else {\n outFileName = StringUtil.hash(fileName + Long.toString(System.currentTimeMillis()));\n }\n if (Boolean.parseBoolean(props.getPropertiesInstance().getProperty(IFConsts.USEEXTENSION, \"true\"))) {\n outFileName = outFileName + DOT + extension;\n }\n String outPathAndName = uploadDirRoot + System.getProperty(\"file.separator\") + dayNamedFolderName + System.getProperty(\"file.separator\") + props.getProperty(\"uploaded.files.prefix\") + outFileName;\n File uploadedFile = new File(outPathAndName);\n _logger.info(\"uploadedFile.getAbsolutePath() = {}\", uploadedFile.getAbsolutePath());\n uploadedFile.createNewFile();\n OutputStream outStream = new FileOutputStream(outPathAndName);\n IOUtils.copyLarge(inStream, outStream);\n IOUtils.closeQuietly(inStream);\n outStream.close();\n if (resize) {\n writeResizedImage(outPathAndName, extension, \"imgSize_xs\");\n writeResizedImage(outPathAndName, extension, \"imgSize_s\");\n writeResizedImage(outPathAndName, extension, \"imgSize_m\");\n writeResizedImage(outPathAndName, extension, \"imgSize_l\");\n writeResizedImage(outPathAndName, extension, \"imgSize_xl\");\n }\n String retVal = dayNamedFolderName + \"/\" + props.getProperty(\"uploaded.files.prefix\") + outFileName;\n return retVal;\n }\n", "func2": " public static void gzip() throws Exception {\n System.out.println(\"gzip()\");\n GZIPOutputStream zipout = new GZIPOutputStream(new FileOutputStream(\"/zip/myzip.gz\"));\n byte buffer[] = new byte[BLOCKSIZE];\n File dir = new File(\"/zip/covers\");\n System.out.println(\"Dir '\" + dir.getAbsolutePath() + \"' exists: \" + dir.exists());\n FileInputStream in = new FileInputStream(dir);\n for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length);\n in.close();\n zipout.close();\n }\n", "label": 1} {"func1": " private static boolean genCustRatingFileAndMovieIndexFile(String completePath, String masterFile, String CustRatingFileName, String MovieIndexFileName) {\n try {\n File inFile = new File(completePath + fSep + \"SmartGRAPE\" + fSep + masterFile);\n FileChannel inC = new FileInputStream(inFile).getChannel();\n File outFile1 = new File(completePath + fSep + \"SmartGRAPE\" + fSep + MovieIndexFileName);\n FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel();\n File outFile2 = new File(completePath + fSep + \"SmartGRAPE\" + fSep + CustRatingFileName);\n FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel();\n int fileSize = (int) inC.size();\n int totalNoDataRows = fileSize / 7;\n ByteBuffer mappedBuffer = inC.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);\n int startIndex = 1, count = 0;\n short currentMovie = 1;\n while (mappedBuffer.hasRemaining()) {\n count++;\n short movieName = mappedBuffer.getShort();\n int customer = mappedBuffer.getInt();\n byte rating = mappedBuffer.get();\n if (movieName != currentMovie) {\n ByteBuffer outBuf1 = ByteBuffer.allocate(10);\n outBuf1.putShort(currentMovie);\n outBuf1.putInt(startIndex);\n outBuf1.putInt(count - 1);\n outBuf1.flip();\n outC1.write(outBuf1);\n currentMovie = movieName;\n startIndex = count;\n }\n ByteBuffer outBuf2 = ByteBuffer.allocate(5);\n outBuf2.putInt(customer);\n outBuf2.put(rating);\n outBuf2.flip();\n outC2.write(outBuf2);\n }\n ByteBuffer endOfIndexFile = ByteBuffer.allocate(10);\n endOfIndexFile.putShort(currentMovie);\n endOfIndexFile.putInt(startIndex);\n endOfIndexFile.putInt(100480506);\n endOfIndexFile.flip();\n outC1.write(endOfIndexFile);\n outC1.close();\n outC2.close();\n return true;\n } catch (IOException e) {\n System.err.println(e);\n return false;\n }\n }\n", "func2": " public String[][] getProjectTreeData() {\n String[][] treeData = null;\n String filename = dms_home + FS + \"temp\" + FS + username + \"adminprojects.xml\";\n String urlString = dms_url + \"/servlet/com.ufnasoft.dms.server.ServerGetAdminProjects\";\n try {\n String urldata = urlString + \"?username=\" + URLEncoder.encode(username, \"UTF-8\") + \"&key=\" + URLEncoder.encode(key, \"UTF-8\") + \"&filename=\" + URLEncoder.encode(username, \"UTF-8\") + \"adminprojects.xml\";\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setValidating(false);\n DocumentBuilder parser = factory.newDocumentBuilder();\n URL u = new URL(urldata);\n DataInputStream is = new DataInputStream(u.openStream());\n FileOutputStream os = new FileOutputStream(filename);\n int iBufSize = is.available();\n byte inBuf[] = new byte[20000 * 1024];\n int iNumRead;\n while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead);\n os.close();\n is.close();\n File f = new File(filename);\n InputStream inputstream = new FileInputStream(f);\n Document document = parser.parse(inputstream);\n NodeList nodelist = document.getElementsByTagName(\"proj\");\n int num = nodelist.getLength();\n treeData = new String[num][3];\n for (int i = 0; i < num; i++) {\n treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), \"pid\"));\n treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), \"ppid\"));\n treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), \"p\"));\n }\n } catch (MalformedURLException ex) {\n System.out.println(ex);\n } catch (ParserConfigurationException ex) {\n System.out.println(ex);\n } catch (NullPointerException e) {\n } catch (Exception ex) {\n System.out.println(ex);\n }\n return treeData;\n }\n", "label": 1} {"func1": " private void checkInputStream(InputStream in, byte[] cmp, boolean all) throws IOException {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n IOUtils.copy(in, stream);\n byte[] out = stream.toByteArray();\n if (all) assertEquals(cmp.length, out.length);\n for (int i = 0; i < cmp.length; i++) assertEquals(cmp[i], out[i]);\n }\n", "func2": " private void copyFileTo(File destination) throws IOException {\n logger.fine(\"Copying from \" + destination + \"...\");\n FileChannel srcChannel = new FileInputStream(getAbsolutePath()).getChannel();\n logger.fine(\"...got source channel \" + srcChannel + \"...\");\n FileChannel destChannel = new FileOutputStream(new File(destination.getAbsolutePath())).getChannel();\n logger.fine(\"...got destination channel \" + destChannel + \"...\");\n logger.fine(\"...Got channels...\");\n destChannel.transferFrom(srcChannel, 0, srcChannel.size());\n logger.fine(\"...transferred.\");\n srcChannel.close();\n destChannel.close();\n }\n", "label": 1} {"func1": " public static void copy(String from_name, String to_name) throws IOException {\n File from_file = new File(from_name);\n File to_file = new File(to_name);\n if (!from_file.exists()) abort(\"FileCopy: no such source file: \" + from_name);\n if (!from_file.isFile()) abort(\"FileCopy: can't copy directory: \" + from_name);\n if (!from_file.canRead()) abort(\"FileCopy: source file is unreadable: \" + from_name);\n if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName());\n if (to_file.exists()) {\n if (!to_file.canWrite()) abort(\"FileCopy: destination file is unwriteable: \" + to_name);\n } else {\n String parent = to_file.getParent();\n if (parent == null) parent = System.getProperty(\"user.dir\");\n File dir = new File(parent);\n if (!dir.exists()) abort(\"FileCopy: destination directory doesn't exist: \" + parent);\n if (dir.isFile()) abort(\"FileCopy: destination is not a directory: \" + parent);\n if (!dir.canWrite()) abort(\"FileCopy: destination directory is unwriteable: \" + parent);\n }\n FileInputStream from = null;\n FileOutputStream to = null;\n try {\n from = new FileInputStream(from_file);\n to = new FileOutputStream(to_file);\n byte[] buffer = new byte[4096];\n int bytes_read;\n while ((bytes_read = from.read(buffer)) != -1) {\n to.write(buffer, 0, bytes_read);\n }\n } finally {\n if (from != null) {\n try {\n from.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n if (to != null) {\n try {\n to.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n", "func2": " @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String rewrittenQueryString = URLDecoder.decode(request.getRequestURI(), \"UTF-8\").replaceFirst(\"^.*?\\\\/(id:.*)\\\\/.*?$\", \"$1\");\n logger.debug(\"rewrittenQueryString: \" + rewrittenQueryString);\n URL rewrittenUrl = new URL(fedoraUrl + rewrittenQueryString);\n logger.debug(\"rewrittenUrl: \" + rewrittenUrl.getProtocol() + \"://\" + rewrittenUrl.getHost() + \":\" + rewrittenUrl.getPort() + rewrittenUrl.getFile());\n HttpURLConnection httpURLConnection = (HttpURLConnection) rewrittenUrl.openConnection();\n HttpURLConnection.setFollowRedirects(false);\n httpURLConnection.connect();\n response.setStatus(httpURLConnection.getResponseCode());\n logger.debug(\"[status=\" + httpURLConnection.getResponseCode() + \"]\");\n logger.debug(\"[headers]\");\n for (Entry> header : httpURLConnection.getHeaderFields().entrySet()) {\n if (header.getKey() != null) {\n for (String value : header.getValue()) {\n if (value != null) {\n logger.debug(header.getKey() + \": \" + value);\n if (!header.getKey().equals(\"Server\") && !header.getKey().equals(\"Transfer-Encoding\")) {\n response.addHeader(header.getKey(), value);\n }\n }\n }\n }\n }\n logger.debug(\"[/headers]\");\n InputStream inputStream = httpURLConnection.getInputStream();\n OutputStream outputStream = response.getOutputStream();\n IOUtils.copy(inputStream, outputStream);\n }\n", "label": 1} {"func1": " public String generateToken(String code) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA1\");\n md.update(code.getBytes());\n byte[] bytes = md.digest();\n return toHex(bytes);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(\"SHA1 missing\");\n }\n }\n", "func2": " static Cipher createCipher(String passwd, int mode) throws Exception {\n PBEKeySpec keySpec = new PBEKeySpec(passwd.toCharArray());\n SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(\"PBEWithMD5AndDES\");\n SecretKey key = keyFactory.generateSecret(keySpec);\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(\"input\".getBytes());\n byte[] digest = md.digest();\n byte[] salt = new byte[8];\n for (int i = 0; i < 8; ++i) salt[i] = digest[i];\n PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);\n Cipher cipher = Cipher.getInstance(\"PBEWithMD5AndDES\");\n cipher.init(mode, key, paramSpec);\n return cipher;\n }\n", "label": 1} {"func1": " public MotixFileItem(final InputStream is, final String name, final String contentType, final int index) throws IOException {\n this.name = name;\n this.contentType = contentType;\n this.index = index;\n this.extension = FilenameUtils.getExtension(this.name);\n this.isImage = ImageUtils.isImage(name);\n ArrayInputStream isAux = null;\n final ByteArrayOutputStream out = new ByteArrayOutputStream();\n try {\n IOUtils.copy(is, out);\n isAux = new ArrayInputStream(out.toByteArray());\n if (this.isImage) {\n this.bufferedImage = imaging.read(isAux);\n }\n } finally {\n IOUtils.closeQuietly(out);\n IOUtils.closeQuietly(isAux);\n }\n this.inputStream = new ArrayInputStream(out.toByteArray());\n }\n", "func2": " public static void copyFileTo(String src, String dest) throws FileNotFoundException, IOException {\n File destFile = new File(dest);\n InputStream in = new FileInputStream(new File(src));\n OutputStream out = new FileOutputStream(destFile);\n byte buf[] = new byte[1024];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n }\n", "label": 1} {"func1": " private JButton getButtonSonido() {\n if (buttonSonido == null) {\n buttonSonido = new JButton();\n buttonSonido.setText(Messages.getString(\"gui.AdministracionResorces.15\"));\n buttonSonido.setIcon(new ImageIcon(getClass().getResource(\"/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png\")));\n buttonSonido.addActionListener(new java.awt.event.ActionListener() {\n\n public void actionPerformed(java.awt.event.ActionEvent e) {\n JFileChooser fc = new JFileChooser();\n fc.addChoosableFileFilter(new SoundFilter());\n int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString(\"gui.AdministracionResorces.17\"));\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File file = fc.getSelectedFile();\n String rutaGlobal = System.getProperty(\"user.dir\") + \"/\" + rutaDatos + \"sonidos/\" + file.getName();\n String rutaRelativa = rutaDatos + \"sonidos/\" + file.getName();\n try {\n FileInputStream fis = new FileInputStream(file);\n FileOutputStream fos = new FileOutputStream(rutaGlobal, true);\n FileChannel canalFuente = fis.getChannel();\n FileChannel canalDestino = fos.getChannel();\n canalFuente.transferTo(0, canalFuente.size(), canalDestino);\n fis.close();\n fos.close();\n imagen.setSonidoURL(rutaRelativa);\n System.out.println(rutaGlobal + \" \" + rutaRelativa);\n buttonSonido.setIcon(new ImageIcon(getClass().getResource(\"/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png\")));\n gui.getAudio().reproduceAudio(imagen);\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n } else {\n }\n }\n });\n }\n return buttonSonido;\n }\n", "func2": " @Test\n public void testTrainingBackprop() throws IOException {\n File temp = File.createTempFile(\"fannj_\", \".tmp\");\n temp.deleteOnExit();\n IOUtils.copy(this.getClass().getResourceAsStream(\"xor.data\"), new FileOutputStream(temp));\n List layers = new ArrayList();\n layers.add(Layer.create(2));\n layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n layers.add(Layer.create(2, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n Fann fann = new Fann(layers);\n Trainer trainer = new Trainer(fann);\n trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_INCREMENTAL);\n float desiredError = .001f;\n float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);\n assertTrue(\"\" + mse, mse <= desiredError);\n }\n", "label": 1} {"func1": " public static byte[] hash(final byte[] saltBefore, final String content, final byte[] saltAfter, final int repeatedHashingCount) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n if (content == null) return null;\n final MessageDigest digest = MessageDigest.getInstance(DIGEST);\n if (digestLength == -1) digestLength = digest.getDigestLength();\n for (int i = 0; i < repeatedHashingCount; i++) {\n if (i > 0) digest.update(digest.digest());\n digest.update(saltBefore);\n digest.update(content.getBytes(WebCastellumFilter.DEFAULT_CHARACTER_ENCODING));\n digest.update(saltAfter);\n }\n return digest.digest();\n }\n", "func2": " public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"SHA-1\");\n byte[] sha1hash = new byte[40];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n sha1hash = md.digest();\n return convertToHex(sha1hash);\n }\n", "label": 1} {"func1": " protected static final byte[] digest(String s) {\n byte[] ret = null;\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(s.getBytes());\n ret = md.digest();\n } catch (NoSuchAlgorithmException e) {\n System.err.println(\"no message digest algorithm available!\");\n System.exit(1);\n }\n return ret;\n }\n", "func2": " public static String mysqlPasswordHash(String string) {\n try {\n MessageDigest digest = MessageDigest.getInstance(HashAlgorithms.SHA1);\n try {\n digest.update(string.getBytes(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n }\n byte[] encodedPassword = digest.digest();\n digest.update(encodedPassword);\n encodedPassword = digest.digest();\n String hash = new BigInteger(1, encodedPassword).toString(16).toUpperCase();\n while (hash.length() < 40) {\n hash = \"0\" + hash;\n }\n return \"*\" + hash;\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n", "label": 1} {"func1": " public String getPasswordMD5() {\n try {\n MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n algorithm.reset();\n algorithm.update(password.getBytes());\n byte messageDigest[] = algorithm.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n hexString.append(Integer.toHexString(0xFF & messageDigest[i]));\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException nsae) {\n }\n return null;\n }\n", "func2": " public static String md5String(String str) {\n try {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n md.update(str.getBytes());\n byte[] hash = md.digest();\n final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n StringBuffer res = new StringBuffer();\n for (int i = 0; i < hash.length; i++) {\n res.append(hexChars[(0xF0 & hash[i]) >> 4]);\n res.append(hexChars[0x0F & hash[i]]);\n }\n return res.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n }\n", "label": 1} {"func1": " public void transport(File file) throws TransportException {\n if (file.exists()) {\n if (file.isDirectory()) {\n File[] files = file.listFiles();\n for (int i = 0; i < files.length; i++) {\n transport(file);\n }\n } else if (file.isFile()) {\n try {\n FileChannel inChannel = new FileInputStream(file).getChannel();\n FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n log.error(\"File transfer failed\", e);\n }\n }\n }\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public static String generateHash(String key) {\n key += \"use_your_key_here\";\n MessageDigest md;\n try {\n md = java.security.MessageDigest.getInstance(\"MD5\");\n md.reset();\n md.update(key.getBytes());\n byte[] bytes = md.digest();\n StringBuffer buff = new StringBuffer();\n for (int l = 0; l < bytes.length; l++) {\n String hx = Integer.toHexString(0xFF & bytes[l]);\n if (hx.length() == 1) buff.append(\"0\");\n buff.append(hx);\n }\n return buff.toString().trim();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n return null;\n }\n", "func2": " private static String encrypt(String algorithm, String password, Long digestSeed) {\n try {\n MessageDigest digest = MessageDigest.getInstance(algorithm);\n digest.reset();\n digest.update(password.getBytes(\"UTF-8\"));\n digest.update(digestSeed.toString().getBytes(\"UTF-8\"));\n byte[] messageDigest = digest.digest();\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4));\n hexString.append(Integer.toHexString(0x0f & messageDigest[i]));\n }\n return hexString.toString();\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(e);\n } catch (NullPointerException e) {\n return new StringBuffer().toString();\n }\n }\n", "label": 1} {"func1": " public static void copyFile(File dest, File src) throws IOException {\n FileChannel srcChannel = new FileInputStream(src).getChannel();\n FileChannel dstChannel = new FileOutputStream(dest).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n }\n", "func2": " public static void createTar(File directoryToPack, File targetTarFile) throws IOException {\n if (directoryToPack == null) {\n throw new NullPointerException(\"The parameter 'directoryToPack' must not be null\");\n }\n if (targetTarFile == null) {\n throw new NullPointerException(\"The parameter 'targetTarFile' must not be null\");\n }\n if (!directoryToPack.exists() || !directoryToPack.isDirectory()) {\n throw new IllegalArgumentException(\"The target file '\" + directoryToPack + \"' does not exist or is not a directory.\");\n }\n if (targetTarFile.exists()) {\n log.warn(\"The target file '\" + targetTarFile + \"' already exists. Will overwrite\");\n }\n log.debug(\"Creating tar from all files in directory '\" + directoryToPack + \"'\");\n byte buffer[] = new byte[BUFFER_SIZE];\n FileOutputStream targetOutput = new FileOutputStream(targetTarFile);\n TarOutputStream targetOutputTar = new TarOutputStream(targetOutput);\n try {\n List fileList = collectFiles(directoryToPack);\n for (Iterator iter = fileList.iterator(); iter.hasNext(); ) {\n File file = iter.next();\n if (file == null || !file.exists() || file.isDirectory()) {\n log.info(\"The file '\" + file + \"' is ignored - is a directory or non-existent\");\n continue;\n }\n if (file.equals(targetTarFile)) {\n log.debug(\"Skipping file: '\" + file + \"' - is the tar file itself\");\n continue;\n }\n log.debug(\"Adding to archive: file='\" + file + \"', archive='\" + targetTarFile + \"'\");\n String filePathInTar = getFilePathInTar(file, directoryToPack);\n log.debug(\"File path in tar: '\" + filePathInTar + \"' (file=\" + file + \")\");\n TarEntry tarAdd = new TarEntry(file);\n tarAdd.setModTime(file.lastModified());\n tarAdd.setName(filePathInTar);\n targetOutputTar.putNextEntry(tarAdd);\n if (file.isFile()) {\n FileInputStream in = new FileInputStream(file);\n try {\n while (true) {\n int nRead = in.read(buffer, 0, buffer.length);\n if (nRead <= 0) break;\n targetOutputTar.write(buffer, 0, nRead);\n }\n } finally {\n StreamUtil.tryCloseStream(in);\n }\n }\n targetOutputTar.closeEntry();\n }\n } finally {\n StreamUtil.tryCloseStream(targetOutputTar);\n StreamUtil.tryCloseStream(targetOutput);\n }\n log.info(\"Tar Archive created successfully '\" + targetTarFile + \"'\");\n }\n", "label": 1} {"func1": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "func2": " private boolean setPayload() throws IOException {\n if (Index < Headers.length) {\n FileOutputStream fos = new FileOutputStream(Headers[Index], true);\n FileInputStream fis = new FileInputStream(HeadlessData);\n FileChannel fic = fis.getChannel();\n FileChannel foc = fos.getChannel();\n fic.transferTo(0, fic.size(), foc);\n fic.close();\n foc.close();\n setDestination(Destinations[Index]);\n setPayload(Headers[Index]);\n Index++;\n return true;\n }\n return false;\n }\n", "label": 1} {"func1": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "func2": " @Override\n public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {\n if (query == null) {\n throw new NotConnectedException();\n }\n ArrayList recipients = query.getUserManager().getTecMail();\n Mail mail = new Mail(recipients);\n try {\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(\"log/ossobooklog.zip\"));\n FileInputStream fis = new FileInputStream(\"log/ossobook.log\");\n ZipEntry entry = new ZipEntry(\"ossobook.log\");\n zos.putNextEntry(entry);\n byte[] buffer = new byte[8192];\n int read = 0;\n while ((read = fis.read(buffer, 0, 1024)) != -1) {\n zos.write(buffer, 0, read);\n }\n zos.closeEntry();\n fis.close();\n zos.close();\n mail.sendErrorMessage(message, new File(\"log/ossobooklog.zip\"), getUserName());\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "label": 1} {"func1": " public void update(String channelPath, String dataField, String fatherDocId) {\n String sqlInitial = \"select uri from t_ip_doc_res where doc_id = '\" + fatherDocId + \"' and type=\" + \" '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n String sqlsortURL = \"update t_ip_doc_res set uri = ? where doc_id = '\" + fatherDocId + \"' \" + \" and type = '\" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + \"' \";\n Connection conn = null;\n ResultSet rs = null;\n PreparedStatement ps = null;\n try {\n dbo = (ERDBOperation) createDBOperation();\n String url = \"\";\n boolean flag = true;\n StringTokenizer st = null;\n conn = dbo.getConnection();\n conn.setAutoCommit(false);\n ps = conn.prepareStatement(sqlInitial);\n rs = ps.executeQuery();\n if (rs.next()) url = rs.getString(1);\n if (!url.equals(\"\")) {\n st = new StringTokenizer(url, \",\");\n String sortDocId = \"\";\n while (st.hasMoreTokens()) {\n if (flag) {\n sortDocId = \"'\" + st.nextToken() + \"'\";\n flag = false;\n } else {\n sortDocId = sortDocId + \",\" + \"'\" + st.nextToken() + \"'\";\n }\n }\n String sqlsort = \"select id from t_ip_doc where id in (\" + sortDocId + \") order by \" + dataField;\n ps = conn.prepareStatement(sqlsort);\n rs = ps.executeQuery();\n String sortURL = \"\";\n boolean sortflag = true;\n while (rs.next()) {\n if (sortflag) {\n sortURL = rs.getString(1);\n sortflag = false;\n } else {\n sortURL = sortURL + \",\" + rs.getString(1);\n }\n }\n ps = conn.prepareStatement(sqlsortURL);\n ps.setString(1, sortURL);\n ps.executeUpdate();\n }\n conn.commit();\n } catch (Exception e) {\n e.printStackTrace();\n try {\n conn.rollback();\n } catch (SQLException e1) {\n e1.printStackTrace();\n }\n } finally {\n close(rs, null, ps, conn, dbo);\n }\n }\n", "func2": " public void deleteAuthors() throws Exception {\n if (proposalIds.equals(\"\") || usrIds.equals(\"\")) throw new Exception(\"No proposal or author selected.\");\n String[] pids = proposalIds.split(\",\");\n String[] uids = usrIds.split(\",\");\n int pnum = pids.length;\n int unum = uids.length;\n if (pnum == 0 || unum == 0) throw new Exception(\"No proposal or author selected.\");\n int i, j;\n PreparedStatement prepStmt = null;\n try {\n con = database.getConnection();\n con.setAutoCommit(false);\n String pStr = \"delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?\";\n prepStmt = con.prepareStatement(pStr);\n for (i = 0; i < pnum; i++) {\n for (j = 0; j < unum; j++) {\n if (!uids[j].equals(userId)) {\n prepStmt.setString(1, pids[i]);\n prepStmt.setString(2, uids[j]);\n prepStmt.executeUpdate();\n }\n }\n }\n con.commit();\n } catch (Exception e) {\n if (!con.isClosed()) {\n con.rollback();\n prepStmt.close();\n con.close();\n }\n throw e;\n }\n }\n", "label": 1} {"func1": " public static boolean decodeFileToFile(final String infile, final String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n final byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (final java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (final Exception exc) {\n }\n try {\n out.close();\n } catch (final Exception exc) {\n }\n }\n return success;\n }\n", "func2": " public void write() throws IOException {\n JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);\n if (includeJars != null) {\n HashSet allEntries = new HashSet(includeJars);\n if (!ignoreDependencies) expandSet(allEntries);\n for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {\n JarFile jar = getJarFile(iterator.next());\n Enumeration jarEntries = jar.entries();\n while (jarEntries.hasMoreElements()) {\n ZipEntry o1 = (ZipEntry) jarEntries.nextElement();\n if (o1.getName().equalsIgnoreCase(\"META-INF/MANIFEST.MF\") || o1.getSize() <= 0) continue;\n jarOut.putNextEntry(o1);\n InputStream entryStream = jar.getInputStream(o1);\n IOUtils.copy(entryStream, jarOut);\n jarOut.closeEntry();\n }\n }\n }\n jarOut.finish();\n jarOut.close();\n }\n", "label": 1} {"func1": " public static String encrypt(String text) throws NoSuchAlgorithmException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"MD5\");\n byte[] md5hash = new byte[32];\n try {\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n md5hash = md.digest();\n return convertToHex(md5hash);\n }\n", "func2": " public static String generate(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {\n MessageDigest md;\n md = MessageDigest.getInstance(\"SHA-1\");\n byte[] sha1hash = new byte[40];\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n sha1hash = md.digest();\n return convertToHex(sha1hash);\n }\n", "label": 1} {"func1": " public void patch() throws IOException {\n if (mods.isEmpty()) {\n return;\n }\n IOUtils.copy(new FileInputStream(Paths.getMinecraftJarPath()), new FileOutputStream(new File(Paths.getMinecraftBackupPath())));\n JarFile mcjar = new JarFile(Paths.getMinecraftJarPath());\n }\n", "func2": " public static void copyFile(File src, File dest) throws IOException {\n FileInputStream fis = new FileInputStream(src);\n FileOutputStream fos = new FileOutputStream(dest);\n java.nio.channels.FileChannel channelSrc = fis.getChannel();\n java.nio.channels.FileChannel channelDest = fos.getChannel();\n channelSrc.transferTo(0, channelSrc.size(), channelDest);\n fis.close();\n fos.close();\n }\n", "label": 1} {"func1": " public static void unzipModel(String filename, String tempdir) throws EDITSException {\n try {\n BufferedOutputStream dest = null;\n FileInputStream fis = new FileInputStream(filename);\n int BUFFER = 2048;\n ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));\n ZipEntry entry;\n while ((entry = zis.getNextEntry()) != null) {\n int count;\n byte data[] = new byte[BUFFER];\n FileOutputStream fos = new FileOutputStream(tempdir + entry.getName());\n dest = new BufferedOutputStream(fos, BUFFER);\n while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count);\n dest.flush();\n dest.close();\n }\n zis.close();\n } catch (Exception e) {\n throw new EDITSException(\"Can not expand model in \\\"\" + tempdir + \"\\\" because:\\n\" + e.getMessage());\n }\n }\n", "func2": " public boolean clonarFichero(FileInputStream rutaFicheroOrigen, String rutaFicheroDestino) {\n System.out.println(\"\");\n boolean estado = false;\n try {\n FileOutputStream salida = new FileOutputStream(rutaFicheroDestino);\n FileChannel canalOrigen = rutaFicheroOrigen.getChannel();\n FileChannel canalDestino = salida.getChannel();\n canalOrigen.transferTo(0, canalOrigen.size(), canalDestino);\n rutaFicheroOrigen.close();\n salida.close();\n estado = true;\n } catch (IOException e) {\n System.out.println(\"No se encontro el archivo\");\n e.printStackTrace();\n estado = false;\n }\n return estado;\n }\n", "label": 1} {"func1": " @Test\n public void testCopy_readerToOutputStream_Encoding() throws Exception {\n InputStream in = new ByteArrayInputStream(inData);\n in = new YellOnCloseInputStreamTest(in);\n Reader reader = new InputStreamReader(in, \"US-ASCII\");\n ByteArrayOutputStream baout = new ByteArrayOutputStream();\n OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);\n IOUtils.copy(reader, out, \"UTF16\");\n byte[] bytes = baout.toByteArray();\n bytes = new String(bytes, \"UTF16\").getBytes(\"US-ASCII\");\n assertTrue(\"Content differs\", Arrays.equals(inData, bytes));\n }\n", "func2": " public void logging() throws Fault {\n final InterceptorWrapper wrap = new InterceptorWrapper(message);\n final LoggingMessage buffer = new LoggingMessage(\"Inbound Message\\n----------------------------\");\n String encoding = (String) wrap.getEncoding();\n if (encoding != null) {\n buffer.getEncoding().append(encoding);\n }\n Object headers = wrap.getProtocolHeaders();\n if (headers != null) {\n buffer.getHeader().append(headers);\n }\n InputStream is = (InputStream) wrap.getContent(InputStream.class);\n if (is != null) {\n CachedOutputStream bos = new CachedOutputStream();\n try {\n IOUtils.copy(is, bos);\n bos.flush();\n is.close();\n this.message.setContent(InputStream.class, bos.getInputStream());\n if (bos.getTempFile() != null) {\n logger.error(\"\\nMessage (saved to tmp file):\\n\");\n logger.error(\"Filename: \" + bos.getTempFile().getAbsolutePath() + \"\\n\");\n }\n if (bos.size() > limit) {\n logger.error(\"(message truncated to \" + limit + \" bytes)\\n\");\n }\n bos.writeCacheTo(buffer.getPayload(), limit);\n bos.close();\n } catch (IOException e) {\n throw new Fault(e);\n }\n }\n logger.debug(\"Message received :\\n\" + buffer.getPayload().toString());\n }\n", "label": 1} {"func1": " public static void writeFileToFile(File fin, File fout, boolean append) throws IOException {\n FileChannel inChannel = new FileInputStream(fin).getChannel();\n FileChannel outChannel = new FileOutputStream(fout, append).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } finally {\n if (inChannel != null) try {\n inChannel.close();\n } catch (IOException ex) {\n }\n if (outChannel != null) try {\n outChannel.close();\n } catch (IOException ex) {\n }\n }\n }\n", "func2": " public static void copyFile(File src, File dst) throws IOException {\n try {\n InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dst);\n byte[] buf = new byte[TEMP_FILE_BUFFER_SIZE];\n int len;\n while ((len = in.read(buf)) > 0) out.write(buf, 0, len);\n in.close();\n out.close();\n } catch (FileNotFoundException e1) {\n MLUtil.runtimeError(e1, src.toString());\n } catch (IOException e2) {\n MLUtil.runtimeError(e2, src.toString());\n }\n }\n", "label": 1} {"func1": " public static final synchronized String hash(String data) {\n if (digest == null) {\n try {\n digest = MessageDigest.getInstance(\"MD5\");\n } catch (NoSuchAlgorithmException nsae) {\n log.error(\"Failed to load the MD5 MessageDigest. \" + \"Jive will be unable to function normally.\", nsae);\n }\n }\n try {\n digest.update(data.getBytes(\"utf-8\"));\n } catch (UnsupportedEncodingException e) {\n log.error(e);\n }\n return encodeHex(digest.digest());\n }\n", "func2": " public static final String calculate(File f) {\n MessageDigest md;\n BufferedReader rd;\n StringBuffer buffer = new StringBuffer(\"\");\n try {\n rd = new BufferedReader(new FileReader(f));\n md = MessageDigest.getInstance(\"SHA\");\n String line = \"\";\n while ((line = rd.readLine()) != null) buffer.append(line);\n md.update(buffer.toString().getBytes());\n byte[] digest = md.digest();\n String result = \"\";\n for (byte b : digest) result += String.format(\"%h\", b & 0xFF);\n return result;\n } catch (Exception ex) {\n ex.printStackTrace();\n return \"\";\n }\n }\n", "label": 1} {"func1": " public static void copyFile(File srcFile, File destFile) throws IOException {\n InputStream src = new FileInputStream(srcFile);\n OutputStream dest = new FileOutputStream(destFile);\n byte buffer[] = new byte[1024];\n int read = 1;\n while (read > 0) {\n read = src.read(buffer);\n if (read > 0) {\n dest.write(buffer, 0, read);\n }\n }\n src.close();\n dest.close();\n }\n", "func2": " public static void copy(File srcPath, File dstPath) throws IOException {\n if (srcPath.isDirectory()) {\n if (!dstPath.exists()) {\n boolean result = dstPath.mkdir();\n if (!result) throw new IOException(\"Unable to create directoy: \" + dstPath);\n }\n String[] files = srcPath.list();\n for (String file : files) {\n copy(new File(srcPath, file), new File(dstPath, file));\n }\n } else {\n if (srcPath.exists()) {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(srcPath).getChannel();\n out = new FileOutputStream(dstPath).getChannel();\n long size = in.size();\n MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);\n out.write(buf);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n }\n }\n", "label": 1} {"func1": " protected static void clearTables() throws SQLException {\n Connection conn = null;\n Statement stmt = null;\n try {\n conn = FidoDataSource.getConnection();\n conn.setAutoCommit(false);\n stmt = conn.createStatement();\n ClearData.clearTables(stmt);\n stmt.executeUpdate(\"delete from Objects\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (1, 'Money value')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (2, 'Date')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (3, 'Unix path')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (4, 'Dos path')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (5, 'Time')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (6, 'IP address')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (7, 'Internet hostname')\");\n stmt.executeUpdate(\"insert into Objects (ObjectId, Description) values (8, 'Number')\");\n conn.commit();\n } catch (SQLException e) {\n if (conn != null) conn.rollback();\n throw e;\n } finally {\n if (stmt != null) stmt.close();\n if (conn != null) conn.close();\n }\n }\n", "func2": " public boolean setUpdateCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) {\n boolean update = false;\n try {\n stm = conexion.prepareStatement(\"update clientes set nombre='\" + nombre.toUpperCase().trim() + \"' , paterno='\" + paterno.toUpperCase().trim() + \"' ,\" + \"materno='\" + materno.toUpperCase().trim() + \"',ocupacion='\" + ocupacion.toUpperCase().trim() + \"',rfc='\" + rfc.trim() + \"' where IDcliente ='\" + IDcliente + \"' \");\n stm.executeUpdate();\n conexion.commit();\n update = true;\n } catch (SQLException e) {\n System.out.println(\"error al actualizar registro en la tabla clientes \" + e.getMessage());\n try {\n conexion.rollback();\n } catch (SQLException ee) {\n System.out.println(ee.getMessage());\n }\n return update = false;\n }\n return update;\n }\n", "label": 1} {"func1": " public void loadSourceCode() {\n int length = MAX_SOURCE_LENGTH;\n try {\n File file = new File(filename);\n length = (int) file.length();\n } catch (SecurityException ex) {\n }\n char[] buff = new char[length];\n InputStream is;\n InputStreamReader isr;\n CodeViewer cv = new CodeViewer();\n URL url;\n try {\n url = getClass().getResource(filename);\n is = url.openStream();\n isr = new InputStreamReader(is);\n BufferedReader reader = new BufferedReader(isr);\n sourceCode = new String(\"
\");\n            String line = reader.readLine();\n            while (line != null) {\n                sourceCode += cv.syntaxHighlight(line) + \" \\n \";\n                line = reader.readLine();\n            }\n            sourceCode += \"
\";\n } catch (Exception ex) {\n sourceCode = getString(\"SourceCode.error\");\n }\n }\n", "func2": " public void init(ServletContext context) throws ScratchException {\n try {\n log.debug(\"Attempting to load Controllers from file: \" + REGISTRY_FILENAME);\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration urls = classLoader.getResources(REGISTRY_FILENAME);\n while (urls.hasMoreElements()) {\n URL url = urls.nextElement();\n log.debug(\"Found: \" + url);\n BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));\n String className = null;\n while ((className = reader.readLine()) != null) {\n className = className.trim();\n if (!\"\".equals(className) && !className.startsWith(\"#\")) {\n log.debug(\"Found class: \" + className);\n Class clazz = classLoader.loadClass(className);\n addClass(clazz);\n }\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n log.error(e);\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n log.error(e);\n }\n }\n", "label": 1} {"func1": " public static void copy(File sourceFile, File destinationFile) {\n try {\n if (((sourceFile == null) && (destinationFile == null)) || ((sourceFile == null) || (destinationFile == null))) {\n System.out.println(\"sourceFile & destinationFile is null\");\n System.exit(-1);\n }\n if (sourceFile.isDirectory()) {\n File[] tmp = sourceFile.listFiles();\n File f;\n for (int i = 0; i < tmp.length; i++) {\n f = new File(destinationFile.getAbsolutePath() + File.separator + tmp[i].getName());\n f.getParentFile().mkdirs();\n copy(tmp[i], f);\n }\n } else {\n System.out.println(\"\\nCopy from: \" + sourceFile + \"\\n\\n to: \" + destinationFile);\n FileChannel source = new FileInputStream(sourceFile).getChannel();\n FileChannel destination = new FileOutputStream(destinationFile).getChannel();\n destination.transferFrom(source, 0, source.size());\n source.close();\n destination.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n", "func2": " private static void copyFile(File source, File dest) throws IOException {\n FileChannel srcChannel = new FileInputStream(source).getChannel();\n FileChannel dstChannel = new FileOutputStream(dest).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n }\n", "label": 1} {"func1": " private String cookieString(String url, String ip) {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(\"SHA-1\");\n md.update((url + \"&&\" + ip + \"&&\" + salt.toString()).getBytes());\n java.math.BigInteger hash = new java.math.BigInteger(1, md.digest());\n return hash.toString(16);\n } catch (NoSuchAlgorithmException e) {\n filterConfig.getServletContext().log(this.getClass().getName() + \" error \" + e);\n return null;\n }\n }\n", "func2": " private String hashKey(String key) {\n String hashed = \"\";\n try {\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.update(key.getBytes());\n BigInteger hash = new BigInteger(1, md5.digest());\n hashed = hash.toString(16);\n } catch (Exception ex) {\n ex.printStackTrace();\n hashed = String.valueOf(key.hashCode());\n }\n return hashed;\n }\n", "label": 1} {"func1": " private boolean copyFile(File _file1, File _file2) {\n FileInputStream fis;\n FileOutputStream fos;\n try {\n fis = new FileInputStream(_file1);\n fos = new FileOutputStream(_file2);\n FileChannel canalFuente = fis.getChannel();\n canalFuente.transferTo(0, canalFuente.size(), fos.getChannel());\n fis.close();\n fos.close();\n return true;\n } catch (FileNotFoundException e) {\n } catch (IOException e) {\n }\n return false;\n }\n", "func2": " @Override\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n String rewrittenQueryString = URLDecoder.decode(request.getRequestURI(), \"UTF-8\").replaceFirst(\"^.*?\\\\/(id:.*)\\\\/.*?$\", \"$1\");\n logger.debug(\"rewrittenQueryString: \" + rewrittenQueryString);\n URL rewrittenUrl = new URL(fedoraUrl + rewrittenQueryString);\n logger.debug(\"rewrittenUrl: \" + rewrittenUrl.getProtocol() + \"://\" + rewrittenUrl.getHost() + \":\" + rewrittenUrl.getPort() + rewrittenUrl.getFile());\n HttpURLConnection httpURLConnection = (HttpURLConnection) rewrittenUrl.openConnection();\n HttpURLConnection.setFollowRedirects(false);\n httpURLConnection.connect();\n response.setStatus(httpURLConnection.getResponseCode());\n logger.debug(\"[status=\" + httpURLConnection.getResponseCode() + \"]\");\n logger.debug(\"[headers]\");\n for (Entry> header : httpURLConnection.getHeaderFields().entrySet()) {\n if (header.getKey() != null) {\n for (String value : header.getValue()) {\n if (value != null) {\n logger.debug(header.getKey() + \": \" + value);\n if (!header.getKey().equals(\"Server\") && !header.getKey().equals(\"Transfer-Encoding\")) {\n response.addHeader(header.getKey(), value);\n }\n }\n }\n }\n }\n logger.debug(\"[/headers]\");\n InputStream inputStream = httpURLConnection.getInputStream();\n OutputStream outputStream = response.getOutputStream();\n IOUtils.copy(inputStream, outputStream);\n }\n", "label": 1} {"func1": " @Override\n public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {\n InputStream is = null;\n InputStream page = null;\n OutputStream os = null;\n String rootUrl = null;\n try {\n boolean isMultipart = ServletFileUpload.isMultipartContent(request);\n if (!isMultipart) {\n request.setAttribute(\"error\", \"Form isn't a multipart form\");\n RequestDispatcher rd = request.getRequestDispatcher(\"/WEB-INF/error.jsp\");\n rd.forward(request, response);\n }\n ServletFileUpload upload = new ServletFileUpload();\n String webUrl = null;\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n if (name.equals(\"webpage\")) {\n is = item.openStream();\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(is, baos);\n page = new ByteArrayInputStream(baos.toByteArray());\n } else if (name.equals(\"weburl\")) {\n InputStream wpIs = null;\n try {\n webUrl = Streams.asString(item.openStream());\n URL u = new URL(webUrl);\n wpIs = new BufferedInputStream(u.openStream());\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n IOUtils.copy(wpIs, baos);\n page = new ByteArrayInputStream(baos.toByteArray());\n } finally {\n IOUtils.closeQuietly(wpIs);\n }\n } else if (name.equals(\"rooturl\")) {\n rootUrl = Streams.asString(item.openStream());\n }\n }\n if (page == null) {\n request.setAttribute(\"error\", \"Form doesn't have an html file\");\n RequestDispatcher rd = request.getRequestDispatcher(\"/WEB-INF/error.jsp\");\n rd.forward(request, response);\n }\n ToMailerDelegate delegate = new ToMailerDelegate(page, rootUrl);\n os = new BufferedOutputStream(response.getOutputStream());\n os.write(delegate.getMailer());\n os.flush();\n } catch (Exception e) {\n streamException(request, response, e);\n } finally {\n IOUtils.closeQuietly(page);\n IOUtils.closeQuietly(is);\n IOUtils.closeQuietly(os);\n }\n }\n", "func2": " public int run(String[] args) throws Exception {\n if (args.length < 2) {\n System.err.println(\"Download dir local\");\n return 1;\n }\n OutputStream out = new FileOutputStream(args[1]);\n Path srcDir = new Path(args[0]);\n Configuration conf = new Configuration();\n FileSystem srcFS = FileSystem.get(conf);\n if (!srcFS.getFileStatus(srcDir).isDirectory()) {\n System.err.println(args[0] + \" is not a directory.\");\n return 1;\n }\n try {\n FileStatus contents[] = srcFS.listStatus(srcDir);\n for (int i = 0; i < contents.length; i++) {\n if (contents[i].isFile()) {\n System.err.println(contents[i].getPath());\n InputStream in = srcFS.open(contents[i].getPath());\n try {\n IOUtils.copyBytes(in, out, conf, false);\n } finally {\n in.close();\n }\n }\n }\n } finally {\n out.close();\n }\n return 0;\n }\n", "label": 1} {"func1": " protected void processAddByURLSubmit(URL url, String invalidUrlMsg) {\n if (!this.hasError()) {\n try {\n StringWriter xmlSourceWriter = new StringWriter();\n IOUtils.copy(url.openStream(), xmlSourceWriter);\n processSubmittedDoap(xmlSourceWriter.toString());\n } catch (FileNotFoundException e) {\n Session.get().error(invalidUrlMsg);\n logger.warn(\"Error processing URL: \" + invalidUrlMsg);\n } catch (IOException e) {\n setResponsePage(new ErrorReportPage(new UserReportableException(\"Unable to add doap using RDF supplied\", DoapFormPage.class, e)));\n logger.warn(\"Error processing URL: \" + url + \"; \" + e.getMessage(), e);\n }\n }\n }\n", "func2": " private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {\n if (entry.isDirectory()) {\n createDir(new File(outputDir, entry.getName()));\n return;\n }\n File outputFile = new File(outputDir, entry.getName());\n if (!outputFile.getParentFile().exists()) {\n createDir(outputFile.getParentFile());\n }\n BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));\n BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));\n try {\n IOUtils.copy(inputStream, outputStream);\n } finally {\n outputStream.close();\n inputStream.close();\n }\n }\n", "label": 1} {"func1": " public static void writeFileToFile(File fin, File fout, boolean append) throws IOException {\n FileChannel inChannel = new FileInputStream(fin).getChannel();\n FileChannel outChannel = new FileOutputStream(fout, append).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } finally {\n if (inChannel != null) try {\n inChannel.close();\n } catch (IOException ex) {\n }\n if (outChannel != null) try {\n outChannel.close();\n } catch (IOException ex) {\n }\n }\n }\n", "func2": " public static void copyFile(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "label": 1} {"func1": " static File copy(File in, File out) throws IOException {\n FileChannel inChannel = new FileInputStream(in).getChannel();\n FileChannel outChannel = new FileOutputStream(out).getChannel();\n try {\n inChannel.transferTo(0, inChannel.size(), outChannel);\n return out;\n } catch (IOException e) {\n throw e;\n } finally {\n if (inChannel != null) inChannel.close();\n if (outChannel != null) outChannel.close();\n }\n }\n", "func2": " static void copy(String src, String dest) throws IOException {\n File ifp = new File(src);\n File ofp = new File(dest);\n if (ifp.exists() == false) {\n throw new IOException(\"file '\" + src + \"' does not exist\");\n }\n FileInputStream fis = new FileInputStream(ifp);\n FileOutputStream fos = new FileOutputStream(ofp);\n byte[] b = new byte[1024];\n while (fis.read(b) > 0) fos.write(b);\n fis.close();\n fos.close();\n }\n", "label": 1} {"func1": " public static boolean encodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "func2": " @Test\n public void testCopy_inputStreamToOutputStream() throws Exception {\n InputStream in = new ByteArrayInputStream(inData);\n in = new YellOnCloseInputStreamTest(in);\n ByteArrayOutputStream baout = new ByteArrayOutputStream();\n OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);\n int count = IOUtils.copy(in, out);\n assertTrue(\"Not all bytes were read\", in.available() == 0);\n assertEquals(\"Sizes differ\", inData.length, baout.size());\n assertTrue(\"Content differs\", Arrays.equals(inData, baout.toByteArray()));\n }\n", "label": 1} {"func1": " public MotixFileItem(final InputStream is, final String name, final String contentType, final int index) throws IOException {\n this.name = name;\n this.contentType = contentType;\n this.index = index;\n this.extension = FilenameUtils.getExtension(this.name);\n this.isImage = ImageUtils.isImage(name);\n ArrayInputStream isAux = null;\n final ByteArrayOutputStream out = new ByteArrayOutputStream();\n try {\n IOUtils.copy(is, out);\n isAux = new ArrayInputStream(out.toByteArray());\n if (this.isImage) {\n this.bufferedImage = imaging.read(isAux);\n }\n } finally {\n IOUtils.closeQuietly(out);\n IOUtils.closeQuietly(isAux);\n }\n this.inputStream = new ArrayInputStream(out.toByteArray());\n }\n", "func2": " public static void DecodeMapFile(String mapFile, String outputFile) throws Exception {\n byte magicKey = 0;\n byte[] buffer = new byte[2048];\n int nread;\n InputStream map;\n OutputStream output;\n try {\n map = new FileInputStream(mapFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n try {\n output = new FileOutputStream(outputFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n while ((nread = map.read(buffer, 0, 2048)) != 0) {\n for (int i = 0; i < nread; ++i) {\n buffer[i] ^= magicKey;\n magicKey += 43;\n }\n output.write(buffer, 0, nread);\n }\n map.close();\n output.close();\n }\n", "label": 1} {"func1": " public static void main(String[] args) throws Exception {\n String st = \"http://www.kmzlinks.com/redirect.asp?id=113&file=HeartShapedIsland.kmz\";\n URL url = new URL(st);\n InputStream fis = null;\n if (\"file\".equals(url.getProtocol())) fis = new FileInputStream(url.getFile()); else if (\"http\".equals(url.getProtocol())) fis = url.openStream();\n ZipInputStream zis = new ZipInputStream(fis);\n ZipEntry entry;\n while ((entry = zis.getNextEntry()) != null) {\n System.out.println(\"Extracting: \" + entry);\n int count;\n byte data[] = new byte[BUFFER];\n FileOutputStream fos = new FileOutputStream(entry.getName());\n BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);\n while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count);\n dest.flush();\n dest.close();\n }\n zis.close();\n }\n", "func2": " public static void main(String[] args) throws Exception {\n FileChannel fc = new FileOutputStream(\"data2.txt\").getChannel();\n fc.write(ByteBuffer.wrap(\"Some text\".getBytes()));\n fc.close();\n fc = new FileInputStream(\"data2.txt\").getChannel();\n ByteBuffer buff = ByteBuffer.allocate(BSIZE);\n fc.read(buff);\n buff.flip();\n System.out.println(buff.asCharBuffer());\n buff.rewind();\n String encoding = System.getProperty(\"file.encoding\");\n System.out.println(\"Decoded using \" + encoding + \": \" + Charset.forName(encoding).decode(buff));\n fc = new FileOutputStream(\"data2.txt\").getChannel();\n fc.write(ByteBuffer.wrap(\"Some text\".getBytes(\"UTF-16BE\")));\n fc.close();\n fc = new FileInputStream(\"data2.txt\").getChannel();\n buff.clear();\n fc.read(buff);\n buff.flip();\n System.out.println(buff.asCharBuffer());\n fc = new FileOutputStream(\"data2.txt\").getChannel();\n buff = ByteBuffer.allocate(24);\n buff.asCharBuffer().put(\"Some text\");\n fc.write(buff);\n fc.close();\n fc = new FileInputStream(\"data2.txt\").getChannel();\n buff.clear();\n fc.read(buff);\n buff.flip();\n System.out.println(buff.asCharBuffer());\n }\n", "label": 1} {"func1": " private void update(String statement, SyrupConnection con, boolean do_log) throws Exception {\n Statement s = null;\n try {\n s = con.createStatement();\n s.executeUpdate(statement);\n con.commit();\n } catch (Throwable e) {\n if (do_log) {\n logger.log(Level.INFO, \"Update failed. Transaction is rolled back\", e);\n }\n con.rollback();\n }\n }\n", "func2": " @Override\n public synchronized void deleteJvmStatistics(String contextName, Date dateFrom, Date dateTo) throws DatabaseException {\n final Connection connection = this.getConnection();\n try {\n connection.setAutoCommit(false);\n String queryString = \"DELETE \" + this.getJvmInvocationsSchemaAndTableName() + \" FROM \" + this.getJvmInvocationsSchemaAndTableName() + \" INNER JOIN \" + this.getJvmElementsSchemaAndTableName() + \" ON \" + this.getJvmElementsSchemaAndTableName() + \".element_id = \" + this.getJvmInvocationsSchemaAndTableName() + \".element_id WHERE \";\n if (contextName != null) {\n queryString = queryString + \" context_name LIKE ? AND \";\n }\n if (dateFrom != null) {\n queryString = queryString + \" start_timestamp >= ? AND \";\n }\n if (dateTo != null) {\n queryString = queryString + \" start_timestamp <= ? AND \";\n }\n queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString);\n final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString);\n int indexCounter = 1;\n if (contextName != null) {\n preparedStatement.setString(indexCounter, contextName);\n indexCounter = indexCounter + 1;\n }\n if (dateFrom != null) {\n preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime()));\n indexCounter = indexCounter + 1;\n }\n if (dateTo != null) {\n preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime()));\n indexCounter = indexCounter + 1;\n }\n preparedStatement.executeUpdate();\n preparedStatement.close();\n connection.commit();\n } catch (final SQLException e) {\n try {\n connection.rollback();\n } catch (final SQLException ex) {\n JeeObserverServerContext.logger.log(Level.SEVERE, \"Transaction rollback error.\", ex);\n }\n JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage());\n throw new DatabaseException(\"Error deleting JVM statistics.\", e);\n } finally {\n this.releaseConnection(connection);\n }\n }\n", "label": 1} {"func1": " public static File copyFile(File fileToCopy, File copiedFile) {\n BufferedInputStream in = null;\n BufferedOutputStream outWriter = null;\n if (!copiedFile.exists()) {\n try {\n copiedFile.createNewFile();\n } catch (IOException e1) {\n e1.printStackTrace();\n return null;\n }\n }\n try {\n in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096);\n outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096);\n int c;\n while ((c = in.read()) != -1) outWriter.write(c);\n in.close();\n outWriter.close();\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return null;\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n return copiedFile;\n }\n", "func2": " public static void saveFileData(File file, File destination, java.io.File newDataFile) throws Exception {\n String fileName = file.getFileName();\n String assetsPath = FileFactory.getRealAssetsRootPath();\n new java.io.File(assetsPath).mkdir();\n java.io.File workingFile = getAssetIOFile(file);\n DotResourceCache vc = CacheLocator.getVeloctyResourceCache();\n vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingFile.getPath());\n if (destination != null && destination.getInode() > 0) {\n FileInputStream is = new FileInputStream(workingFile);\n FileChannel channelFrom = is.getChannel();\n java.io.File newVersionFile = getAssetIOFile(destination);\n FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();\n channelFrom.transferTo(0, channelFrom.size(), channelTo);\n channelTo.force(false);\n channelTo.close();\n channelFrom.close();\n }\n if (newDataFile != null) {\n FileChannel writeCurrentChannel = new FileOutputStream(workingFile).getChannel();\n writeCurrentChannel.truncate(0);\n FileChannel fromChannel = new FileInputStream(newDataFile).getChannel();\n fromChannel.transferTo(0, fromChannel.size(), writeCurrentChannel);\n writeCurrentChannel.force(false);\n writeCurrentChannel.close();\n fromChannel.close();\n if (UtilMethods.isImage(fileName)) {\n BufferedImage img = javax.imageio.ImageIO.read(workingFile);\n int height = img.getHeight();\n file.setHeight(height);\n int width = img.getWidth();\n file.setWidth(width);\n }\n String folderPath = workingFile.getParentFile().getAbsolutePath();\n Identifier identifier = IdentifierCache.getIdentifierFromIdentifierCache(file);\n java.io.File directory = new java.io.File(folderPath);\n java.io.File[] files = directory.listFiles((new FileFactory()).new ThumbnailsFileNamesFilter(identifier));\n for (java.io.File iofile : files) {\n try {\n iofile.delete();\n } catch (SecurityException e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + iofile.getName() + \" cannot be erased. Please check the file permissions.\");\n } catch (Exception e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + e.getMessage());\n }\n }\n }\n }\n", "label": 1} {"func1": " public void cpFile(File source, File target, boolean replace, int bufferSize) throws IOException {\n if (!source.exists()) throw new IOException(\"source file not exists\");\n if (!source.isFile()) throw new IOException(\"source file not exists(is a directory)\");\n InputStream src = new FileInputStream(source);\n File tarn = target;\n if (target.isDirectory() || !(!(target.exists()) || replace)) {\n String tardir = target.isDirectory() ? target.getPath() : target.getParent();\n tarn = new File(tardir + File.separator + source.getName());\n int n = 1;\n while (!(!tarn.exists() || replace)) {\n tarn = new File(tardir + File.separator + String.valueOf(n) + \" copy of \" + source.getName());\n n++;\n }\n }\n if (source.getPath().equals(tarn.getPath()) && replace) return;\n OutputStream tar = new FileOutputStream(tarn);\n byte[] bytes = new byte[bufferSize];\n int readn = -1;\n while ((readn = src.read(bytes)) > 0) {\n tar.write(bytes, 0, readn);\n }\n tar.flush();\n tar.close();\n src.close();\n }\n", "func2": " private void copyJar(File src, File dst) throws IOException {\n FileChannel srcChannel = null;\n FileChannel dstChannel = null;\n try {\n srcChannel = new FileInputStream(src).getChannel();\n dstChannel = new FileOutputStream(dst).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } catch (IOException e) {\n fLog.log(Level.SEVERE, e.getMessage(), e);\n } finally {\n srcChannel.close();\n dstChannel.close();\n }\n }\n", "label": 1} {"func1": " public static void DecodeMapFile(String mapFile, String outputFile) throws Exception {\n byte magicKey = 0;\n byte[] buffer = new byte[2048];\n int nread;\n InputStream map;\n OutputStream output;\n try {\n map = new FileInputStream(mapFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n try {\n output = new FileOutputStream(outputFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n while ((nread = map.read(buffer, 0, 2048)) != 0) {\n for (int i = 0; i < nread; ++i) {\n buffer[i] ^= magicKey;\n magicKey += 43;\n }\n output.write(buffer, 0, nread);\n }\n map.close();\n output.close();\n }\n", "func2": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 1} {"func1": " public static void copy(File sourceFile, File destinationFile) throws IOException {\n FileChannel sourceFileChannel = (new FileInputStream(sourceFile)).getChannel();\n FileChannel destinationFileChannel = (new FileOutputStream(destinationFile)).getChannel();\n sourceFileChannel.transferTo(0, sourceFile.length(), destinationFileChannel);\n sourceFileChannel.close();\n destinationFileChannel.close();\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public static void copyFile(File source, File destination) throws IOException {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(source).getChannel();\n out = new FileOutputStream(destination).getChannel();\n in.transferTo(0, in.size(), out);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "func2": " private static void copyFile(File source, File dest) throws IOException {\n FileChannel srcChannel = new FileInputStream(source).getChannel();\n FileChannel dstChannel = new FileOutputStream(dest).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n }\n", "label": 1} {"func1": " private void doFinishLoadAttachment(long attachmentId) {\n if (attachmentId != mLoadAttachmentId) {\n return;\n }\n Attachment attachment = Attachment.restoreAttachmentWithId(MessageView.this, attachmentId);\n Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);\n Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(getContentResolver(), attachmentUri);\n if (mLoadAttachmentSave) {\n try {\n File file = createUniqueFile(Environment.getExternalStorageDirectory(), attachment.mFileName);\n InputStream in = getContentResolver().openInputStream(contentUri);\n OutputStream out = new FileOutputStream(file);\n IOUtils.copy(in, out);\n out.flush();\n out.close();\n in.close();\n Toast.makeText(MessageView.this, String.format(getString(R.string.message_view_status_attachment_saved), file.getName()), Toast.LENGTH_LONG).show();\n new MediaScannerNotifier(this, file, mHandler);\n } catch (IOException ioe) {\n Toast.makeText(MessageView.this, getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show();\n }\n } else {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.setData(contentUri);\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);\n startActivity(intent);\n } catch (ActivityNotFoundException e) {\n mHandler.attachmentViewError();\n }\n }\n }\n", "func2": " public static void copy(File srcPath, File dstPath) throws IOException {\n if (srcPath.isDirectory()) {\n if (!dstPath.exists()) {\n boolean result = dstPath.mkdir();\n if (!result) throw new IOException(\"Unable to create directoy: \" + dstPath);\n }\n String[] files = srcPath.list();\n for (String file : files) {\n copy(new File(srcPath, file), new File(dstPath, file));\n }\n } else {\n if (srcPath.exists()) {\n FileChannel in = null;\n FileChannel out = null;\n try {\n in = new FileInputStream(srcPath).getChannel();\n out = new FileOutputStream(dstPath).getChannel();\n long size = in.size();\n MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);\n out.write(buf);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n }\n }\n", "label": 1} {"func1": " public void actualizar() throws SQLException, ClassNotFoundException, Exception {\n Connection conn = null;\n PreparedStatement ms = null;\n registroActualizado = false;\n try {\n conn = ToolsBD.getConn();\n conn.setAutoCommit(false);\n Date fechaSystem = new Date();\n DateFormat aaaammdd = new SimpleDateFormat(\"yyyyMMdd\");\n int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));\n DateFormat hhmmss = new SimpleDateFormat(\"HHmmss\");\n DateFormat sss = new SimpleDateFormat(\"S\");\n String ss = sss.format(fechaSystem);\n if (ss.length() > 2) {\n ss = ss.substring(0, 2);\n }\n int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);\n ms = conn.prepareStatement(SENTENCIA_UPDATE);\n ms.setString(1, descartadoEntrada);\n ms.setString(2, usuarioEntrada);\n ms.setString(3, motivosDescarteEntrada);\n ms.setInt(4, Integer.parseInt(anoOficio));\n ms.setInt(5, Integer.parseInt(oficinaOficio));\n ms.setInt(6, Integer.parseInt(numeroOficio));\n ms.setInt(7, anoEntrada != null ? Integer.parseInt(anoEntrada) : 0);\n ms.setInt(8, oficinaEntrada != null ? Integer.parseInt(oficinaEntrada) : 0);\n ms.setInt(9, numeroEntrada != null ? Integer.parseInt(numeroEntrada) : 0);\n int afectados = ms.executeUpdate();\n if (afectados > 0) {\n registroActualizado = true;\n } else {\n registroActualizado = false;\n }\n conn.commit();\n } catch (Exception ex) {\n System.out.println(\"Error inesperat, no s'ha desat el registre: \" + ex.getMessage());\n ex.printStackTrace();\n registroActualizado = false;\n errores.put(\"\", \"Error inesperat, no s'ha desat el registre\" + \": \" + ex.getClass() + \"->\" + ex.getMessage());\n try {\n if (conn != null) conn.rollback();\n } catch (SQLException sqle) {\n throw new RemoteException(\"S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats\", sqle);\n }\n throw new RemoteException(\"Error inesperat, no s'ha modifcat el registre\", ex);\n } finally {\n ToolsBD.closeConn(conn, ms, null);\n }\n }\n", "func2": " public static void addRecipe(String name, String instructions, int categoryId, String[][] ainekset) throws Exception {\n PreparedStatement pst1 = null;\n PreparedStatement pst2 = null;\n ResultSet rs = null;\n int retVal = -1;\n try {\n pst1 = conn.prepareStatement(\"INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)\");\n pst1.setString(1, name);\n pst1.setString(2, instructions);\n pst1.setInt(3, categoryId);\n if (pst1.executeUpdate() > 0) {\n pst2 = conn.prepareStatement(\"SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?\");\n pst2.setString(1, name);\n pst2.setString(2, instructions);\n pst2.setInt(3, categoryId);\n rs = pst2.executeQuery();\n if (rs.next()) {\n int id = rs.getInt(1);\n System.out.println(\"Lis�t��n ainesosat\");\n String[] aines;\n for (int i = 0; i < ainekset.length; ++i) {\n aines = ainekset[i];\n addIngredient(id, aines[0], aines[1], Integer.parseInt(aines[2]), Integer.parseInt(aines[3]));\n }\n retVal = id;\n } else {\n retVal = -1;\n }\n } else {\n retVal = -1;\n }\n conn.commit();\n } catch (Exception e) {\n conn.rollback();\n throw new Exception(\"Reseptin lis�ys ep�onnistui. Poikkeus: \" + e.getMessage());\n }\n }\n", "label": 1} {"func1": " protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n if (request.getParameter(\"edit\") != null) {\n try {\n User cu = (User) request.getSession().getAttribute(\"currentuser\");\n UserDetails ud = cu.getUserDetails();\n String returnTo = \"editprofile.jsp\";\n if (!request.getParameter(\"password\").equals(\"\")) {\n String password = request.getParameter(\"password\");\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(new String(password).getBytes());\n byte[] hash = md.digest();\n String pass = new BigInteger(1, hash).toString(16);\n cu.setClientPassword(pass);\n }\n ud.setFirstName(request.getParameter(\"fname\"));\n ud.setLastName(request.getParameter(\"lname\"));\n ud.setEmailAddress(request.getParameter(\"email\"));\n ud.setAddress(request.getParameter(\"address\"));\n ud.setZipcode(request.getParameter(\"zipcode\"));\n ud.setTown(request.getParameter(\"town\"));\n ud.setCountry(request.getParameter(\"country\"));\n ud.setTrackingColor(request.getParameter(\"input1\"));\n String vis = request.getParameter(\"visibility\");\n if (vis.equals(\"self\")) {\n cu.setVisibility(0);\n } else if (vis.equals(\"friends\")) {\n cu.setVisibility(1);\n } else if (vis.equals(\"all\")) {\n cu.setVisibility(2);\n } else {\n response.sendRedirect(\"error.jsp?id=8\");\n }\n em.getTransaction().begin();\n em.persist(cu);\n em.getTransaction().commit();\n response.sendRedirect(returnTo);\n } catch (Throwable e) {\n e.printStackTrace();\n response.sendRedirect(\"error.jsp?id=5\");\n }\n return;\n }\n }\n", "func2": " public byte[] getDigest(OMAttribute attribute, String digestAlgorithm) throws OMException {\n byte[] digest = new byte[0];\n if (!(attribute.getLocalName().equals(\"xmlns\") || attribute.getLocalName().startsWith(\"xmlns:\"))) try {\n MessageDigest md = MessageDigest.getInstance(digestAlgorithm);\n md.update((byte) 0);\n md.update((byte) 0);\n md.update((byte) 0);\n md.update((byte) 2);\n md.update(getExpandedName(attribute).getBytes(\"UnicodeBigUnmarked\"));\n md.update((byte) 0);\n md.update((byte) 0);\n md.update(attribute.getAttributeValue().getBytes(\"UnicodeBigUnmarked\"));\n digest = md.digest();\n } catch (NoSuchAlgorithmException e) {\n throw new OMException(e);\n } catch (UnsupportedEncodingException e) {\n throw new OMException(e);\n }\n return digest;\n }\n", "label": 1} {"func1": " public void createJAR(String fileString, String ext) {\n try {\n File file = new File(fileString);\n int i = fileString.lastIndexOf(java.io.File.separator);\n String dir = fileString.substring(0, i + 1);\n if (ext.matches(\"jar\")) {\n jarFile = new File(getClass().getClassLoader().getResource(\"jsdviewer.jar\").toURI());\n java.io.FileOutputStream fstrm = new java.io.FileOutputStream(file);\n FileChannel in = (new java.io.FileInputStream(jarFile)).getChannel();\n FileChannel out = fstrm.getChannel();\n in.transferTo(0, jarFile.length(), out);\n in.close();\n out.close();\n } else {\n file.mkdir();\n }\n File.umount(file);\n File temp = new File(dir + \"document.jsd\");\n FileOutputStream fstrm2 = new FileOutputStream(temp.getCanonicalPath());\n ostrm = new ObjectOutputStream(fstrm2);\n ostrm.writeObject(doc);\n ostrm.flush();\n ostrm.close();\n File.umount();\n File docFile = new File(file.getCanonicalPath() + java.io.File.separator + \"document.jsd\");\n File.cp_p(temp, docFile);\n File.umount();\n temp.delete();\n File.umount(file);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n", "func2": " public byte[] getResponse() {\n final ByteArrayInputStream bais = new ByteArrayInputStream(request);\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n List lines = Collections.emptyList();\n try {\n @SuppressWarnings(\"unchecked\") List dl = IOUtils.readLines(bais);\n lines = dl;\n } catch (IOException ioex) {\n throw new AssertionError(ioex);\n }\n String resource = null;\n for (String line : lines) {\n if (line.startsWith(\"GET \")) {\n int endIndex = line.lastIndexOf(' ');\n resource = line.substring(4, endIndex);\n }\n }\n final PrintStream printStream = new PrintStream(baos);\n if (resource == null) {\n printStream.println(\"HTTP/1.1 400 Bad Request\");\n } else {\n final InputStream inputStream = getClass().getResourceAsStream(resource);\n if (inputStream == null) {\n printStream.println(\"HTTP/1.1 404 Not Found\");\n printStream.println();\n } else {\n printStream.println(\"HTTP/1.1 200 OK\");\n printStream.println();\n try {\n IOUtils.copy(inputStream, printStream);\n } catch (IOException ioex) {\n throw new AssertionError(ioex);\n }\n }\n }\n printStream.flush();\n printStream.close();\n return baos.toByteArray();\n }\n", "label": 1} {"func1": " @Test\n public void testTrainingBackprop() throws IOException {\n File temp = File.createTempFile(\"fannj_\", \".tmp\");\n temp.deleteOnExit();\n IOUtils.copy(this.getClass().getResourceAsStream(\"xor.data\"), new FileOutputStream(temp));\n List layers = new ArrayList();\n layers.add(Layer.create(2));\n layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n layers.add(Layer.create(2, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));\n Fann fann = new Fann(layers);\n Trainer trainer = new Trainer(fann);\n trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_INCREMENTAL);\n float desiredError = .001f;\n float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);\n assertTrue(\"\" + mse, mse <= desiredError);\n }\n", "func2": " public static String CopyFile(String sourcefile, String destfile) throws FileNotFoundException, IOException {\n int last = destfile.lastIndexOf('/');\n if (last < 0) {\n DrxWriteError(\"CopyFile\", \"Destination filepath \" + destfile + \" doesn't contain /\");\n throw new java.io.FileNotFoundException(destfile);\n }\n String parent = destfile.substring(0, last);\n if (parent.length() > 0) {\n File f = new File(parent);\n if (!f.isDirectory()) {\n if (!f.mkdirs()) {\n DrxWriteError(\"CopyFile\", \"Folder \" + parent + \" doesn't exist, cannot create\");\n }\n }\n }\n FileChannel srcChannel = new FileInputStream(sourcefile).getChannel();\n FileChannel dstChannel = new FileOutputStream(destfile).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n return destfile;\n }\n", "label": 1} {"func1": " @Override\n public void alterar(Disciplina t) throws Exception {\n PreparedStatement stmt = null;\n String sql = \"UPDATE disciplina SET nm_disciplina = ?, cod_disciplina = ? WHERE id_disciplina = ?\";\n try {\n stmt = conexao.prepareStatement(sql);\n stmt.setString(1, t.getNomeDisciplina());\n stmt.setString(2, t.getCodDisciplina());\n stmt.setInt(3, t.getIdDisciplina());\n stmt.executeUpdate();\n conexao.commit();\n int id_disciplina = t.getIdDisciplina();\n excluirTopico(t.getIdDisciplina());\n for (Topico item : t.getTopicos()) {\n criarTopico(item, id_disciplina);\n }\n } catch (SQLException e) {\n conexao.rollback();\n throw e;\n }\n }\n", "func2": " public void deleteObject(String id) throws SQLException {\n boolean selfConnection = true;\n Connection conn = null;\n PreparedStatement stmt = null;\n try {\n if (dbConnection == null) {\n DatabaseConn dbConn = new DatabaseConn();\n conn = dbConn.getConnection();\n conn.setAutoCommit(false);\n } else {\n conn = dbConnection;\n selfConnection = false;\n }\n stmt = conn.prepareStatement(this.deleteSql);\n stmt.setString(1, id);\n stmt.executeUpdate();\n if (selfConnection) conn.commit();\n } catch (Exception e) {\n if (selfConnection && conn != null) conn.rollback();\n throw new SQLException(e.getMessage());\n } finally {\n if (stmt != null) {\n stmt.close();\n stmt = null;\n }\n if (selfConnection && conn != null) {\n conn.close();\n conn = null;\n }\n }\n }\n", "label": 1} {"func1": " private void CopyTo(File dest) throws IOException {\n FileReader in = null;\n FileWriter out = null;\n int c;\n try {\n in = new FileReader(image);\n out = new FileWriter(dest);\n while ((c = in.read()) != -1) out.write(c);\n } finally {\n if (in != null) try {\n in.close();\n } catch (Exception e) {\n }\n if (out != null) try {\n out.close();\n } catch (Exception e) {\n }\n }\n }\n", "func2": " public static boolean copyFile(String sourceName, String destName) {\n FileChannel sourceChannel = null;\n FileChannel destChannel = null;\n boolean wasOk = false;\n try {\n sourceChannel = new FileInputStream(sourceName).getChannel();\n destChannel = new FileOutputStream(destName).getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n wasOk = true;\n } catch (Throwable exception) {\n logger.log(Level.SEVERE, \"Exception in copyFile\", exception);\n } finally {\n try {\n if (sourceChannel != null) sourceChannel.close();\n } catch (Throwable tt) {\n }\n try {\n if (destChannel != null) destChannel.close();\n } catch (Throwable tt) {\n }\n }\n return wasOk;\n }\n", "label": 1} {"func1": " static void copy(String src, String dest) throws IOException {\n InputStream in = null;\n OutputStream out = null;\n try {\n in = new FileInputStream(src);\n out = new FileOutputStream(dest);\n byte[] buf = new byte[1024];\n int n;\n while ((n = in.read(buf)) > 0) out.write(buf, 0, n);\n } finally {\n if (in != null) in.close();\n if (out != null) out.close();\n }\n }\n", "func2": " public static boolean decodeFileToFile(String infile, String outfile) {\n boolean success = false;\n java.io.InputStream in = null;\n java.io.OutputStream out = null;\n try {\n in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);\n out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));\n byte[] buffer = new byte[65536];\n int read = -1;\n while ((read = in.read(buffer)) >= 0) {\n out.write(buffer, 0, read);\n }\n success = true;\n } catch (java.io.IOException exc) {\n exc.printStackTrace();\n } finally {\n try {\n in.close();\n } catch (Exception exc) {\n }\n try {\n out.close();\n } catch (Exception exc) {\n }\n }\n return success;\n }\n", "label": 1} {"func1": " private static boolean copyFile(File in, File out) {\n boolean ok = true;\n InputStream is = null;\n OutputStream os = null;\n try {\n is = new FileInputStream(in);\n os = new FileOutputStream(out);\n byte[] buffer = new byte[0xFFFF];\n for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len);\n } catch (IOException e) {\n System.err.println(e);\n ok = false;\n } finally {\n if (is != null) {\n try {\n is.close();\n } catch (IOException e) {\n System.err.println(e);\n }\n }\n if (os != null) {\n try {\n os.close();\n } catch (IOException e) {\n System.err.println(e);\n }\n }\n }\n return ok;\n }\n", "func2": " public static void copy(File source, File destination) throws FileNotFoundException, IOException {\n if (source == null) throw new NullPointerException(\"The source may not be null.\");\n if (destination == null) throw new NullPointerException(\"The destination may not be null.\");\n FileInputStream sourceStream = new FileInputStream(source);\n destination.getParentFile().mkdirs();\n FileOutputStream destStream = new FileOutputStream(destination);\n try {\n FileChannel sourceChannel = sourceStream.getChannel();\n FileChannel destChannel = destStream.getChannel();\n destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());\n } finally {\n try {\n sourceStream.close();\n destStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n", "label": 1} {"func1": " public static void main(String[] args) throws FileNotFoundException {\n if (args.length < 2) throw new IllegalArgumentException();\n String fnOut = args[args.length - 1];\n PrintWriter writer = new PrintWriter(fnOut);\n for (int i = 0; i < args.length - 1; i++) {\n File fInput = new File(args[i]);\n Scanner in = new Scanner(fInput);\n while (in.hasNext()) {\n writer.println(in.nextLine());\n }\n }\n writer.close();\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public static void DecodeMapFile(String mapFile, String outputFile) throws Exception {\n byte magicKey = 0;\n byte[] buffer = new byte[2048];\n int nread;\n InputStream map;\n OutputStream output;\n try {\n map = new FileInputStream(mapFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n try {\n output = new FileOutputStream(outputFile);\n } catch (Exception e) {\n throw new Exception(\"Map file error\", e);\n }\n while ((nread = map.read(buffer, 0, 2048)) != 0) {\n for (int i = 0; i < nread; ++i) {\n buffer[i] ^= magicKey;\n magicKey += 43;\n }\n output.write(buffer, 0, nread);\n }\n map.close();\n output.close();\n }\n", "func2": " private void copyFile(final String sourceFileName, final File path) throws IOException {\n final File source = new File(sourceFileName);\n final File destination = new File(path, source.getName());\n FileChannel srcChannel = null;\n FileChannel dstChannel = null;\n try {\n srcChannel = new FileInputStream(source).getChannel();\n dstChannel = new FileOutputStream(destination).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n } finally {\n try {\n if (dstChannel != null) {\n dstChannel.close();\n }\n } catch (Exception exception) {\n }\n try {\n if (srcChannel != null) {\n srcChannel.close();\n }\n } catch (Exception exception) {\n }\n }\n }\n", "label": 1} {"func1": " public void cpFile(File source, File target, boolean replace, int bufferSize) throws IOException {\n if (!source.exists()) throw new IOException(\"source file not exists\");\n if (!source.isFile()) throw new IOException(\"source file not exists(is a directory)\");\n InputStream src = new FileInputStream(source);\n File tarn = target;\n if (target.isDirectory() || !(!(target.exists()) || replace)) {\n String tardir = target.isDirectory() ? target.getPath() : target.getParent();\n tarn = new File(tardir + File.separator + source.getName());\n int n = 1;\n while (!(!tarn.exists() || replace)) {\n tarn = new File(tardir + File.separator + String.valueOf(n) + \" copy of \" + source.getName());\n n++;\n }\n }\n if (source.getPath().equals(tarn.getPath()) && replace) return;\n OutputStream tar = new FileOutputStream(tarn);\n byte[] bytes = new byte[bufferSize];\n int readn = -1;\n while ((readn = src.read(bytes)) > 0) {\n tar.write(bytes, 0, readn);\n }\n tar.flush();\n tar.close();\n src.close();\n }\n", "func2": " public static void saveFileData(File file, File destination, java.io.File newDataFile) throws Exception {\n String fileName = file.getFileName();\n String assetsPath = FileFactory.getRealAssetsRootPath();\n new java.io.File(assetsPath).mkdir();\n java.io.File workingFile = getAssetIOFile(file);\n DotResourceCache vc = CacheLocator.getVeloctyResourceCache();\n vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingFile.getPath());\n if (destination != null && destination.getInode() > 0) {\n FileInputStream is = new FileInputStream(workingFile);\n FileChannel channelFrom = is.getChannel();\n java.io.File newVersionFile = getAssetIOFile(destination);\n FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();\n channelFrom.transferTo(0, channelFrom.size(), channelTo);\n channelTo.force(false);\n channelTo.close();\n channelFrom.close();\n }\n if (newDataFile != null) {\n FileChannel writeCurrentChannel = new FileOutputStream(workingFile).getChannel();\n writeCurrentChannel.truncate(0);\n FileChannel fromChannel = new FileInputStream(newDataFile).getChannel();\n fromChannel.transferTo(0, fromChannel.size(), writeCurrentChannel);\n writeCurrentChannel.force(false);\n writeCurrentChannel.close();\n fromChannel.close();\n if (UtilMethods.isImage(fileName)) {\n BufferedImage img = javax.imageio.ImageIO.read(workingFile);\n int height = img.getHeight();\n file.setHeight(height);\n int width = img.getWidth();\n file.setWidth(width);\n }\n String folderPath = workingFile.getParentFile().getAbsolutePath();\n Identifier identifier = IdentifierCache.getIdentifierFromIdentifierCache(file);\n java.io.File directory = new java.io.File(folderPath);\n java.io.File[] files = directory.listFiles((new FileFactory()).new ThumbnailsFileNamesFilter(identifier));\n for (java.io.File iofile : files) {\n try {\n iofile.delete();\n } catch (SecurityException e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + iofile.getName() + \" cannot be erased. Please check the file permissions.\");\n } catch (Exception e) {\n Logger.error(FileFactory.class, \"EditFileAction._saveWorkingFileData(): \" + e.getMessage());\n }\n }\n }\n }\n", "label": 1} {"func1": " public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {\n String name = metadata.get(Metadata.RESOURCE_NAME_KEY);\n if (name != null && wanted.containsKey(name)) {\n FileOutputStream out = new FileOutputStream(wanted.get(name));\n IOUtils.copy(stream, out);\n out.close();\n } else {\n if (downstreamParser != null) {\n downstreamParser.parse(stream, handler, metadata, context);\n }\n }\n }\n", "func2": " private static void copyFile(File in, File out) {\n try {\n FileChannel sourceChannel = new FileInputStream(in).getChannel();\n FileChannel destinationChannel = new FileOutputStream(out).getChannel();\n sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);\n sourceChannel.close();\n destinationChannel.close();\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n }\n", "label": 1} {"func1": " protected ExternalDecoder(InputStream source, Process process) {\n super(source);\n this.process = process;\n this.processStdOut = process.getInputStream();\n this.processStdIn = process.getOutputStream();\n new Thread() {\n\n @Override\n public void run() {\n try {\n IOUtils.copy(getSource(), processStdIn);\n System.err.println(\"Copy done.\");\n close();\n } catch (IOException e) {\n e.printStackTrace();\n IOUtils.closeQuietly(ExternalDecoder.this);\n }\n }\n }.start();\n }\n", "func2": " private static void readAndRewrite(File inFile, File outFile) throws IOException {\n ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));\n DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);\n Dataset ds = DcmObjectFactory.getInstance().newDataset();\n dcmParser.setDcmHandler(ds.getDcmHandler());\n dcmParser.parseDcmFile(null, Tags.PixelData);\n PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n System.out.println(\"reading \" + inFile + \"...\");\n pdReader.readPixelData(false);\n ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));\n DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;\n ds.writeDataset(out, dcmEncParam);\n ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());\n System.out.println(\"writing \" + outFile + \"...\");\n PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());\n pdWriter.writePixelData();\n out.flush();\n out.close();\n System.out.println(\"done!\");\n }\n", "label": 1} {"func1": " public void logging() throws Fault {\n final InterceptorWrapper wrap = new InterceptorWrapper(message);\n final LoggingMessage buffer = new LoggingMessage(\"Inbound Message\\n----------------------------\");\n String encoding = (String) wrap.getEncoding();\n if (encoding != null) {\n buffer.getEncoding().append(encoding);\n }\n Object headers = wrap.getProtocolHeaders();\n if (headers != null) {\n buffer.getHeader().append(headers);\n }\n InputStream is = (InputStream) wrap.getContent(InputStream.class);\n if (is != null) {\n CachedOutputStream bos = new CachedOutputStream();\n try {\n IOUtils.copy(is, bos);\n bos.flush();\n is.close();\n this.message.setContent(InputStream.class, bos.getInputStream());\n if (bos.getTempFile() != null) {\n logger.error(\"\\nMessage (saved to tmp file):\\n\");\n logger.error(\"Filename: \" + bos.getTempFile().getAbsolutePath() + \"\\n\");\n }\n if (bos.size() > limit) {\n logger.error(\"(message truncated to \" + limit + \" bytes)\\n\");\n }\n bos.writeCacheTo(buffer.getPayload(), limit);\n bos.close();\n } catch (IOException e) {\n throw new Fault(e);\n }\n }\n logger.debug(buffer.getPayload().toString().replaceAll(\"\\r\\n|\\n|\\r\", \"\"));\n }\n", "func2": " @Override\n public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {\n if (query == null) {\n throw new NotConnectedException();\n }\n ArrayList recipients = query.getUserManager().getTecMail();\n Mail mail = new Mail(recipients);\n try {\n ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(\"log/ossobooklog.zip\"));\n FileInputStream fis = new FileInputStream(\"log/ossobook.log\");\n ZipEntry entry = new ZipEntry(\"ossobook.log\");\n zos.putNextEntry(entry);\n byte[] buffer = new byte[8192];\n int read = 0;\n while ((read = fis.read(buffer, 0, 1024)) != -1) {\n zos.write(buffer, 0, read);\n }\n zos.closeEntry();\n fis.close();\n zos.close();\n mail.sendErrorMessage(message, new File(\"log/ossobooklog.zip\"), getUserName());\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n", "label": 1} {"func1": " public static String CopyFile(String sourcefile, String destfile) throws FileNotFoundException, IOException {\n int last = destfile.lastIndexOf('/');\n if (last < 0) {\n DrxWriteError(\"CopyFile\", \"Destination filepath \" + destfile + \" doesn't contain /\");\n throw new java.io.FileNotFoundException(destfile);\n }\n String parent = destfile.substring(0, last);\n if (parent.length() > 0) {\n File f = new File(parent);\n if (!f.isDirectory()) {\n if (!f.mkdirs()) {\n DrxWriteError(\"CopyFile\", \"Folder \" + parent + \" doesn't exist, cannot create\");\n }\n }\n }\n FileChannel srcChannel = new FileInputStream(sourcefile).getChannel();\n FileChannel dstChannel = new FileOutputStream(destfile).getChannel();\n dstChannel.transferFrom(srcChannel, 0, srcChannel.size());\n srcChannel.close();\n dstChannel.close();\n return destfile;\n }\n", "func2": " private void compress(String outputFile, ArrayList inputFiles, PrintWriter log, boolean compress) throws Exception {\n String absPath = getAppConfig().getPathConfig().getAbsoluteServerPath();\n log.println(\"Concat files into: \" + outputFile);\n OutputStream out = new FileOutputStream(absPath + outputFile);\n byte[] buffer = new byte[4096];\n int readBytes;\n for (String file : inputFiles) {\n log.println(\" Read: \" + file);\n InputStream in = new FileInputStream(absPath + file);\n while ((readBytes = in.read(buffer)) != -1) {\n out.write(buffer, 0, readBytes);\n }\n in.close();\n }\n out.close();\n if (compress) {\n long normalSize = new File(absPath + outputFile).length();\n ProcessBuilder builder = new ProcessBuilder(\"java\", \"-jar\", \"WEB-INF/yuicompressor.jar\", outputFile, \"-o\", outputFile, \"--line-break\", \"4000\");\n builder.directory(new File(absPath));\n Process process = builder.start();\n process.waitFor();\n long minSize = new File(absPath + outputFile).length();\n long diff = normalSize - minSize;\n double percentage = Math.floor((double) diff / normalSize * 1000.0) / 10.0;\n double diffSize = (Math.floor(diff / 1024.0 * 10.0) / 10.0);\n log.println(\"Result: \" + percentage + \" % (\" + diffSize + \" KB)\");\n }\n }\n", "label": 1} {"func1": " private void run(Reader xmlIn, OutputStream out) throws IOException, SAXException {\n Document dom = null;\n try {\n DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();\n f.setNamespaceAware(false);\n f.setCoalescing(true);\n f.setIgnoringComments(true);\n f.setValidating(false);\n DocumentBuilder b = f.newDocumentBuilder();\n dom = b.parse(new InputSource(xmlIn));\n } catch (ParserConfigurationException err) {\n throw new IOException(err);\n }\n Element root = dom.getDocumentElement();\n if (root == null) throw new SAXException(\"Not root in document\");\n Attr att = root.getAttributeNode(\"label\");\n if (att == null) root.setAttribute(\"label\", \"Wikipedia\");\n Menu menu = parseMenu(root);\n menu.id = \"menuWikipedia\";\n ZipOutputStream zout = new ZipOutputStream(out);\n String content = ResourceUtils.getContent(XUL4Wikipedia.class, \"chrome.manifest\");\n addEntry(zout, \"chrome.manifest\", content);\n content = ResourceUtils.getContent(XUL4Wikipedia.class, \"install.rdf\");\n addEntry(zout, \"install.rdf\", content);\n content = ResourceUtils.getContent(XUL4Wikipedia.class, \"library.js\");\n addDir(zout, \"chrome/\");\n addDir(zout, \"chrome/content/\");\n addDir(zout, \"chrome/skin/\");\n String signal = \"/*INSERT_CMD_HERE*/\";\n int n = content.indexOf(signal);\n if (n == -1) throw new RuntimeException(\"where is \" + signal + \" ??\");\n ZipEntry entry = new ZipEntry(\"chrome/content/library.js\");\n zout.putNextEntry(entry);\n PrintWriter pout = new PrintWriter(zout);\n pout.write(content.substring(0, n));\n menu.toJS(pout);\n pout.write(content.substring(n + signal.length()));\n pout.flush();\n zout.closeEntry();\n entry = new ZipEntry(\"chrome/content/menu.xul\");\n zout.putNextEntry(entry);\n pout = new PrintWriter(zout);\n pout.println(\"\");\n pout.println(\"\");\n pout.println(\"