label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
0
@Override public void onLoadingEnded() { if (m_frame != null) { try { String urltext = getDocument().getDocumentURI(); URL url = new URL(urltext); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader in = new BufferedReader(isr); String inputLine; urltext = null; url = null; m_content.clear(); while ((inputLine = in.readLine()) != null) { m_content.add(inputLine); } in.close(); isr = null; in = null; inputLine = null; Action action = parseHtml(); if (action.value() == Action.ACTION_BROWSER_LOADING_DONE && action.toString().equals(Action.COMMAND_CARD_PREVIEW)) { FileUtils.copyURLToFile(new URL(getCardImageURL(m_card.MID)), new File(m_card.getImagePath())); fireActionEvent(MainWindow.class, action.value(), action.toString()); } action = null; } catch (Exception ex) { Dialog.ErrorBox(m_frame, ex.getStackTrace()); } } m_loading = false; }
public String move(Integer param) { LOG.debug("move " + param); StringBuffer ret = new StringBuffer(); try { URL url = new URL("http://" + host + "/decoder_control.cgi?command=" + param + "&user=" + user + "&pwd=" + password); URLConnection con = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { ret.append(inputLine); } in.close(); } catch (Exception e) { logException(e); connect(host, user, password); } return ret.toString(); }
200
0
private void loadDefaultDrivers() { final URL url = _app.getResources().getDefaultDriversUrl(); try { InputStreamReader isr = new InputStreamReader(url.openStream()); try { _cache.load(isr); } finally { isr.close(); } } catch (Exception ex) { final Logger logger = _app.getLogger(); logger.showMessage(Logger.ILogTypes.ERROR, "Error loading default driver file: " + url != null ? url.toExternalForm() : ""); logger.showMessage(Logger.ILogTypes.ERROR, ex); } }
public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
201
0
public void deletePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portletNameBean.getPortletId() == null) throw new IllegalArgumentException("portletNameId is null"); String sql = "delete from WM_PORTAL_PORTLET_NAME " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
public TestReport runImpl() throws Exception { DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); File ser1 = File.createTempFile("doc1", "ser"); File ser2 = File.createTempFile("doc2", "ser"); try { ObjectOutputStream oos; oos = new ObjectOutputStream(new FileOutputStream(ser1)); oos.writeObject(doc); oos.close(); ObjectInputStream ois; ois = new ObjectInputStream(new FileInputStream(ser1)); doc = (Document) ois.readObject(); ois.close(); oos = new ObjectOutputStream(new FileOutputStream(ser2)); oos.writeObject(doc); oos.close(); } catch (IOException e) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode("io.error"); report.addDescriptionEntry("message", e.getClass().getName() + ": " + e.getMessage()); report.addDescriptionEntry("file.name", testFileName); report.setPassed(false); return report; } InputStream is1 = new FileInputStream(ser1); InputStream is2 = new FileInputStream(ser2); for (; ; ) { int i1 = is1.read(); int i2 = is2.read(); if (i1 == -1 && i2 == -1) { return reportSuccess(); } if (i1 != i2) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode("difference.found"); report.addDescriptionEntry("file.name", testFileName); report.setPassed(false); return report; } } }
202
1
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
public ContourGenerator(URL url, float modelMean, float modelStddev) throws IOException { this.modelMean = modelMean; this.modelStddev = modelStddev; List termsList = new ArrayList(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); while (line != null) { if (!line.startsWith("***")) { parseAndAdd(termsList, line); } line = reader.readLine(); } terms = (F0ModelTerm[]) termsList.toArray(terms); reader.close(); }
203
0
protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); String line = null; try { urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); line = reader.readLine(); reader.close(); } finally { urlcon.disconnect(); } return line; }
private void download(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
204
0
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } }
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
205
0
public JarClassLoader(ClassLoader parent) { super(parent); initLogger(); hmClass = new HashMap<String, Class<?>>(); lstJarFile = new ArrayList<JarFileInfo>(); hsDeleteOnExit = new HashSet<File>(); String sUrlTopJar = null; pd = getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL urlTopJar = cs.getLocation(); String protocol = urlTopJar.getProtocol(); JarFileInfo jarFileInfo = null; if ("http".equals(protocol) || "https".equals(protocol)) { try { urlTopJar = new URL("jar:" + urlTopJar + "!/"); JarURLConnection jarCon = (JarURLConnection) urlTopJar.openConnection(); JarFile jarFile = jarCon.getJarFile(); jarFileInfo = new JarFileInfo(jarFile, jarFile.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", urlTopJar, protocol); } catch (Exception e) { logError(LogArea.JAR, "Failure to load HTTP JAR: %s %s", urlTopJar, e.toString()); return; } } if ("file".equals(protocol)) { try { sUrlTopJar = URLDecoder.decode(urlTopJar.getFile(), "UTF-8"); } catch (UnsupportedEncodingException e) { logError(LogArea.JAR, "Failure to decode URL: %s %s", urlTopJar, e.toString()); return; } File fileJar = new File(sUrlTopJar); if (fileJar.isDirectory()) { logInfo(LogArea.JAR, "Loading from exploded directory: %s", sUrlTopJar); return; } try { jarFileInfo = new JarFileInfo(new JarFile(fileJar), fileJar.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", sUrlTopJar, protocol); } catch (IOException e) { logError(LogArea.JAR, "Not a JAR: %s %s", sUrlTopJar, e.toString()); return; } } try { if (jarFileInfo == null) { throw new IOException(String.format("Unknown protocol %s", protocol)); } loadJar(jarFileInfo); } catch (IOException e) { logError(LogArea.JAR, "Not valid URL: %s %s", urlTopJar, e.toString()); return; } checkShading(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { shutdown(); } }); }
protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
206
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
public void test() throws Exception { File temp = File.createTempFile("test", ".test"); temp.deleteOnExit(); StorageFile s = new StorageFile(temp, "UTF-8"); s.addText("Test"); s.getOutputStream().write("ing is important".getBytes("UTF-8")); s.getWriter().write(" but overrated"); assertEquals("Testing is important but overrated", s.getText()); s.close(ResponseStateOk.getInstance()); assertEquals("Testing is important but overrated", s.getText()); InputStream input = s.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer, "UTF-8"); assertEquals("Testing is important but overrated", writer.toString()); try { s.getOutputStream(); fail("Should thow an IOException as it is closed."); } catch (IOException e) { } }
207
0
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
public static String sendGetRequest(String urlStr) { String result = null; try { URL url = new URL(urlStr); System.out.println(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line = ""; System.out.println("aa" + line); while ((line = rd.readLine()) != null) { System.out.println("aa" + line); sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
208
0
public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; }
public void testStorageString() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); r.addText("This is an example"); r.addText(" and another one."); assertEquals("This is an example and another one.", r.getText()); InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); try { r.getOutputStream(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } try { r.getWriter(); fail("Once addText() is used the text is stored as a String and you cannot use getOutputStream anymore"); } catch (IOException e) { } r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); }
209
1
public DoSearch(String searchType, String searchString) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerDoSearch"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "search.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + key + "&search=" + URLEncoder.encode(searchString, "UTF-8") + "&searchtype=" + URLEncoder.encode(searchType, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "search.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("entry"); int num = nodelist.getLength(); searchDocs = new String[num][3]; searchDocImageName = new String[num]; searchDocsToolTip = new String[num]; for (int i = 0; i < num; i++) { searchDocs[i][0] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename"); searchDocs[i][1] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project"); searchDocs[i][2] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"); searchDocImageName[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename"); searchDocsToolTip[i] = DOMUtil.getSimpleElementText((Element) nodelist.item(i), "description"); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } System.out.println(rvalue); if (rvalue.equalsIgnoreCase("yes")) { } }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
210
0
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (text == null || text.length() < 1) { return null; } MessageDigest md = MessageDigest.getInstance(TYPE_SHA); md.update(text.getBytes(ENCODE), 0, text.length()); byte[] sha1hash = new byte[40]; sha1hash = md.digest(); return convertToHexFormat(sha1hash); }
@TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = { }) public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception { String jarFileName = ""; String entry = "text.txt"; String cts = System.getProperty("java.io.tmpdir"); File tmpDir = new File(cts); File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir); jarFileName = jarFile.getPath(); FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName); JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream)); JarEntry jarEntry = new JarEntry(entry); out.putNextEntry(jarEntry); out.write(new byte[] { 'a', 'b', 'c' }); out.close(); URL url = new URL("jar:file:" + jarFileName + "!/" + entry); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStream is = conn.getInputStream(); is.close(); assertTrue(jarFile.delete()); }
211
0
public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
public static String encrypt(String key) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.update(key.getBytes()); byte hash[] = md5.digest(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String temp = Integer.toHexString(0xFF & hash[i]); if (temp.length() == 1) temp = "0" + temp; buffer.append(temp); } return buffer.toString(); }
212
0
private void checkLogin(String email, String password) throws JspTagException { String cryptedPassword; try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(password.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } cryptedPassword = hexString.toString(); crypt.reset(); InitialContext context = new InitialContext(); java.lang.Object homeRef = context.lookup("java:comp/env/ejb/Value"); ValueHome valueHome = (ValueHome) PortableRemoteObject.narrow(homeRef, ValueHome.class); Value value = valueHome.findByPasswordCheck(email, cryptedPassword); pageContext.setAttribute("validLogin", new Boolean(true)); HttpSession session = pageContext.getSession(); session.setAttribute("jspShop.userID", value.getObjectID()); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } catch (ObjectNotFoundException e) { pageContext.setAttribute("validLogin", new Boolean(false)); } catch (NamingException e) { System.err.println("jspShop: Could not initialise context in LoginTag"); e.printStackTrace(); } catch (RemoteException e) { System.err.println("jspShop: Could not connect to container in LoginTag"); } catch (FinderException e) { System.err.println("jspShop: Error using finderQuery in LoginTag"); } }
public static void copy(String inputFile, String outputFile) throws Exception { try { FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new Exception("Could not copy " + inputFile + " into " + outputFile + " because:\n" + e.getMessage()); } }
213
1
@Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } }
public static void copyFile(File from, File to) { try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[1024 * 16]; int read = 0; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } in.close(); } catch (IOException e) { e.printStackTrace(); } }
214
1
@Override public void onClick(View v) { Log.d(Config.SS_TAG, "Sending POST request to server..."); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try { JSONObject callJson = new JSONObject(); callJson.put("method", "ping"); callJson.put("void", "null"); callsJson.put(0, callJson); requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); HttpResponse httpResponse = httpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); JSONObject result = resultsJson.getJSONObject(0); String returnValue = result.getJSONObject("data").getString("return"); Log.d(Config.SS_TAG, "Response message: " + returnValue); } else { Log.e(Config.SS_TAG, "Unsuccessful ping..."); } } catch (Exception e) { Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet"); e.printStackTrace(); } }
private static void grab(String urlString) throws MalformedURLException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); BufferedReader in = null; StringBuffer sb = new StringBuffer(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; boolean f = false; while ((inputLine = in.readLine()) != null) { inputLine = inputLine.trim(); if (inputLine.startsWith("<tbody>")) { f = true; continue; } if (inputLine.startsWith("</table>")) { f = false; continue; } if (f) { sb.append(inputLine); sb.append("\n"); } } process(sb.toString()); }
215
1
public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; }
216
1
public void postProcess() throws StopWriterVisitorException { shpWriter.postProcess(); try { FileChannel fcinShp = new FileInputStream(fTemp).getChannel(); FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel(); DriverUtilities.copy(fcinShp, fcoutShp); File shxFile = SHP.getShxFile(fTemp); FileChannel fcinShx = new FileInputStream(shxFile).getChannel(); FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel(); DriverUtilities.copy(fcinShx, fcoutShx); File dbfFile = getDataFile(fTemp); short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset()); RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); shxFile.delete(); dbfFile.delete(); reload(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (ReloadDriverException e) { throw new StopWriterVisitorException(getName(), e); } }
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
217
0
@Override public void alterar(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoMultiplaEscolha(q); } catch (SQLException e) { conexao.rollback(); throw e; } }
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
218
0
public void readCatalog(Catalog catalog, String fileUrl) throws MalformedURLException, IOException, CatalogException { URL url = null; try { url = new URL(fileUrl); } catch (MalformedURLException e) { url = new URL("file:///" + fileUrl); } debug = catalog.getCatalogManager().debug; try { URLConnection urlCon = url.openConnection(); readCatalog(catalog, urlCon.getInputStream()); } catch (FileNotFoundException e) { catalog.getCatalogManager().debug.message(1, "Failed to load catalog, file not found", url.toString()); } }
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
219
1
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public static void copy(FileInputStream from, FileOutputStream to) throws IOException { FileChannel fromChannel = from.getChannel(); FileChannel toChannel = to.getChannel(); copy(fromChannel, toChannel); fromChannel.close(); toChannel.close(); }
220
1
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
221
0
private FTPClient connect() throws IOException { FTPClient client = null; Configuration conf = getConf(); String host = conf.get("fs.ftp.host"); int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT); String user = conf.get("fs.ftp.user." + host); String password = conf.get("fs.ftp.password." + host); client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Server - " + host + " refused connection on port - " + port); } else if (client.login(user, password)) { client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE); client.setFileType(FTP.BINARY_FILE_TYPE); client.setBufferSize(DEFAULT_BUFFER_SIZE); } else { throw new IOException("Login failed on server - " + host + ", port - " + port); } return client; }
@SuppressWarnings("unchecked") public void findServiceDescriptionsAsync(FindServiceDescriptionsCallBack callBack) { String url; boolean url_valid = true; URI url_uri = getConfiguration().getUri(); url = url_uri.toString(); URLConnection urlConn_test; try { urlConn_test = (new URL(url)).openConnection(); } catch (MalformedURLException e2) { url_valid = false; e2.printStackTrace(); System.out.println("ERROR: Bad Opal service URL entered:" + url); } catch (IOException e2) { url_valid = false; e2.printStackTrace(); System.out.println("ERROR: Bad Opal service URL entered:" + url); } if (url_uri != null && url_valid == true) { System.out.println("URL entered: " + url_uri); url = url_uri.toString(); List<ServiceDescription> results = new ArrayList<ServiceDescription>(); try { URL ws_url = new URL(url); URLConnection urlConn; DataInputStream dis; try { urlConn = ws_url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); dis = new DataInputStream(urlConn.getInputStream()); String s; int fpos = 0; int lpos; int lslash; String sn; String hi; while ((s = dis.readLine()) != null) { if (s.contains("?wsdl")) { fpos = s.indexOf("\"") + 1; lpos = s.indexOf("?"); s = s.substring(fpos, lpos); if (s.startsWith("http")) s = s.substring(7); lslash = s.lastIndexOf('/'); sn = s.substring(lslash + 1); hi = s.substring(0, lslash); hi = hi.replace('/', '_'); if (!sn.equals("Version") && !sn.equals("AdminService")) { ExampleServiceDesc service = new ExampleServiceDesc(); s = sn + "_from_" + hi; service.setExampleString(s); service.setExampleUri(URI.create(url)); results.add(service); } } } dis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } callBack.partialResults(results); callBack.finished(); } }
222
0
public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } }
public Program createNewProgram(int projectID, String name, String description) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = DriverManager.getConnection(CONN_STR); connection.setAutoCommit(false); statement = connection.createStatement(); String query = "INSERT INTO Programs(projectID, name, " + "description, sourcePath) VALUES ( " + projectID + ", " + "'" + name + "', " + "'" + description + "', " + "'" + "[unknown]" + "')"; log.debug("SQL Query:\n" + query); statement.executeUpdate(query); query = "SELECT * FROM Programs WHERE " + " projectID = " + projectID + " AND " + " name = '" + name + "' AND " + " description = '" + description + "'"; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to create program failed"; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in createNewProgram"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
223
1
public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
public static void copyFile(String fileName, String dstPath) throws IOException { FileChannel sourceChannel = new FileInputStream(fileName).getChannel(); FileChannel destinationChannel = new FileOutputStream(dstPath).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
224
0
void bsort(int a[], int lo, int hi) throws Exception { for (int j = hi; j > lo; j--) { for (int i = lo; i < j; i++) { if (a[i] > a[i + 1]) { int T = a[i]; a[i] = a[i + 1]; a[i + 1] = T; pause(); } } } }
@Override public boolean postPage() { MySpaceBlogExporterGuiApp.getApplication().getWizContainer().showStatus(myResourceMap.getString("CheckingBlogUrl.text")); URL url; try { url = new URL(txtBlogUrl.getText()); URLConnection con = url.openConnection(); con.getContentType(); String newLink = con.getURL().toString(); if (!newLink.equalsIgnoreCase(txtBlogUrl.getText())) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidBlogUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } } catch (Exception ex) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } finally { MySpaceBlogExporterGuiApp.getApplication().getWizContainer().hideStatus(); } if (txtBlogUrl.getText().toLowerCase().indexOf("friendid") > 0) { JOptionPane.showMessageDialog(new JFrame(), myResourceMap.getString("InvalidBlogUrl.text"), "Error", JOptionPane.ERROR_MESSAGE); return false; } MySpaceBlogExporterGuiApp.getApplication().getMySpaceBlogExporter().setBlogUrl(txtBlogUrl.getText()); return true; }
225
0
private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } }
public static InputStream gunzip(final InputStream inputStream) throws IOException { Assert.notNull(inputStream, "inputStream"); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputOutputStream inputOutputStream = new InputOutputStream(); IOUtils.copy(gzipInputStream, inputOutputStream); return inputOutputStream.getInputStream(); }
226
1
public String hash(String text) { try { MessageDigest md = MessageDigest.getInstance(hashFunction); md.update(text.getBytes(charset)); byte[] raw = md.digest(); return new String(encodeHex(raw)); } catch (Exception e) { throw new RuntimeException(e); } }
public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
227
0
public static void checkForUpdate(String version) { try { URL url = new URL(WiimoteWhiteboard.getProperty("updateURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); final String current = in.readLine(); if (compare(version, current)) showUpdateNotification(version, current); in.close(); } catch (Exception e) { } }
private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
228
0
String fetch_pls(String pls) { InputStream pstream = null; if (pls.startsWith("http://")) { try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), pls); else url = new URL(pls); URLConnection urlc = url.openConnection(); pstream = urlc.getInputStream(); } catch (Exception ee) { System.err.println(ee); return null; } } if (pstream == null && !running_as_applet) { try { pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + pls); } catch (Exception ee) { System.err.println(ee); return null; } } String line = null; while (true) { try { line = readline(pstream); } catch (Exception e) { } if (line == null) break; if (line.startsWith("File1=")) { byte[] foo = line.getBytes(); int i = 6; for (; i < foo.length; i++) { if (foo[i] == 0x0d) break; } return line.substring(6, i); } } return null; }
static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
229
1
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
230
1
public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } }
private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
231
0
public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
private String fetchLocalPage(String page) throws IOException { final String fullUrl = HOST + page; LOG.debug("Fetching local page: " + fullUrl); URL url = new URL(fullUrl); URLConnection connection = url.openConnection(); StringBuilder sb = new StringBuilder(); BufferedReader input = null; try { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = null; while ((line = input.readLine()) != null) { sb.append(line).append("\n"); } } finally { if (input != null) try { input.close(); } catch (IOException e) { LOG.error("Could not close reader!", e); } } return sb.toString(); }
232
1
public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } }
public static String getMd5(String str) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); final byte b[] = md.digest(); int i; final StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }
233
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
234
0
public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } }
public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { } } } return url; }
235
1
public static void copyFile(String sourceName, String destName) throws IOException { FileChannel sourceChannel = null; FileChannel destChannel = null; try { sourceChannel = new FileInputStream(sourceName).getChannel(); destChannel = new FileOutputStream(destName).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException exception) { throw exception; } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException ex) { } } if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { } } } }
public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
236
0
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
public boolean urlToSpeech(String urlPath) { boolean ok = false; try { URL url = new URL(urlPath); InputStream is = url.openStream(); ok = streamToSpeech(is); } catch (IOException ioe) { System.err.println("Can't read data from " + urlPath); } return ok; }
237
0
public void readHTMLFromURL(URL url) throws IOException { InputStream in = url.openStream(); try { readHTMLFromStream(new InputStreamReader(in)); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(HTMLTextAreaModel.class.getName()).log(Level.SEVERE, "Exception while closing InputStream", ex); } } }
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
238
0
@Override public void execute(Client client, TaskProperties properties, TaskLog taskLog) throws SearchLibException { String url = properties.getValue(propUrl); URI uri; try { uri = new URI(url); } catch (URISyntaxException e) { throw new SearchLibException(e); } String login = properties.getValue(propLogin); String password = properties.getValue(propPassword); String instanceId = properties.getValue(propInstanceId); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); HttpClientParams.setRedirecting(params, true); DefaultHttpClient httpClient = new DefaultHttpClient(params); CredentialsProvider credential = httpClient.getCredentialsProvider(); if (login != null && login.length() > 0 && password != null && password.length() > 0) credential.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(login, password)); else credential.clear(); HttpPost httpPost = new HttpPost(uri); MultipartEntity reqEntity = new MultipartEntity(); new Monitor().writeToPost(reqEntity); try { reqEntity.addPart("instanceId", new StringBody(instanceId)); } catch (UnsupportedEncodingException e) { throw new SearchLibException(e); } httpPost.setEntity(reqEntity); try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity resEntity = httpResponse.getEntity(); StatusLine statusLine = httpResponse.getStatusLine(); EntityUtils.consume(resEntity); if (statusLine.getStatusCode() != 200) throw new SearchLibException("Wrong code status:" + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase()); taskLog.setInfo("Monitoring data uploaded"); } catch (ClientProtocolException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { ClientConnectionManager connectionManager = httpClient.getConnectionManager(); if (connectionManager != null) connectionManager.shutdown(); } }
private Properties loadPropertiesFromURL(String propertiesURL, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); URL url; try { url = new URL(propertiesURL); URLConnection urlConnection = url.openConnection(); properties.load(urlConnection.getInputStream()); } catch (MalformedURLException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } return properties; }
239
0
private void storeConfigurationPropertiesFile(java.net.URL url, String comp) { java.util.Properties p; try { p = new java.util.Properties(); p.load(url.openStream()); } catch (java.io.IOException ie) { System.err.println("error opening: " + url.getPath() + ": " + ie.getMessage()); return; } storeConfiguration(p, comp); return; }
public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
240
1
public void update(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String exp = channel.getExtendParent(); String path = channel.getPath(); try { String sqlStr = "UPDATE t_ip_channel SET id=?,name=?,description=?,ascii_name=?,site_id=?,type=?,data_url=?,template_id=?,use_status=?,order_no=?,style=?,creator=?,create_date=?,refresh_flag=?,page_num=? where channel_path=?"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(path, exp, connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); selfDefineAdd(selfDefinePath, channel, connection, preparedStatement); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, channel.getChannelID()); preparedStatement.setString(2, channel.getName()); preparedStatement.setString(3, channel.getDescription()); preparedStatement.setString(4, channel.getAsciiName()); preparedStatement.setInt(5, channel.getSiteId()); preparedStatement.setString(6, channel.getChannelType()); preparedStatement.setString(7, channel.getDataUrl()); if (channel.getTemplateId() == null || channel.getTemplateId().trim().equals("")) preparedStatement.setNull(8, Types.INTEGER); else preparedStatement.setInt(8, Integer.parseInt(channel.getTemplateId())); preparedStatement.setString(9, channel.getUseStatus()); preparedStatement.setInt(10, channel.getOrderNo()); preparedStatement.setString(11, channel.getStyle()); preparedStatement.setInt(12, channel.getCreator()); preparedStatement.setTimestamp(13, (Timestamp) channel.getCreateDate()); preparedStatement.setString(14, channel.getRefresh()); preparedStatement.setInt(15, channel.getPageNum()); preparedStatement.setString(16, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); int resID = channel.getChannelID() + Const.CHANNEL_TYPE_RES; StructResource sr = new StructResource(); sr.setResourceID(Integer.toString(resID)); sr.setOperateID(Integer.toString(1)); sr.setOperateTypeID(Const.OPERATE_TYPE_ID); sr.setTypeID(Const.RES_TYPE_ID); StructAuth sa = new AuthorityManager().getExternalAuthority(sr); int authID = sa.getAuthID(); if (authID == 0) { String resName = channel.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); } } catch (SQLException ex) { connection.rollback(); log.error("����Ƶ��ʧ�ܣ�channelPath=" + channel.getPath()); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
public synchronized void deleteDocument(final String file) throws IOException { SQLException ex = null; try { PreparedStatement findFileStmt = con.prepareStatement("SELECT ID AS \"ID\" FROM File_ WHERE Name = ?"); findFileStmt.setString(1, file); ResultSet rs = findFileStmt.executeQuery(); if (null != rs && rs.next()) { int fileId = rs.getInt("ID"); rs.close(); rs = null; PreparedStatement deleteTokensStmt = con.prepareStatement("DELETE FROM Token_ WHERE FieldID IN ( SELECT ID FROM Field_ WHERE FileID = ? )"); deleteTokensStmt.setInt(1, fileId); deleteTokensStmt.executeUpdate(); PreparedStatement deleteFieldsStmt = con.prepareStatement("DELETE FROM Field_ WHERE FileID = ?"); deleteFieldsStmt.setInt(1, fileId); deleteFieldsStmt.executeUpdate(); PreparedStatement deleteFileStmt = con.prepareStatement("DELETE FROM File_ WHERE ID = ?"); deleteFileStmt.setInt(1, fileId); deleteFileStmt.executeUpdate(); deleteFileStmt.close(); deleteFileStmt = null; deleteFieldsStmt.close(); deleteFieldsStmt = null; deleteTokensStmt.close(); deleteTokensStmt = null; } findFileStmt.close(); findFileStmt = null; } catch (SQLException e) { e.printStackTrace(); ex = e; try { this.con.rollback(); } catch (SQLException e2) { } } finally { try { this.con.setAutoCommit(true); } catch (SQLException e2) { } } if (null != ex) throw new IOException(ex.getMessage()); }
241
0
public static byte[] post(String path, Map<String, String> params, String encode) throws Exception { StringBuilder parambuilder = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { parambuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } parambuilder.deleteCharAt(parambuilder.length() - 1); } byte[] data = parambuilder.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Connection", "Keep-Alive"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { return StreamTool.readInputStream(conn.getInputStream()); } return null; }
@Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
242
0
public static void convert(URL url, PrintWriter writer, String server) { try { XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); XPath xpe = xpf.newXPath(); InputStream is = null; try { is = url.openStream(); } catch (IOException e) { e.printStackTrace(); } Document doc = readFromStream(is); xpe.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String s) { if (s.equals("tns")) { return "http://services.remote/"; } else if (s.equals("xsd")) { return "http://www.w3.org/2001/XMLSchema"; } else if (s.equals("soap")) { return "http://schemas.xmlsoap.org/wsdl/soap/"; } else if (s.equals(XMLConstants.DEFAULT_NS_PREFIX)) { return "http://schemas.xmlsoap.org/wsdl/"; } else { return null; } } public String getPrefix(String s) { return null; } public Iterator getPrefixes(String s) { return null; } }); Element defs = (Element) xpe.compile("/*:definitions").evaluate(doc, XPathConstants.NODE); defs.setAttribute("xmlns", "http://schemas.xmlsoap.org/wsdl/"); Node schemaLocation = (Node) xpe.compile("/*:definitions/*:types/xsd:schema/xsd:import/@schemaLocation").evaluate(doc, XPathConstants.NODE); String sl = schemaLocation.getNodeValue(); for (int i = 0; i < 3; i++) sl = sl.substring(sl.indexOf('/') + 1); schemaLocation.setNodeValue(server + "/" + sl); Node location = (Node) xpe.compile("/*:definitions/*:service/*:port/soap:address/@location").evaluate(doc, XPathConstants.NODE); String l = location.getNodeValue(); for (int i = 0; i < 3; i++) l = l.substring(l.indexOf('/') + 1); location.setNodeValue(server + "/" + l); write(doc, writer); } catch (XPathFactoryConfigurationException e) { e.printStackTrace(); System.err.println("Error:" + e); } catch (XPathExpressionException e) { e.printStackTrace(); System.err.println("Error:" + e); } }
public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } }
243
0
private void initStreams() throws IOException { if (audio != null) { audio.close(); } if (url != null) { audio = new OggInputStream(url.openStream()); } else { audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref)); } }
public final synchronized boolean isValidLicenseFile() throws LicenseNotSetupException { if (!isSetup()) { throw new LicenseNotSetupException(); } boolean returnValue = false; Properties properties = getLicenseFile(); logger.debug("isValidLicenseFile: License to validate:"); logger.debug(properties); StringBuffer validationStringBuffer = new StringBuffer(); validationStringBuffer.append(LICENSE_KEY_KEY + ":" + properties.getProperty(LICENSE_KEY_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_STATUS_KEY + ":" + properties.getProperty(LICENSE_FILE_STATUS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_USERS_KEY + ":" + properties.getProperty(LICENSE_FILE_USERS_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_MAC_KEY + ":" + properties.getProperty(LICENSE_FILE_MAC_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_HOST_NAME_KEY + ":" + properties.getProperty(LICENSE_FILE_HOST_NAME_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_OFFSET_KEY + ":" + properties.getProperty(LICENSE_FILE_OFFSET_KEY) + ","); validationStringBuffer.append(LICENSE_FILE_EXP_DATE_KEY + ":" + properties.getProperty(LICENSE_FILE_EXP_DATE_KEY) + ","); validationStringBuffer.append(LICENSE_EXPIRES_KEY + ":" + properties.getProperty(LICENSE_EXPIRES_KEY)); logger.debug("isValidLicenseFile: Validation String Buffer: " + validationStringBuffer.toString()); String validationKey = (String) properties.getProperty(LICENSE_FILE_SHA_KEY); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(validationStringBuffer.toString().getBytes()); String newValidation = Base64.encode(messageDigest.digest()); if (newValidation.equals(validationKey)) { if (getMACAddress().equals(Settings.getInstance().getMACAddress())) { returnValue = true; } } } catch (Exception exception) { System.out.println("Exception in LicenseInstanceVO.isValidLicenseFile"); } return returnValue; }
244
1
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
private void dumpFile(File repository, File copy) { try { if (copy.exists() && !copy.delete()) { throw new RuntimeException("can't delete copy: " + copy); } printFile("Real Archive File", repository); new ZipArchive(repository.getPath()); IOUtils.copyFiles(repository, copy); printFile("Copy Archive File", copy); new ZipArchive(copy.getPath()); } catch (IOException e) { e.printStackTrace(); } }
245
0
protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } }
public static String md5encrypt(String toEncrypt) { if (toEncrypt == null) { throw new IllegalArgumentException("null is not a valid password to encrypt"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncrypt.getBytes()); byte[] hash = md.digest(); return new String(dumpBytes(hash)); } catch (NoSuchAlgorithmException nsae) { return toEncrypt; } }
246
0
public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; if (connectionType.equals(SQL.ORACLE)) { url = DBCreateConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = DBCreateConfig.class.getResource("sql2k.xml"); } return url.openStream(); }
247
1
public static void main(String[] args) { Option optHelp = new Option("h", "help", false, "print this message"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", true, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { CommandLineParser parser = new PosixParser(); line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(-1); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } for (String tmpFilePath : tmpArgs) { System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(-1); } continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); System.exit(-1); } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } if (failFast && SignatureVerification.isError(tmpResult.getVerificationResultCode())) { System.exit(tmpResult.getVerificationResultCode()); } } } } }
public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; }
248
0
static byte[] getSystemEntropy() { byte[] ba; final MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException nsae) { throw new InternalError("internal error: SHA-1 not available."); } byte b = (byte) System.currentTimeMillis(); md.update(b); java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() { public Object run() { try { String s; Properties p = System.getProperties(); Enumeration e = p.propertyNames(); while (e.hasMoreElements()) { s = (String) e.nextElement(); md.update(s.getBytes()); md.update(p.getProperty(s).getBytes()); } md.update(InetAddress.getLocalHost().toString().getBytes()); File f = new File(p.getProperty("java.io.tmpdir")); String[] sa = f.list(); for (int i = 0; i < sa.length; i++) md.update(sa[i].getBytes()); } catch (Exception ex) { md.update((byte) ex.hashCode()); } Runtime rt = Runtime.getRuntime(); byte[] memBytes = longToByteArray(rt.totalMemory()); md.update(memBytes, 0, memBytes.length); memBytes = longToByteArray(rt.freeMemory()); md.update(memBytes, 0, memBytes.length); return null; } }); return md.digest(); }
public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } }
249
1
public static void copyFile(File source, File destination) throws IOException { if (!source.isFile()) { throw new IOException(source + " is not a file."); } if (destination.exists()) { throw new IOException("Destination file " + destination + " is already exist."); } FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { inChannel.close(); outChannel.close(); } }
private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
250
0
public PollSetMessage(String username, String question, String title, String[] choices) { this.username = username; MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } String id = username + String.valueOf(System.nanoTime()); m.update(id.getBytes(), 0, id.length()); voteId = new BigInteger(1, m.digest()).toString(16); this.question = question; this.title = title; this.choices = choices; }
private InputStream getManifestAsResource() { ClassLoader cl = getClass().getClassLoader(); try { Enumeration manifests = cl != null ? cl.getResources(Constants.OSGI_BUNDLE_MANIFEST) : ClassLoader.getSystemResources(Constants.OSGI_BUNDLE_MANIFEST); while (manifests.hasMoreElements()) { URL url = (URL) manifests.nextElement(); try { Headers headers = Headers.parseManifest(url.openStream()); if ("true".equals(headers.get(Constants.ECLIPSE_SYSTEMBUNDLE))) return url.openStream(); } catch (BundleException e) { } } } catch (IOException e) { } return null; }
251
0
public TwilioRestResponse request(String path, String method, Map<String, String> vars) throws TwilioRestException { String encoded = ""; if (vars != null) { for (String key : vars.keySet()) { try { encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (encoded.length() > 0) { encoded = encoded.substring(1); } } String url = this.endpoint + path; if (method.toUpperCase().equals("GET")) url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded; try { URL resturl = new URL(url); HttpURLConnection con = (HttpURLConnection) resturl.openConnection(); String userpass = this.accountSid + ":" + this.authToken; String encodeuserpass = new String(Base64.encodeToByte(userpass.getBytes(), false)); con.setRequestProperty("Authorization", "Basic " + encodeuserpass); con.setDoOutput(true); if (method.toUpperCase().equals("GET")) { con.setRequestMethod("GET"); } else if (method.toUpperCase().equals("POST")) { con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("PUT")) { con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("DELETE")) { con.setRequestMethod("DELETE"); } else { throw new TwilioRestException("Unknown method " + method); } BufferedReader in = null; try { if (con.getInputStream() != null) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { if (con.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } } if (in == null) { throw new TwilioRestException("Unable to read response from server"); } StringBuffer decodedString = new StringBuffer(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); int responseCode = con.getResponseCode(); return new TwilioRestResponse(url, decodedString.toString(), responseCode); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static AudioInputStream getWavFromURL(String urlstr) { URL url; AudioInputStream ais = null; try { url = new URL(urlstr); URLConnection c = url.openConnection(); c.connect(); InputStream stream = c.getInputStream(); ais = new AudioInputStream(stream, playFormat, AudioSystem.NOT_SPECIFIED); LOG.debug("[getWavFromURL]Getting audio from URL: {}", url); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ais; }
252
1
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
253
0
private static InputStream connect(String url) throws IOException { int status = 0; String currentlyActiveServer = getCurrentlyActiveServer(); try { long begin = System.currentTimeMillis(); HttpURLConnection httpConnection = (HttpURLConnection) new URL(currentlyActiveServer + url).openConnection(); httpConnection.setConnectTimeout(connectTimeOut); httpConnection.setReadTimeout(readTimeOut); httpConnection.setRequestProperty("User-Agent", USER_AGENT); InputStream in = httpConnection.getInputStream(); status = httpConnection.getResponseCode(); if (status == 200) { long elapsedTime = System.currentTimeMillis() - begin; averageConnectTime = (averageConnectTime * (averageSampleSize - 1) + elapsedTime) / averageSampleSize; if (geoNamesServerFailover != null && averageConnectTime > 5000 && !currentlyActiveServer.equals(geoNamesServerFailover)) { timeOfLastFailureMainServer = System.currentTimeMillis(); } return in; } } catch (IOException e) { return tryFailoverServer(url, currentlyActiveServer, 0, e); } IOException ioException = new IOException("status code " + status + " for " + url); return tryFailoverServer(url, currentlyActiveServer, status, ioException); }
public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
254
0
public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } }
@Override public void handlePeerEvent(PeerEvent event) { if (event.geteventInfo() instanceof EventServiceInfo) { EventServiceInfo info = (EventServiceInfo) event.geteventInfo(); if (info.getServiceState() != ServiceState.Deployed) return; long bid = info.getBundleId(); Bundle bundle = context.getBundle(bid); Enumeration entries = bundle.findEntries("OSGI-INF/PrivacyPolicy/", "*.xml", true); if (entries != null) { if (entries.hasMoreElements()) { try { URL url = (URL) entries.nextElement(); BufferedInputStream in = new BufferedInputStream(url.openStream()); XMLPolicyReader reader = new XMLPolicyReader(this.context); RequestPolicy policy = reader.readPolicyFromFile(in); if (policy != null) { this.policyMgr.addPrivacyPolicyForService(info.getServiceID(), policy); } } catch (IOException ioe) { } } } } }
255
1
public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); }
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
256
1
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
String extractTiffFile(String path) throws IOException { ZipInputStream in = new ZipInputStream(new FileInputStream(path)); OutputStream out = new FileOutputStream(dir + TEMP_NAME); byte[] buf = new byte[1024]; int len; ZipEntry entry = in.getNextEntry(); if (entry == null) return null; String name = entry.getName(); if (!name.endsWith(".tif")) throw new IOException("This ZIP archive does not appear to contain a TIFF file"); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return name; }
257
0
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
258
1
public static String[] parsePLS(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parsePLS"; Vector<String> radio = new Vector<String>(); final String filetoken = "file"; final String SPLITTER = "="; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { String[] s = Pattern.compile(SPLITTER).split(temp); radio.add(s[1]); Log.d(TAG, "Found audio " + s[1]); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; }
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
259
0
@SuppressWarnings("null") public static void copyFile(File src, File dst) throws IOException { if (!dst.getParentFile().exists()) { dst.getParentFile().mkdirs(); } dst.createNewFile(); FileChannel srcC = null; FileChannel dstC = null; try { srcC = new FileInputStream(src).getChannel(); dstC = new FileOutputStream(dst).getChannel(); dstC.transferFrom(srcC, 0, srcC.size()); } finally { try { if (dst != null) { dstC.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (src != null) { srcC.close(); } } catch (Exception e) { e.printStackTrace(); } } }
public String SHA1(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convToHex(sha1hash); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
260
1
public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; }
private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { } } catch (FileNotFoundException e) { } }
261
1
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.close(); }
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
262
0
@org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); }
public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
263
1
private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); }
private void copyLocalFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
264
0
public String fetchContent(PathObject file) throws NetworkException { if (file.isFetched()) { return file.getContent(); } if (!"f".equals(file.getType())) { return null; } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_ANC + file.getPath()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parsePathContent(doc, file); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
protected InputStream callApiMethod(String apiUrl, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.connect(); if (request.getResponseCode() != expected) { Error error = readResponse(Error.class, getWrappedInputStream(request.getErrorStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()))); throw createBingSearchApiClientException(error); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingSearchException(e); } }
265
0
public static void main(final String[] args) throws RecognitionException, TokenStreamException, IOException, IllegalOptionValueException, UnknownOptionException { try { CmdLineParser cmdLineParser = new CmdLineParser(); Option formatOption = cmdLineParser.addStringOption('f', "format"); Option encodingOption = cmdLineParser.addStringOption('c', "charset"); cmdLineParser.parse(args); String format = (String) cmdLineParser.getOptionValue(formatOption); String encoding = (String) cmdLineParser.getOptionValue(encodingOption); if (encoding == null || encoding.trim().equals("")) { encoding = "utf-8"; System.out.println("Defaulting to output charset utf-8 as argument -c is missing or not valid."); } String[] remainingArgs = cmdLineParser.getRemainingArgs(); if (remainingArgs.length != 2) { printUsage("Input and output file are not specified correctly. "); } File inputFile = new File(remainingArgs[0]); if (!inputFile.exists()) { printUsage("Input file " + remainingArgs[0] + " does not exist. "); } File outputFile = new File(remainingArgs[1]); if (!outputFile.exists()) { outputFile.createNewFile(); } if (format == null || format.trim().equals("")) { format = (String) FileUtil.cutExtension(outputFile.getName()).getValue(); } if ("tex".equals(format)) { Reader reader = new LatexEncoderReader(new FileReader(inputFile)); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outputFile), encoding); char[] buffer = new char[1024]; int read; do { read = reader.read(buffer); if (read > 0) { out.write(buffer, 0, read); } } while (read != -1); out.flush(); out.close(); } else { printUsage("Format not specified via argument -f. Also guessing for the extension of output file " + outputFile.getName() + " failed"); } } catch (Exception ex) { ex.printStackTrace(); printUsage(ex.getMessage()); } }
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); InputStream result = urlConnection.getInputStream(); Map<Object, Object> response = getResponse(options); if (response != null) { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } return result; } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } }
266
0
public static void main(String[] args) throws ParseException, FileNotFoundException, IOException { InputStream input = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); Translator t = new Translator(input, "UTF8"); Node template = Translator.Start(); File langs = new File("support/support/translate/languages"); for (File f : langs.listFiles()) { if (f.getName().endsWith(".lng")) { input = new BufferedInputStream(new FileInputStream(f)); try { Translator.ReInit(input, "UTF8"); } catch (java.lang.NullPointerException e) { new Translator(input, "UTF8"); } Node newFile = Translator.Start(); ArrayList<Addition> additions = new ArrayList<Addition>(); syncKeys(template, newFile, additions); ArrayList<String> fileLines = new ArrayList<String>(); Scanner scanner = new Scanner(new BufferedReader(new FileReader(f))); while (scanner.hasNextLine()) { fileLines.add(scanner.nextLine()); } int offset = 0; for (Addition a : additions) { System.out.println("Key added " + a + " to " + f.getName()); if (a.afterLine < 0 || a.afterLine >= fileLines.size()) { fileLines.add(a.getAddition(0)); } else { fileLines.add(a.afterLine + (offset++) + 1, a.getAddition(0)); } } f.delete(); Writer writer = new BufferedWriter(new FileWriter(f)); for (String s : fileLines) writer.write(s + "\n"); writer.close(); System.out.println("Language " + f.getName() + " had " + additions.size() + " additions"); } } File defFile = new File(langs, "language.lng"); defFile.delete(); defFile.createNewFile(); InputStream copyStream = new BufferedInputStream(UpdateLanguages.class.getResourceAsStream("definition_template")); OutputStream out = new BufferedOutputStream(new FileOutputStream(defFile)); int c = 0; while ((c = copyStream.read()) >= 0) out.write(c); out.close(); System.out.println("Languages updated."); }
private void updateIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { conn = getConnection(); pst1 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ?"); pst1.setInt(1, id); if (pst1.executeUpdate() >= 0) { pst2 = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst2.setInt(1, id); pst2.setString(2, ingBean.getName()); pst2.setDouble(3, ingBean.getAmount()); pst2.setInt(4, ingBean.getType()); pst2.setInt(5, ingBean.getShopFlag()); pst2.executeUpdate(); } } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
267
0
@NotNull public Set<Class<?>> in(Package pack) { String packageName = pack.getName(); String packageOnly = pack.getName(); final boolean recursive = true; Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); String packageDirName = packageOnly.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); } catch (IOException e) { throw new PackageScanFailedException("Could not read from package directory: " + packageDirName, e); } while (dirs.hasMoreElements()) { URL url = dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { try { findClassesInDirPackage(packageOnly, URLDecoder.decode(url.getFile(), "UTF-8"), recursive, classes); } catch (UnsupportedEncodingException e) { throw new PackageScanFailedException("Could not read from file: " + url, e); } } else if ("jar".equals(protocol)) { JarFile jar; try { jar = ((JarURLConnection) url.openConnection()).getJarFile(); } catch (IOException e) { throw new PackageScanFailedException("Could not read from jar url: " + url, e); } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (name.charAt(0) == '/') { name = name.substring(1); } if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); if (idx != -1) { packageName = name.substring(0, idx).replace('/', '.'); } if ((idx != -1) || recursive) { if (name.endsWith(".class") && !entry.isDirectory()) { String className = name.substring(packageName.length() + 1, name.length() - 6); add(packageName, classes, className); } } } } } } return classes; }
public GGPhotoInfo getPhotoInfo(String photoId, String language) throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.getInfo")); qparams.add(new BasicNameValuePair("key", this.key)); qparams.add(new BasicNameValuePair("photo_id", photoId)); if (null != language) { qparams.add(new BasicNameValuePair("language", language)); } String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGPhotoInfo photo = JAXB.unmarshal(content, GGPhotoInfo.class); return photo; }
268
1
private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } }
@Override public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String userAgentGroup = processUserAgent(request); final LiwenxRequest lRequest = new LiwenxRequestImpl(request, response, messageSource, userAgentGroup); Locator loc = router.route(lRequest); if (loc instanceof RedirectLocator) { response.sendRedirect(((RedirectLocator) loc).getPage()); } else { ((AbstractLiwenxRequest) lRequest).setRequestedLocator(loc); try { LiwenxResponse resp = processPage(lRequest, lRequest.getRequestedLocator(), maxRedirections); processHeaders(resp, response); processCookies(resp, response); if (resp instanceof ExternalRedirectionResponse) { response.sendRedirect(((ExternalRedirectionResponse) resp).getRedirectTo()); } else if (resp instanceof BinaryResponse) { BinaryResponse bResp = (BinaryResponse) resp; response.setContentType(bResp.getMimeType().toString()); IOUtils.copy(bResp.getInputStream(), response.getOutputStream()); } else if (resp instanceof XmlResponse) { final Element root = ((XmlResponse) resp).getXml(); Document doc = root.getDocument(); if (doc == null) { doc = new Document(root); } final Locator l = lRequest.getCurrentLocator(); final Device device = l.getDevice(); response.setContentType(calculateContentType(device)); response.setCharacterEncoding(encoding); if (device == Device.HTML) { view.processView(doc, l.getLocale(), userAgentGroup, response.getWriter()); } else { Serializer s = new Serializer(response.getOutputStream(), encoding); s.write(doc); } } } catch (PageNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (TooManyRedirectionsException e) { throw e; } catch (Exception e) { throw e; } } }
269
1
private void sendFile(File file, HttpExchange response) throws IOException { response.getResponseHeaders().add(FileUploadBase.CONTENT_LENGTH, Long.toString(file.length())); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getResponseBody()); } catch (Exception exception) { throw new IOException("error sending file", exception); } finally { IOUtils.closeQuietly(inputStream); } }
protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = new ArrayList<Datastream>(); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); tDatastreams.add(tDatastream); tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName)); return tDatastreams; }
270
1
@Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } }
public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } }
271
1
public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } }
272
1
public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
273
1
public static File writeInternalFile(Context cx, URL url, String dir, String filename) { FileOutputStream fos = null; File fi = null; try { fi = newInternalFile(cx, dir, filename); fos = FileUtils.openOutputStream(fi); int length = IOUtils.copy(url.openStream(), fos); log(length + " bytes copyed."); } catch (IOException e) { AIOUtils.log("", e); } finally { try { fos.close(); } catch (IOException e) { AIOUtils.log("", e); } } return fi; }
public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
274
0
public boolean add(String url) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("POST"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.setRequestProperty(GameRecord.GAME_MESSAGE_HEADER, message); request.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat)); request.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon)); request.setRequestProperty("Content-Length", "0"); request.connect(); if (request.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected response: " + request.getResponseCode() + " " + request.getResponseMessage()); } return true; } catch (IOException e) { e.printStackTrace(); } return false; }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { URL url = new URL("http://pubsubhubbub.appspot.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("hub.mode=publish&hub.url=" + req.getParameter("url")); out.flush(); out.close(); conn.getResponseCode(); try { resp.sendRedirect(req.getParameter("from")); } catch (Exception e) { } }
275
1
private static String retrieveVersion(InputStream is) throws RepositoryException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { IOUtils.copy(is, buffer); } catch (IOException e) { throw new RepositoryException(exceptionLocalizer.format("device-repository-file-missing", DeviceRepositoryConstants.VERSION_FILENAME), e); } return buffer.toString().trim(); }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
276
0
private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
InputStream openReader(String s) { System.err.println("Fetcher: trying url " + s); try { URL url = new URL(s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); return url.openStream(); } catch (IOException e) { } return null; }
277
0
public void callUpdate() { LOGGER.debug("Checking for Updates"); new Thread() { @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (!lastVersion.equals(G15LastfmPlayer.getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } } }.start(); }
@Override public final boolean delete() throws RecordException { if (frozen) { throw new RecordException("The object is frozen."); } Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; Class<? extends Record> actualClass = this.getClass(); StatementBuilder builder = null; try { builder = new StatementBuilder("delete from " + TableNameResolver.getTableName(actualClass) + " where id = :id"); Field f = FieldHandler.findField(this.getClass(), "id"); builder.set("id", FieldHandler.getValue(f, this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); return i == 1; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
278
1
protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } }
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
279
1
private byte[] hash(String toHash) { try { MessageDigest md5 = MessageDigest.getInstance("MD5", "BC"); md5.update(toHash.getBytes("ISO-8859-1")); return md5.digest(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; }
280
0
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath()); LOGGER.debug("Output stream: " + out.toString()); if (ServerConfiguration.isDynamicSEL()) { LOGGER.error("IS DINAMIC SEL????"); } else { } if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } else { FileInputStream in = null; try { in = new FileInputStream(realFile); int bytes = IOUtils.copy(in, out); LOGGER.debug("System resource or Allowed Client wrote bytes: " + bytes); out.flush(); } catch (Exception e) { LOGGER.error("Error while uploading over encryption system " + realFile.getName() + " file", e); } finally { IOUtils.closeQuietly(in); } } }
281
1
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
public void send(org.hibernate.Session hsession, Session session, String repositoryName, Vector files, int label, String charset) throws FilesException { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { if ((files == null) || (files.size() <= 0)) { return; } if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } Users user = getUser(hsession, repositoryName); Identity identity = getDefaultIdentity(hsession, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress _to = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); for (int i = 0; i < files.size(); i++) { MultiPartEmail email = email = new MultiPartEmail(); email.setCharset(charset); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if (_to != null) { email.addTo(_to.getAddress(), _to.getPersonal()); } MailPartObj obj = (MailPartObj) files.get(i); email.setSubject("Files-System " + obj.getName()); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); email.attach(attachment); String mid = getId(); email.addHeader(RFC2822Headers.IN_REPLY_TO, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader(RFC2822Headers.REFERENCES, "<" + mid + ".JavaMail.duroty@duroty" + ">"); email.addHeader("X-DBox", "FILES"); email.addHeader("X-DRecent", "false"); email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeMessage(mid, mime, user); } } catch (FilesException e) { throw e; } catch (Exception e) { throw new FilesException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new FilesException(ex); } catch (Throwable e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } }
282
0
private void populateAPI(API api) { try { if (api.isPopulated()) { log.traceln("Skipping API " + api.getName() + " (already populated)"); return; } api.setPopulated(true); String sql = "update API set populated=1 where name=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, api.getName()); pstmt.executeUpdate(); pstmt.close(); storePackagesAndClasses(api); conn.commit(); } catch (SQLException ex) { log.error("Store (api: " + api.getName() + ") failed!"); DBUtils.logSQLException(ex); log.error("Rolling back.."); try { conn.rollback(); } catch (SQLException inner_ex) { log.error("rollback failed!"); } } }
static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; }
283
0
public void markAsCachedHelper(Item item, Date from, Date to, Map<String, Boolean> properties) { if (properties.size() == 0) { return; } Connection conn = null; Iterable<Integer> props = representer.getInternalReps(properties.keySet()); Integer hostIndex = representer.lookUpInternalRep(item.getResolved().getHost()); HashMap<Integer, long[]> periods = new HashMap<Integer, long[]>(); for (Map.Entry<String, Boolean> e : properties.entrySet()) { periods.put(representer.lookUpInternalRep(e.getKey()), new long[] { from.getTime(), to.getTime(), e.getValue() ? 1 : 0 }); } try { conn = getConnection(); conn.setAutoCommit(false); conn.setSavepoint(); PreparedStatement stmt = null; try { stmt = conn.prepareStatement("SELECT MIN(starttime), MAX(endtime), MAX(hasvalues) FROM cachedperiods WHERE " + "id = ? AND host = ? AND prop = ? AND " + "starttime <= ? AND endtime >= ?"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(4, to.getTime()); stmt.setLong(5, from.getTime()); for (Map.Entry<Integer, long[]> e1 : periods.entrySet()) { stmt.setInt(3, e1.getKey()); ResultSet rs = stmt.executeQuery(); if (rs.next()) { e1.getValue()[0] = Math.min(rs.getLong(1), e1.getValue()[0]); e1.getValue()[1] = Math.max(rs.getLong(2), e1.getValue()[1]); e1.getValue()[2] = Math.max(rs.getInt(3), e1.getValue()[2]); } StorageUtils.close(rs); } StorageUtils.close(stmt); stmt = conn.prepareStatement("DELETE FROM cachedperiods WHERE " + "id = ? AND host = ? AND " + "starttime <= ? AND endtime >= ? AND " + "prop IN (" + StringUtils.join(props.iterator(), ",") + ")"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); stmt.setLong(3, to.getTime()); stmt.setLong(4, from.getTime()); stmt.executeUpdate(); StorageUtils.close(stmt); stmt = conn.prepareStatement("INSERT INTO cachedperiods (id, host, prop, starttime, endtime, hasvalues) VALUES (?, ?, ?, ?, ?, ?)"); stmt.setString(1, item.getResolved().getId()); stmt.setInt(2, hostIndex); for (Map.Entry<Integer, long[]> e2 : periods.entrySet()) { stmt.setInt(3, e2.getKey()); stmt.setLong(4, e2.getValue()[0]); stmt.setLong(5, e2.getValue()[1]); stmt.setInt(6, (int) e2.getValue()[2]); stmt.executeUpdate(); } } finally { StorageUtils.close(stmt); } conn.commit(); } catch (SQLException ex) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Cannot update cachedperiods table.", ex); try { conn.rollback(); } catch (SQLException ex1) { Logger.getLogger(MetaDataStoragerImpl.class.getName()).log(Level.SEVERE, "Could not roll back database, please consult system administrator.", ex1); } } finally { StorageUtils.close(conn); } }
public Configuration load(URL url) throws ConfigurationException { LOG.info("Configuring from url : " + url.toString()); try { return load(url.openStream(), url.toString()); } catch (IOException ioe) { throw new ConfigurationException("Could not configure from URL : " + url, ioe); } }
284
0
public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } }
protected void writeToResponse(InputStream stream, HttpServletResponse response) throws IOException { OutputStream output = response.getOutputStream(); try { IOUtils.copy(stream, output); } finally { try { stream.close(); } finally { output.close(); } } }
285
0
@Override public void write(OutputStream output) throws IOException, WebApplicationException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOs = new GZIPOutputStream(baos); IOUtils.copy(is, gzipOs); baos.close(); gzipOs.close(); output.write(baos.toByteArray()); }
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
286
1
public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
public boolean clonarFichero(String rutaFicheroOrigen, String rutaFicheroDestino) { System.out.println(""); System.out.println("*********** DENTRO DE 'clonarFichero' ***********"); boolean estado = false; try { FileInputStream entrada = new FileInputStream(rutaFicheroOrigen); FileOutputStream salida = new FileOutputStream(rutaFicheroDestino); FileChannel canalOrigen = entrada.getChannel(); FileChannel canalDestino = salida.getChannel(); canalOrigen.transferTo(0, canalOrigen.size(), canalDestino); entrada.close(); salida.close(); estado = true; } catch (IOException e) { System.out.println("No se encontro el archivo"); e.printStackTrace(); estado = false; } return estado; }
287
0
@Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); }
public boolean saveLecturerecordingsXMLOnWebserver() { boolean error = false; FTPClient ftp = new FTPClient(); String lecture = ""; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/lecturerecordings.jsp?seminarid=" + this.getSeminarID()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { lecture += zeile + "\n"; } in.close(); http.disconnect(); } catch (Exception e) { System.err.println("Konnte lecturerecordings.xml nicht lesen."); } try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream lectureIn = new ByteArrayInputStream(lecture.getBytes()); System.err.println("FTP Verzeichnis: " + ftp.printWorkingDirectory()); ftp.storeFile("lecturerecordings.xml", lectureIn); lectureIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } catch (NullPointerException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden. (Kein Webserver zugewiesen)"); error = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
288
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } }
289
1
private HashSet<String> href(String urlstr) throws IOException { HashSet<String> hrefs = new HashSet<String>(); URL url = new URL(urlstr); URLConnection con = url.openConnection(); con.setRequestProperty("Cookie", "_session_id=" + _session_id); InputStreamReader r = new InputStreamReader(con.getInputStream()); StringWriter b = new StringWriter(); IOUtils.copyTo(r, b); r.close(); try { Thread.sleep(WAIT_SECONDS * 1000); } catch (Exception err) { } String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]"); for (String s1 : tokens) { if (!(s1.startsWith("a") && s1.contains("href"))) continue; String tokens2[] = s1.split("[\\\"\\\']"); for (String s2 : tokens2) { if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue; hrefs.add(s2); } } return hrefs; }
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
290
0
private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } }
public static void postData(Reader data, URL endpoint, Writer output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endpoint.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
291
0
@Override protected PermissionCollection getPermissions(CodeSource _codeSource) { PermissionCollection perms = super.getPermissions(_codeSource); URL url = _codeSource.getLocation(); Permission perm = null; URLConnection urlConnection = null; try { urlConnection = url.openConnection(); urlConnection.connect(); perm = urlConnection.getPermission(); } catch (IOException excp) { perm = null; urlConnection = null; } if (perm == null) { perm = new ModulePermission(url.getHost(), "read"); } if (perm != null) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { final Permission fp = perm; AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() throws SecurityException { sm.checkPermission(fp); return null; } }, this.controlContext); } perms.add(perm); } return perms; }
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
292
1
public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; }
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
293
0
private String readDataFromUrl(URL url) throws IOException { InputStream inputStream = null; InputStreamReader streamReader = null; BufferedReader in = null; StringBuffer data = new StringBuffer(); try { inputStream = url.openStream(); streamReader = new InputStreamReader(inputStream); in = new BufferedReader(streamReader); String inputLine; while ((inputLine = in.readLine()) != null) data.append(inputLine); } finally { if (in != null) { in.close(); } if (streamReader != null) { streamReader.close(); } if (inputStream != null) { inputStream.close(); } } return data.toString(); }
public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
294
1
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } }
295
1
public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); }
296
0
static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) { String link = pkglisturlpath + "package-list"; try { boolean relative = isRelativePath(urlpath); readPackageList((new URL(link)).openStream(), urlpath, relative); } catch (MalformedURLException exc) { return getText("doclet.MalformedURL", link); } catch (IOException exc) { return getText("doclet.URL_error", link); } return null; }
public static String get(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-Agent:", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4 Safari/523.12.2"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += '\n' + s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
297
0
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnRegister) { Error.log(6002, "Bot�o cadastrar pressionado por " + login + "."); if (nameUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo nome requerido"); nameUser.setFocusable(true); return; } if (loginUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo login requerido"); loginUser.setFocusable(true); return; } String group = ""; if (groupUser.getSelectedIndex() == 0) group = "admin"; else if (groupUser.getSelectedIndex() == 1) group = "user"; else { JOptionPane.showMessageDialog(null, "Campo grupo n�o selecionado"); return; } if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int i = 1; for (i = 1; i < password1.length(); i++) { if (passwordUser1.getPassword()[i] != c) { break; } c = passwordUser1.getPassword()[i]; } if (i == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } ResultSet rs; Statement stmt; String sql; String result = ""; sql = "select login from Usuarios where login='" + loginUser.getText() + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("login"); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (result.compareTo("") != 0) { JOptionPane.showMessageDialog(null, "Login " + result + " j� existe"); loginUser.setText(""); loginUser.setFocusable(true); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } sql = "insert into Usuarios (login,password,tries_personal,tries_one_use," + "grupo,description) values " + "('" + loginUser.getText() + "','" + outputDigest + "',0,0,'" + group + "','" + nameUser.getText() + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(loginUser.getText() + ".txt", false)); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + loginUser.getText() + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + loginUser.getText() + " foi cadastrado com sucesso."); dispose(); } if (e.getSource() == btnCancel) { Error.log(6003, "Bot�o voltar de cadastrar para o menu principal pressionado por " + login + "."); dispose(); } }
298
0
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (String key : zipInfo.getEntryKeys()) { ZipEntry entry = zipInfo.getEntry(key); InputStream in = zipInfo.getInputStream(entry); File entryDest = new File(destDir, entry.getName()); entryDest.getParentFile().mkdirs(); if (!entry.isDirectory()) { OutputStream out = new FileOutputStream(new File(destDir, entry.getName())); try { IOUtils.copy(in, out); out.flush(); if (monitor != null) monitor.worked(1); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } if (monitor != null) monitor.done(); }
299