label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
0
public boolean downloadNextTLE() { boolean success = true; if (!downloadINI) { errorText = "startTLEDownload() must be ran before downloadNextTLE() can begin"; return false; } if (!this.hasMoreToDownload()) { errorText = "There are no more TLEs to download"; return false; } int i = currentTLEindex; try { URL url = new URL(rootWeb + fileNames[i]); URLConnection c = url.openConnection(); InputStreamReader isr = new InputStreamReader(c.getInputStream()); BufferedReader br = new BufferedReader(isr); File outFile = new File(localPath + fileNames[i]); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); String currentLine = ""; while ((currentLine = br.readLine()) != null) { writer.write(currentLine); writer.newLine(); } br.close(); writer.close(); } catch (Exception e) { System.out.println("Error Reading/Writing TLE - " + fileNames[i] + "\n" + e.toString()); success = false; errorText = e.toString(); return false; } currentTLEindex++; return success; }
public static String post(String url, Map params, String line_delimiter) { String response = ""; try { URL _url = new URL(url); URLConnection conn = _url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); String postdata = ""; int mapsize = params.size(); Iterator keyValue = params.entrySet().iterator(); for (int i = 0; i < mapsize; i++) { Map.Entry entry = (Map.Entry) keyValue.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (i > 0) postdata += "&"; postdata += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } wr.write(postdata); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) response += line + line_delimiter; wr.close(); rd.close(); } catch (Exception e) { System.err.println(e); } return response; }
900,500
0
public String getHashedPhoneId(Context aContext) { if (hashedPhoneId == null) { final String androidId = BuildInfo.getAndroidID(aContext); if (androidId == null) { hashedPhoneId = "EMULATOR"; } else { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(androidId.getBytes()); messageDigest.update(aContext.getPackageName().getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (byte b : messageDigest.digest()) { stringBuilder.append(String.format("%02X", b)); } hashedPhoneId = stringBuilder.toString(); } catch (Exception e) { Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e); hashedPhoneId = "Not Available"; } } } return hashedPhoneId; }
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
900,501
1
private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } }
public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); }
900,502
0
@Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
void sort(int a[]) throws Exception { for (int i = a.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (stopRequested) { return; } if (a[j] > a[j + 1]) { int T = a[j]; a[j] = a[j + 1]; a[j + 1] = T; flipped = true; } pause(i, j); } if (!flipped) { return; } } }
900,503
1
private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
public String storeUploadedZip(byte[] zip, String name) { List filesToStore = new ArrayList(); int i = 0; ZipInputStream zipIs = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry zipEntry = zipIs.getNextEntry(); while (zipEntry != null) { if (zipEntry.isDirectory() == false) { i++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zipIs, baos); baos.close(); } zipIs.closeEntry(); zipEntry = zipIs.getNextEntry(); } }
900,504
0
protected Object serveFile(MyServerSocket socket, String filenm, URL url) { PrintStream out = null; InputStream in = null; long len = 0; try { out = new PrintStream(socket.getOutputStream()); in = url.openStream(); len = in.available(); } catch (IOException e) { HttpHelper.httpWrap(HttpHelper.EXC, e.toString(), 0); } if (HttpHelper.isImage(filenm)) { out.print(HttpHelper.httpWrapPic(filenm, len)); } else if (filenm.endsWith(".html")) { Comms.copyStreamSED(in, out, MPRES); } else if (HttpHelper.isOtherFile(filenm)) { out.print(HttpHelper.httpWrapOtherFile(filenm, len)); } else { String type = MimeUtils.getMimeType(filenm); if (type.equals(MimeUtils.UNKNOWN_MIME_TYPE)) { out.print(HttpHelper.httpWrapMimeType(type, len)); } else { out.print(HttpHelper.httpWrapMimeType(type, len)); } } if (in == null) { Log.logThis("THE INPUT STREAM IS NULL...url=" + url); } else Files.copyStream(in, out); return null; }
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
900,505
1
private static String hashWithDigest(String in, String digest) { try { MessageDigest Digester = MessageDigest.getInstance(digest); Digester.update(in.getBytes("UTF-8"), 0, in.length()); byte[] sha1Hash = Digester.digest(); return toSimpleHexString(sha1Hash); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("Hashing the password failed", ex); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding the string failed", e); } }
private 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); }
900,506
0
protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
protected Connection openRelativeFile(String file) throws IOException { if (cachedBits == null) { cachedBits = new ByteArray(url.openConnection().getInputStream()).getBytes(); } ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(cachedBits)); ZipEntry zentry; while (true) { zentry = zin.getNextEntry(); if (zentry == null) { throw new IOException("Couldn't find resource " + file + " in ZIP-file"); } if (zentry.getName().equals(file)) { return new Connection(zin, zentry.getSize()); } } }
900,507
1
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
@Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } }
900,508
1
private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } }
private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception { String inputFileName = sourceRoot + extension; String outputFileName = targetRoot + extension; System.out.println("Copying resource file: " + outputFileName); File inputFile = new File(inputFileName); if (!inputFile.exists() || !inputFile.canRead()) { throw new Exception("Could not read from the file " + inputFileName); } File outputFile = new File(outputFileName); if (!outputFile.exists()) { if (!outputFile.createNewFile() || !outputFile.canWrite()) throw new Exception("Could not write to the file " + outputFileName); } FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); try { char[] buffer = new char[1024]; int nread = 0; while ((nread = in.read(buffer)) != -1) { out.write(buffer, 0, nread); } } finally { in.close(); out.close(); } }
900,509
0
public static String gerarDigest(String mensagem) { String mensagemCriptografada = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); System.out.println("Mensagem original: " + mensagem); md.update(mensagem.getBytes()); byte[] digest = md.digest(); mensagemCriptografada = converterBytesEmHexa(digest); } catch (Exception e) { e.printStackTrace(); } return mensagemCriptografada; }
public long getLastModified() { if (lastModified == 0) { if (connection == null) try { connection = url.openConnection(); } catch (IOException e) { } if (connection != null) lastModified = connection.getLastModified(); } return lastModified; }
900,510
0
public OAIRecord getRecord(String identifier, String metadataPrefix) throws OAIException { PrefixResolverDefault prefixResolver; XPath xpath; XPathContext xpathSupport; int ctxtNode; XObject list; Node node; OAIRecord rec = new OAIRecord(); priCheckBaseURL(); String params = priBuildParamString("", "", "", identifier, metadataPrefix); try { URL url = new URL(strBaseURL + "?verb=GetRecord" + params); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); if (validation == VALIDATION_VERY_STRICT) { docFactory.setValidating(true); } else { docFactory.setValidating(false); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document xml = null; try { xml = docBuilder.parse(http.getInputStream()); rec.frndSetValid(true); } catch (IllegalArgumentException iae) { throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage()); } catch (SAXException se) { if (validation != VALIDATION_LOOSE) { throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage()); } else { try { url = new URL(strBaseURL + "?verb=GetRecord" + params); http.disconnect(); http = (HttpURLConnection) url.openConnection(); http = frndTrySend(http); xml = docBuilder.parse(priCreateDummyGetRecord(identifier, http.getInputStream())); rec.frndSetValid(false); } catch (SAXException se2) { throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage()); } } } try { namespaceNode = xml.createElement("GetRecord"); namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI + "GetRecord"); namespaceNode.setAttribute("xmlns:dc", XMLNS_DC); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); xpathSupport = new XPathContext(); ctxtNode = xpathSupport.getDTMHandleFromNode(xml); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI_2_0); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:OAI-PMH/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", XMLNS_OAI_1_0 + "GetRecord"); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:GetRecord/oai:record", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); } else { xpath = new XPath("oai:OAI-PMH/oai:error", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); ixmlErrors = list.nodelist(); if (ixmlErrors.getLength() > 0) { strProtocolVersion = "2"; throw new OAIException(OAIException.OAI_ERR, getLastOAIError().getCode() + ": " + getLastOAIError().getReason()); } } } if (node != null) { rec.frndSetRepository(this); rec.frndSetMetadataPrefix(metadataPrefix); rec.frndSetIdOnly(false); ctxtNode = xpathSupport.getDTMHandleFromNode(node); xpath = new XPath("//oai:header/oai:identifier", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); rec.frndSetIdentifier(list.nodeset().nextNode().getFirstChild().getNodeValue()); xpath = new XPath("//oai:header/oai:datestamp", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); rec.frndSetDatestamp(list.nodeset().nextNode().getFirstChild().getNodeValue()); rec.frndSetRecord(node); NamedNodeMap nmap = node.getAttributes(); if (nmap != null) { if (nmap.getNamedItem("status") != null) { rec.frndSetStatus(nmap.getNamedItem("status").getFirstChild().getNodeValue()); } } } else { rec = null; } xpath = new XPath("//oai:responseDate", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { strResponseDate = node.getFirstChild().getNodeValue(); } else { if (validation == VALIDATION_LOOSE) { strResponseDate = ""; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing responseDate"); } } xpath = new XPath("//oai:requestURL | //oai:request", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node != null) { ixmlRequest = node; } else { if (validation == VALIDATION_LOOSE) { ixmlRequest = null; } else { throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing requestURL"); } } xpath = null; prefixResolver = null; xpathSupport = null; list = null; } catch (TransformerException te) { throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage()); } url = null; docFactory = null; docBuilder = null; } catch (MalformedURLException mue) { throw new OAIException(OAIException.CRITICAL_ERR, mue.getMessage()); } catch (FactoryConfigurationError fce) { throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage()); } catch (ParserConfigurationException pce) { throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage()); } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } return rec; }
@Test public final void testCheckCookies() { URL url = null; try { url = new URL("http://localhost:8080"); } catch (MalformedURLException e1) { e1.printStackTrace(); } StringBuffer content = new StringBuffer(); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; H010818)"); cookie = connection.getHeaderField("Set-Cookie"); if (cookie != null) System.out.println("cookie: " + cookie.toString()); connection.setDoInput(true); InputStream is = connection.getInputStream(); byte[] buffer = new byte[2048]; int count; while (-1 != (count = is.read(buffer))) { content.append(new String(buffer, 0, count)); } } catch (IOException e) { System.out.print(e.getMessage()); return; } }
900,511
0
private void SaveToArchive(Layer layer, String layerFileName) throws Exception { Object archiveObj = layer.getBlackboard().get("ArchiveFileName"); Object entryObj = layer.getBlackboard().get("ArchiveEntryPrefix"); if ((archiveObj == null) || (entryObj == null)) return; String archiveName = archiveObj.toString(); String entryPrefix = entryObj.toString(); if ((archiveName == "") || (entryPrefix == "")) return; File tempZip = File.createTempFile("tmp", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(archiveName)); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempZip)); copy(in, out); in.close(); out.close(); ZipFile zipFile = new ZipFile(tempZip); ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveName))); ZipInputStream zin = new ZipInputStream(new FileInputStream(tempZip)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String en = GUIUtil.nameWithoutExtension(new File(entryName)); if (en.equalsIgnoreCase(entryPrefix)) { if (entryName.endsWith(".jmp")) { String layerTaskPath = CreateArchivePlugIn.createLayerTask(layer, archiveName, entryPrefix); CreateArchivePlugIn.WriteZipEntry(layerTaskPath, entryPrefix, zout); } else if ((!entryName.endsWith(".shx")) && (!entryName.endsWith(".dbf")) && (!entryName.endsWith(".shp.xml")) && (!entryName.endsWith(".prj"))) { CreateArchivePlugIn.WriteZipEntry(layerFileName, entryPrefix, zout); } } else { zout.putNextEntry(entry); copy(zin, zout); } entry = zin.getNextEntry(); } zin.close(); zout.close(); zipFile.close(); tempZip.delete(); }
private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
900,512
1
private GmailContact convertContactToGmailContact(Contact contact) throws GmailManagerException { boolean homePhone = false, homePhone2 = false, homeFax = false, homeMobile = false, homePager = false; boolean businessPhone = false, businessPhone2 = false, businessFax = false, businessMobile = false, businessPager = false; boolean otherPhone = false, otherFax = false; if (log.isTraceEnabled()) log.trace("Converting Foundation contact to Gmail contact: Name:" + contact.getName().getFirstName().getPropertyValueAsString()); try { GmailContact gmailContact = new GmailContact(); gmailContact.setId(contact.getUid()); Name name = contact.getName(); if (name != null) if (name.getFirstName() != null && name.getFirstName().getPropertyValueAsString() != null) { StringBuffer buffer = new StringBuffer(); buffer.append(name.getFirstName().getPropertyValueAsString()).append(" "); if (name.getMiddleName() != null && name.getMiddleName().getPropertyValueAsString() != null) buffer.append(name.getMiddleName().getPropertyValueAsString()).append(" "); if (name.getLastName() != null && name.getLastName().getPropertyValueAsString() != null) buffer.append(name.getLastName().getPropertyValueAsString()).append(" "); if (log.isDebugEnabled()) log.debug("NAME: " + buffer.toString().trim()); gmailContact.setName(buffer.toString().trim()); } if (contact.getPersonalDetail() != null) { if (contact.getPersonalDetail().getEmails() != null && contact.getPersonalDetail().getEmails().size() > 0) { if (contact.getPersonalDetail().getEmails().get(0) != null) { Email email1 = (Email) contact.getPersonalDetail().getEmails().get(0); if (email1.getPropertyValueAsString() != null && email1.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL1: " + email1.getPropertyValueAsString()); gmailContact.setEmail(email1.getPropertyValueAsString()); } } if (contact.getPersonalDetail().getEmails().size() > 1 && contact.getPersonalDetail().getEmails().get(1) != null) { Email email2 = (Email) contact.getPersonalDetail().getEmails().get(1); if (email2.getPropertyValueAsString() != null && email2.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL2: " + email2.getPropertyValueAsString()); gmailContact.setEmail2(email2.getPropertyValueAsString()); } } } Address address = contact.getPersonalDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("HOME_ADDRESS: " + addressBuffer.toString()); gmailContact.setHomeAddress(addressBuffer.toString()); } Address addressOther = contact.getPersonalDetail().getOtherAddress(); if (addressOther != null) if (addressOther.getStreet() != null) if (addressOther.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(addressOther.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("OTHER_ADDRESS: " + addressBuffer.toString()); gmailContact.setOtherAddress(addressBuffer.toString()); } if (contact.getPersonalDetail().getPhones() != null && contact.getPersonalDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getPersonalDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getPersonalDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("PERSONAL_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.HOME_TELEPHONE_NUMBER) && homePhone == false) { gmailContact.setHomePhone(phone.getPropertyValueAsString()); homePhone = true; } else if (phone.getPhoneType().equals(SIFC.HOME2_TELEPHONE_NUMBER) && homePhone2 == false) { gmailContact.setHomePhone2(phone.getPropertyValueAsString()); homePhone2 = true; } else if (phone.getPhoneType().equals(SIFC.HOME_FAX_NUMBER) && homeFax == false) { gmailContact.setHomeFax(phone.getPropertyValueAsString()); homeFax = true; } else if ((phone.getPhoneType().equals(SIFC.MOBILE_TELEPHONE_NUMBER) || phone.getPhoneType().equals(SIFC.MOBILE_HOME_TELEPHONE_NUMBER)) && homeMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); homeMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); homePager = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_TELEPHONE_NUMBER) && otherPhone == false) { gmailContact.setOtherPhone(phone.getPropertyValueAsString()); otherPhone = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_FAX_NUMBER) && otherFax == false) { gmailContact.setOtherFax(phone.getPropertyValueAsString()); otherFax = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Personal Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } } if (contact.getBusinessDetail() != null) { if (contact.getBusinessDetail().getEmails() != null && contact.getBusinessDetail().getEmails().size() > 0) { if (contact.getBusinessDetail().getEmails().get(0) != null) { Email email3 = (Email) contact.getBusinessDetail().getEmails().get(0); if (email3.getPropertyValueAsString() != null && email3.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL3: " + email3.getPropertyValueAsString()); gmailContact.setEmail3(email3.getPropertyValueAsString()); } } } Address address = contact.getBusinessDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("BUSINESS_ADDRESS: " + addressBuffer.toString()); gmailContact.setBusinessAddress(addressBuffer.toString()); } if (contact.getBusinessDetail().getPhones() != null && contact.getBusinessDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getBusinessDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getBusinessDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("BUSINESS_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.BUSINESS_TELEPHONE_NUMBER) && businessPhone == false) { gmailContact.setBusinessPhone(phone.getPropertyValueAsString()); businessPhone = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS2_TELEPHONE_NUMBER) && businessPhone2 == false) { gmailContact.setBusinessPhone2(phone.getPropertyValueAsString()); businessPhone2 = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS_FAX_NUMBER) && businessFax == false) { gmailContact.setBusinessFax(phone.getPropertyValueAsString()); businessFax = true; } else if (phone.getPhoneType().equals(SIFC.MOBILE_BUSINESS_TELEPHONE_NUMBER) && homeMobile == false && businessMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); businessMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false && businessPager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); businessPager = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Business Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } if (contact.getBusinessDetail().getCompany() != null) if (contact.getBusinessDetail().getCompany().getPropertyValueAsString() != null) { if (log.isDebugEnabled()) log.debug("COMPANY: " + contact.getBusinessDetail().getCompany().getPropertyValueAsString()); gmailContact.setCompany(contact.getBusinessDetail().getCompany().getPropertyValueAsString()); } if (contact.getBusinessDetail().getTitles() != null && contact.getBusinessDetail().getTitles().size() > 0) { if (contact.getBusinessDetail().getTitles().get(0) != null) { Title title = (Title) contact.getBusinessDetail().getTitles().get(0); if (log.isDebugEnabled()) log.debug("TITLE: " + title.getPropertyValueAsString()); gmailContact.setJobTitle(title.getPropertyValueAsString()); } } } if (contact.getNotes() != null && contact.getNotes().size() > 0) { if (contact.getNotes().get(0) != null) { Note notes = (Note) contact.getNotes().get(0); if (notes.getPropertyValueAsString() != null && notes.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("NOTES: " + notes.getPropertyValueAsString()); gmailContact.setNotes(notes.getPropertyValueAsString()); } } } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(contact.toString().getBytes()); gmailContact.setMd5Hash(new BigInteger(m.digest()).toString()); return gmailContact; } catch (Exception e) { throw new GmailManagerException("GOOGLE Gmail - convertContactToGmailContact error: " + e.getMessage()); } }
public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } }
900,513
1
public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } }
public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
900,514
1
public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } }
public static String plainToMD(LoggerCollection loggerCol, String input) { byte[] byteHash = null; MessageDigest md = null; StringBuilder md4result = new StringBuilder(); try { md = MessageDigest.getInstance("MD4", new BouncyCastleProvider()); md.reset(); md.update(input.getBytes("UnicodeLittleUnmarked")); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { md4result.append(Integer.toHexString(0xFF & byteHash[i])); } } catch (UnsupportedEncodingException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } catch (NoSuchAlgorithmException ex) { loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex); } return (md4result.toString()); }
900,515
1
private synchronized void persist() { Connection conn = null; try { PoolManager pm = PoolManager.getInstance(); conn = pm.getConnection(JukeXTrackStore.DB_NAME); conn.setAutoCommit(false); Statement state = conn.createStatement(); state.executeUpdate("DELETE FROM PlaylistEntry WHERE playlistid=" + this.id); if (this.size() > 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO PlaylistEntry ( playlistid , trackid , position ) VALUES "); int location = 0; Iterator i = ll.iterator(); while (i.hasNext()) { long currTrackID = ((DatabaseObject) i.next()).getId(); sql.append('(').append(this.id).append(',').append(currTrackID).append(',').append(location++).append(')'); if (i.hasNext()) sql.append(','); } state.executeUpdate(sql.toString()); } conn.commit(); conn.setAutoCommit(true); state.close(); } catch (SQLException se) { try { conn.rollback(); } catch (SQLException ignore) { } log.error("Encountered an error persisting a playlist", se); } finally { try { conn.close(); } catch (SQLException ignore) { } } }
public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; }
900,516
1
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
private boolean copyFiles(File sourceDir, File destinationDir) { boolean result = false; try { if (sourceDir != null && destinationDir != null && sourceDir.exists() && destinationDir.exists() && sourceDir.isDirectory() && destinationDir.isDirectory()) { File sourceFiles[] = sourceDir.listFiles(); if (sourceFiles != null && sourceFiles.length > 0) { File destFiles[] = destinationDir.listFiles(); if (destFiles != null && destFiles.length > 0) { for (int i = 0; i < destFiles.length; i++) { if (destFiles[i] != null) { destFiles[i].delete(); } } } for (int i = 0; i < sourceFiles.length; i++) { if (sourceFiles[i] != null && sourceFiles[i].exists() && sourceFiles[i].isFile()) { String fileName = destFiles[i].getName(); File destFile = new File(destinationDir.getAbsolutePath() + "/" + fileName); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(sourceFiles[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } } } } result = true; } catch (Exception e) { System.out.println("Exception in copyFiles Method : " + e); } return result; }
900,517
1
public static String encrypt(String text) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
public static final String computeHash(String stringToCompile) { String retVal = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(stringToCompile.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } retVal = hexString.toString(); if (log.isDebugEnabled()) log.debug("MD5 hash for \"" + stringToCompile + "\" is: " + retVal); } catch (Exception exe) { log.error(exe.getMessage(), exe); } return retVal; }
900,518
1
public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.close(); }
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!"); }
900,519
0
public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } }
protected synchronized String encryptThis(String seed, String text) throws EncryptionException { String encryptedValue = null; String textToEncrypt = text; if (seed != null) { textToEncrypt = seed.toLowerCase() + text; } try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(textToEncrypt.getBytes("UTF-8")); encryptedValue = (new BASE64Encoder()).encode(md.digest()); } catch (Exception e) { throw new EncryptionException(e); } return encryptedValue; }
900,520
0
public Usuario insertUsuario(IUsuario usuario) throws SQLException { Connection conn = null; String insert = "insert into Usuario (idusuario, nome, email, telefone, cpf, login, senha) " + "values " + "(nextval('seq_usuario'), '" + usuario.getNome() + "', '" + usuario.getEmail() + "', " + "'" + usuario.getTelefone() + "', '" + usuario.getCpf() + "', '" + usuario.getLogin() + "', '" + usuario.getSenha() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_usuario"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { usuario.setIdUsuario(rs.getInt("last_value")); } if (usuario instanceof Requerente) { RequerenteDAO requerenteDAO = new RequerenteDAO(); requerenteDAO.insertRequerente((Requerente) usuario, conn); } else if (usuario instanceof RecursoHumano) { RecursoHumanoDAO recursoHumanoDAO = new RecursoHumanoDAO(); recursoHumanoDAO.insertRecursoHumano((RecursoHumano) usuario, conn); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } }
900,521
1
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."); } } }
@Override public String resolveItem(String oldJpgFsPath) throws DatabaseException { if (oldJpgFsPath == null || "".equals(oldJpgFsPath)) throw new NullPointerException("oldJpgFsPath"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement statement = null; String ret = null; try { statement = getConnection().prepareStatement(SELECT_ITEM_STATEMENT); statement.setString(1, oldJpgFsPath); ResultSet rs = statement.executeQuery(); int i = 0; int id = -1; int rowsAffected = 0; while (rs.next()) { id = rs.getInt("id"); ret = rs.getString("imageFile"); i++; } if (id != -1 && new File(ret).exists()) { statement = getConnection().prepareStatement(UPDATE_ITEM_STATEMENT); statement.setInt(1, id); rowsAffected = statement.executeUpdate(); } else { return null; } if (rowsAffected == 1) { getConnection().commit(); LOGGER.debug("DB has been updated."); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback!"); } } catch (SQLException e) { LOGGER.error(e); } finally { closeConnection(); } return ret; }
900,522
0
public static String encrypt(String plaintext) throws Exception { String algorithm = XML.get("security.algorithm"); if (algorithm == null) algorithm = "SHA-1"; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); }
private LSInput resolveResource(String aPublicId, String aSystemId, String aBaseURI, boolean baseUsed) { LSInput lsInput = new DefaultLSInput(); lsInput.setPublicId(aPublicId); lsInput.setSystemId(aSystemId); String base = null; try { int baseEndPos = -1; if (aBaseURI != null) { baseEndPos = aBaseURI.lastIndexOf("/"); } if (baseEndPos <= 0) { if (baseUsed) { return null; } else { return resolveResource(aPublicId, aSystemId, schemaBasePath + "/" + aSystemId, true); } } base = aBaseURI.substring(0, baseEndPos); URL url = new URL(base + "/" + aSystemId); lsInput.setByteStream(url.openConnection().getInputStream()); return lsInput; } catch (IOException e) { return resolveResource(aPublicId, aSystemId, base, baseUsed); } }
900,523
1
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(); } }
private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
900,524
1
public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
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) { ; } } }
900,525
0
public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } }
900,526
0
public void downSync(Vector v) throws SQLException { try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cal_Event set owner=?,subject=?,text=?,place=?," + "contactperson=?,startdate=?,enddate=?,starttime=?,endtime=?,allday=?," + "syncstatus=?,dirtybits=? where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cal_Event (owner,subject,text,place," + "contactperson,startdate,enddate,starttime,endtime,allday,syncstatus," + "dirtybits) values(?,?,?,?,?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cal_Event", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cal_Event_Remind where event=?"); PreparedStatement delete2 = con.prepareStatement("delete from cal_Event where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (EventDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getSubject()); insert.setString(3, DO.getText()); insert.setString(4, DO.getPlace()); insert.setString(5, DO.getContactperson()); insert.setDate(6, DO.getStartdate()); insert.setDate(7, DO.getEnddate()); insert.setTime(8, DO.getStarttime()); insert.setTime(9, DO.getEndtime()); insert.setBoolean(10, DO.getAllday()); insert.setInt(11, RESET); insert.setInt(12, RESET); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getSubject()); update.setString(3, DO.getText()); update.setString(4, DO.getPlace()); update.setString(5, DO.getContactperson()); update.setDate(6, DO.getStartdate()); update.setDate(7, DO.getEnddate()); update.setTime(8, DO.getStarttime()); update.setTime(9, DO.getEndtime()); update.setBoolean(10, DO.getAllday()); update.setInt(11, RESET); update.setInt(12, RESET); update.setBigDecimal(13, DO.getOId()); update.setInt(14, RESET); con.executeUpdate(update, null); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); } else { con.commit(); } } catch (Exception e) { con.rollback(); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-EventDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } }
String digest(final UserAccountEntity account) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(account.getUserId().getBytes("UTF-8")); digest.update(account.getLastLogin().toString().getBytes("UTF-8")); digest.update(account.getPerson().getGivenName().getBytes("UTF-8")); digest.update(account.getPerson().getSurname().getBytes("UTF-8")); digest.update(account.getPerson().getEmail().getBytes("UTF-8")); digest.update(m_random); return new String(Base64.altEncode(digest.digest())); } catch (final Exception e) { LOG.error("Exception", e); throw new RuntimeException(e); } }
900,527
0
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException 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); } }
public void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
900,528
1
public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
900,529
0
public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
public InputStream getFtpInputStream() throws IOException { try { URL url = getURL(); URLConnection urlc = url.openConnection(); return urlc.getInputStream(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
900,530
1
public static String encrypt(String password, String algorithm, byte[] salt) { StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); }
public String getMd5CodeOf16(String str) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte b[] = md.digest(); int i; 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)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return buf.toString().substring(8, 24); } }
900,531
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!"); }
private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); }
900,532
0
public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception { int noOfComponents = m_components.length; Statement statement = null; StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating "); pmNoteBuf.append(m_itemNameAbbrev); pmNoteBuf.append(" "); pmNoteBuf.append(m_itemNameValue); final String pmNote = pmNoteBuf.toString(); progressMonitor.setNote(pmNote); try { conn.setAutoCommit(false); int id = -1; if (m_update) { statement = conn.createStatement(); String sql = getUpdateSql(noOfComponents, m_id); statement.executeUpdate(sql); id = m_id; if (m_indexesChanged) deleteComponents(conn, id); } else { PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents); pStmt.executeUpdate(); Integer res = DbCommon.getAutoGenId(parent, context, pStmt); if (res == null) return; id = res.intValue(); } if (!m_update || m_indexesChanged) { PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql()); for (int i = 0; i < noOfComponents; i++) { createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt); } } conn.commit(); m_itemTable.getPrimaryId().setVal(m_item, id); m_itemCache.updateCache(m_item, id); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
900,533
0
private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); }
private int addPollToDB(DataSource database) { int pollid = -2; Connection con = null; try { con = database.getConnection(); con.setAutoCommit(false); String add = "insert into polls" + " values( ?, ?, ?, ?)"; PreparedStatement prepStatement = con.prepareStatement(add); prepStatement.setString(1, selectedCourse.getAdmin()); prepStatement.setString(2, selectedCourse.getCourseId()); prepStatement.setString(3, getTitle()); prepStatement.setInt(4, 0); prepStatement.executeUpdate(); String findNewID = "select max(pollid) from polls"; prepStatement = con.prepareStatement(findNewID); ResultSet newID = prepStatement.executeQuery(); pollid = -2; while (newID.next()) { pollid = newID.getInt(1); } if (pollid == -2) { this.sqlError = true; throw new Exception(); } String[] options = getAllOptions(); for (int i = 0; i < 4; i++) { String insertOption = "insert into polloptions values ( ?, ?, ? )"; prepStatement = con.prepareStatement(insertOption); prepStatement.setString(1, options[i]); prepStatement.setInt(2, 0); prepStatement.setInt(3, pollid); prepStatement.executeUpdate(); } prepStatement.close(); con.commit(); } catch (Exception e) { sqlError = true; e.printStackTrace(); if (con != null) try { con.rollback(); } catch (Exception logOrIgnore) { } try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } finally { if (con != null) try { con.close(); } catch (Exception logOrIgnore) { } } return pollid; }
900,534
0
public static void downloadImage(File file, String imageUrl) throws IOException { int size = 0; int copied = 0; InputStream in = null; FileOutputStream out = null; try { URL url; url = new URL(imageUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(false); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); size = httpURLConnection.getContentLength(); in = httpURLConnection.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int n = 0; int percent = 0; int lastPercent = 0; while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); copied += n; percent = copied * 100 / size; if (lastPercent != percent) { lastPercent = percent; String message = MessageUtils.getMessage(JWallpaperChanger.class, "downloadPercent", "" + percent + "%"); Platform.getPlatform().setTrayCaption(message); } } out.flush(); } finally { Platform.getPlatform().setTrayCaption(null); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); }
900,535
0
public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); }
public void setDefaultDomain(final int domainId) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("domain.setDefaultDomainId")); psImpl.setInt(1, domainId); psImpl.executeUpdate(); } }); connection.commit(); cm.updateDefaultDomain(); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
900,536
0
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
public static JSONObject doJSONQuery(String urlstr) throws IOException, MalformedURLException, JSONException, SolrException { URL url = new URL(urlstr); HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuffer buffer = new StringBuffer(); String str; while ((str = in.readLine()) != null) { buffer.append(str + "\n"); } in.close(); JSONObject response = new JSONObject(buffer.toString()); return response; } catch (IOException e) { if (con != null) { try { int statusCode = con.getResponseCode(); if (statusCode >= 400) { throw (new SolrSelectUtils()).new SolrException(statusCode); } } catch (IOException exc) { } } throw (e); } }
900,537
0
public static void copyFile(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(); } } }
PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
900,538
0
private List<String> getRobots(String beginURL, String contextRoot) { List<String> vtRobots = new ArrayList<String>(); BufferedReader bfReader = null; try { URL urlx = new URL(beginURL + "/" + contextRoot + "/" + "robots.txt"); URLConnection urlConn = urlx.openConnection(); urlConn.setUseCaches(false); bfReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String sxLine = ""; while ((sxLine = bfReader.readLine()) != null) { if (sxLine.startsWith("Disallow:")) { vtRobots.add(sxLine.substring(10)); } } } catch (Exception e) { PetstoreUtil.getLogger().log(Level.SEVERE, "Exception" + e); vtRobots = null; } finally { try { if (bfReader != null) { bfReader.close(); } } catch (Exception ee) { } } return vtRobots; }
public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); }
900,539
1
public static void copyFile(File src, File dest) { try { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ioe) { System.err.println(ioe); } }
public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!generatedOutputDirectory.exists()) { generatedOutputDirectory.createFolder(); } if (outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/service/xdoc/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.xml"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } } { Writer out = null; try { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = generatedOutputDirectory.resolveFile("index.xml"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
900,540
0
public boolean deploy(MMedia[] media) { if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) { log.warning("You have not defined your own server, we will not really deploy to localhost!"); return true; } FTPClient ftp = new FTPClient(); try { ftp.connect(getIP_Address()); if (ftp.login(getUserName(), getPassword())) log.info("Connected to " + getIP_Address() + " as " + getUserName()); else { log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName()); return false; } } catch (Exception e) { log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e); return false; } boolean success = true; String cmd = null; try { cmd = "cwd"; ftp.changeWorkingDirectory(getFolder()); cmd = "list"; String[] fileNames = ftp.listNames(); log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length); cmd = "bin"; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); for (int i = 0; i < media.length; i++) { if (!media[i].isSummary()) { log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension()); MImage thisImage = media[i].getImage(); byte[] buffer = thisImage.getData(); ByteArrayInputStream is = new ByteArrayInputStream(buffer); String fileName = media[i].get_ID() + media[i].getExtension(); cmd = "put " + fileName; ftp.storeFile(fileName, is); is.close(); } } } catch (Exception e) { log.log(Level.WARNING, cmd, e); success = false; } try { cmd = "logout"; ftp.logout(); cmd = "disconnect"; ftp.disconnect(); } catch (Exception e) { log.log(Level.WARNING, cmd, e); } ftp = null; return success; }
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException { try { if (vtf == null) { LOG.debug("Serializing from database"); existDocument.stream(out); } else { LOG.debug("Serializing from buffer"); InputStream is = vtf.getByteStream(); IOUtils.copy(is, out); out.flush(); IOUtils.closeQuietly(is); vtf.delete(); vtf = null; } } catch (PermissionDeniedException e) { LOG.debug(e.getMessage()); throw new NotAuthorizedException(this); } finally { IOUtils.closeQuietly(out); } }
900,541
0
public static String MD5Encode(String password) { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } return buf.toString(); } catch (NoSuchAlgorithmException e) { return password; } }
@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET) public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception { File file = new File(STORAGE_PATH + fileName + ".jpg"); res.setHeader("Cache-Control", "no-store"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); res.setContentType("image/jpg"); ServletOutputStream ostream = res.getOutputStream(); IOUtils.copy(new FileInputStream(file), ostream); ostream.flush(); ostream.close(); }
900,542
0
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) { } } } }
private void downloadFtp(File file, URL jurl) throws SocketException, IOException { System.out.println("downloadFtp(" + file + ", " + jurl + ")"); FTPClient client = new FTPClient(); client.addProtocolCommandListener(new ProtocolCommandListener() { public void protocolCommandSent(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } public void protocolReplyReceived(ProtocolCommandEvent event) { System.out.println("downloadFtp: " + event.getMessage()); } }); try { client.connect(jurl.getHost(), -1 == jurl.getPort() ? FTP.DEFAULT_PORT : jurl.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { client.disconnect(); throw new IOException("FTP server refused connection."); } if (!client.login("anonymous", "anonymous")) { client.logout(); throw new IOException("Authentication failure."); } client.setFileType(FTP.BINARY_FILE_TYPE); client.enterLocalPassiveMode(); FileOutputStream out = new FileOutputStream(file); boolean ok = client.retrieveFile(jurl.getPath(), out); out.close(); client.logout(); if (!ok) { throw new IOException("File transfer failure."); } } catch (IOException e) { throw e; } finally { if (client.isConnected()) { try { client.disconnect(); } catch (IOException e) { } } } }
900,543
0
public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new ProjectEditPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
private List<Feature> getFeatures(String source, EntryPoint e) throws MalformedURLException, SAXException, IOException, ParserConfigurationException, URISyntaxException { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); FeatureParser featp = new FeatureParser(); parser.parse(URIFactory.url(serverPrefix + "/das/" + source + "/features?segment=" + e.id + ":" + e.start + "," + e.stop).openStream(), featp); return featp.list; }
900,544
1
public boolean copy(Class<?> subCls, String subCol, long id) { boolean bool = false; this.result = null; Connection conn = null; Object vo = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PojoParser parser = PojoParser.getInstances(); String sql = SqlUtil.getInsertSql(this.getCls()); vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id); String pk = parser.getPriamryKey(cls); this.getCls().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 }); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, vo); ps.executeUpdate(); ps.close(); long key = this.id; parser = PojoParser.getInstances(); sql = SqlUtil.getInsertSql(subCls); Class<?> clses = this.cls; this.cls = subCls; ps = conn.prepareStatement("select * from " + parser.getTableName(subCls) + " where " + subCol + "=" + id); this.assembleObjToList(ps); ps = conn.prepareStatement(sql); ids = new long[orgList.size()]; Method m = subCls.getMethod("set" + SqlUtil.getFieldName(subCol), new Class[] { long.class }); for (int i = 0; i < orgList.size(); ++i) { Object obj = orgList.get(i); subCls.getMethod("set" + SqlUtil.getFieldName(parser.getPriamryKey(subCls)), new Class[] { long.class }).invoke(obj, new Object[] { 0 }); m.invoke(obj, new Object[] { key }); setPsParams(ps, obj); ps.addBatch(); if ((i % 100) == 0) ps.executeBatch(); ids[i] = this.id; } ps.executeBatch(); ps.close(); conn.commit(); this.cls = clses; this.id = key; bool = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { ex.printStackTrace(); } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from WebServices where WebServiceId = " + id); stmt.executeUpdate("delete from WebServiceParams where WebServiceId = " + id); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
900,545
1
public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
public static String cryptoSHA(String _strSrc) { try { BASE64Encoder encoder = new BASE64Encoder(); MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(_strSrc.getBytes()); byte[] buffer = sha.digest(); return encoder.encode(buffer); } catch (Exception err) { System.out.println(err); } return ""; }
900,546
1
@Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); String encodedRawPass = new String(digest.digest(rawPass.getBytes("UTF-8"))); return encodedRawPass.equals(encPass); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = -302443565702455874L; }; } }
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
900,547
1
protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) { String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.'); String methodName = getMethodName(par); String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName; PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey); if (gr != null) { _sharedAddData.cacheInfo.incCombinePredicateCacheHit(); return gr; } else { _sharedAddData.cacheInfo.incCombinePredicateCacheMiss(); } String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred"; ClassFile predicateCF = null; File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class"); if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) { try { predicateCF = new ClassFile(new FileInputStream(clonedFile)); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe); } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { _templatePredicateClassFile.write(baos); predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray())); } catch (IOException ioe) { throw new ThreadCheckException("Could not open predicate template class file", ioe); } } clonedFile.getParentFile().mkdirs(); final ArrayList<String> paramNames = new ArrayList<String>(); final HashMap<String, String> paramTypes = new HashMap<String, String>(); performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() { public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) { paramNames.add(param1); paramTypes.put(param1, param2); return null; } }, ""); ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>(); for (String key : par.combinedPredicates.keySet()) { for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) { if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) { memberPARs.add(memberPAR); } else { memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor)); } } } AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool()); int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem }); predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem }); predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null); predicateCF.setThisClass(predicateClassItem); StringBuilder sb = new StringBuilder(); sb.append("(Ljava/lang/Object;"); if (par.passArguments) { sb.append("[Ljava/lang/Object;"); } for (String key : paramNames) { sb.append(paramTypes.get(key)); } sb.append(")Z"); String methodDesc = sb.toString(); MethodInfo templateMI = null; MethodInfo predicateMI = null; for (MethodInfo mi : predicateCF.getMethods()) { if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) { predicateMI = mi; break; } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) { templateMI = mi; } } if ((templateMI == null) && (predicateMI == null)) { throw new ThreadCheckException("Could not find template predicate method in class file"); } if (predicateMI == null) { AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi }); namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool()); l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi }); descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null); ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>(); for (AAttributeInfo a : templateMI.getAttributes()) { try { AAttributeInfo clonedA = (AAttributeInfo) a.clone(); list.add(clonedA); } catch (CloneNotSupportedException e) { throw new InstrumentorException("Could not clone method attributes"); } } predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {})); predicateCF.getMethods().add(predicateMI); CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties(); props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0); InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode()); if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) { il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); } else { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); } boolean res; res = il.advanceIndex(); assert res == true; int accumVarIndex = props.maxLocals - 1; AInstruction loadAccumInstr; AInstruction storeAccumInstr; if (accumVarIndex < 256) { loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex); storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex); } else { byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 }; Types.bytesFromShort((short) accumVarIndex, bytes, 1); loadAccumInstr = new WideInstruction(bytes); bytes[0] = Opcode.ISTORE; storeAccumInstr = new WideInstruction(bytes); } il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int maxStack = 0; int paramIndex = 1; int lvIndex = 1; if (par.passArguments) { lvIndex += 1; } int memberCount = 0; for (PredicateAnnotationRecord memberPAR : memberPARs) { ++memberCount; il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int curStack = 1; if (memberPAR.passArguments) { if (par.passArguments) { il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; curStack += 1; } } for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) { String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex)); if (t.length() == 0) { throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } byte opcode; int nextLVIndex = lvIndex; switch(t.charAt(0)) { case 'I': case 'B': case 'C': case 'S': case 'Z': opcode = Opcode.ILOAD; nextLVIndex += 1; curStack += 1; break; case 'F': opcode = Opcode.FLOAD; nextLVIndex += 1; curStack += 1; break; case '[': case 'L': opcode = Opcode.ALOAD; nextLVIndex += 1; curStack += 1; break; case 'J': opcode = Opcode.LLOAD; nextLVIndex += 2; curStack += 2; break; case 'D': opcode = Opcode.DLOAD; nextLVIndex += 2; curStack += 2; break; default: throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName()); } AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex); il.insertInstr(load, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; ++paramIndex; lvIndex = nextLVIndex; } if (curStack > maxStack) { maxStack = curStack; } ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0); int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString()); predicateCallInstr.setReference(predicateCallIndex); il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) { il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; if (par.combineMode == Combine.Mode.OR) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) { il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo()); } else if (par.combineMode == Combine.Mode.IMPLIES) { il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo()); } else { assert false; } res = il.advanceIndex(); assert res == true; il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } if (par.combineMode == Combine.Mode.XOR) { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1); il.insertInstr(br2, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; int jumpIndex = il.getIndex(); il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; res = il.rewindIndex(3); assert res == true; BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex); il.insertInstr(br1, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(4); assert res == true; } else { il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo()); res = il.advanceIndex(); assert res == true; } il.deleteInstr(predicateMI.getCodeAttributeInfo()); predicateMI.getCodeAttributeInfo().setCode(il.getCode()); props.maxStack = Math.max(maxStack, 2); predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals); try { FileOutputStream fos = new FileOutputStream(clonedFile); predicateCF.write(fos); fos.close(); } catch (IOException e) { throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile); } } gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>()); _generatedPredicateRecords.put(hashKey, gr); return gr; }
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(); }
900,548
1
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public static void copyFile(File source, File dest) { try { FileChannel in = new FileInputStream(source).getChannel(); if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); FileChannel out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
900,549
1
private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } }
public void objectParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int indexLastSeparator; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("object"); } else { nl = doc_[currentquestion].getElementsByTagName("object"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("data"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getFile(); sOldPath = sOldPath.replace('/', File.separatorChar); indexLastSeparator = sOldPath.lastIndexOf(File.separatorChar); String sSourcePath = sOldPath; sFilename = sOldPath.substring(indexLastSeparator + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
900,550
0
public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
900,551
0
public static void httpOnLoad(String fileName, String urlpath) throws Exception { URL url = new URL(urlpath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); int responseCode = conn.getResponseCode(); System.err.println("Code : " + responseCode); System.err.println("getResponseMessage : " + conn.getResponseMessage()); if (responseCode >= 400) { return; } int threadSize = 3; int fileLength = conn.getContentLength(); System.out.println("fileLength:" + fileLength); int block = fileLength / threadSize; int lastBlock = fileLength - (block * (threadSize - 1)); conn.disconnect(); File file = new File(fileName); RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); randomFile.setLength(fileLength); randomFile.close(); for (int i = 2; i < 3; i++) { int startPosition = i * block; if (i == threadSize - 1) { block = lastBlock; } RandomAccessFile threadFile = new RandomAccessFile(file, "rw"); threadFile.seek(startPosition); new TestDownFile(url, startPosition, threadFile, block).start(); } }
public void xtestURL2() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL2.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
900,552
1
private void SaveLoginInfo() { int iSize; try { if (m_bSavePwd) { byte[] MD5PWD = new byte[80]; java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-1"); String szPath = System.getProperty("user.home"); szPath += System.getProperty("file.separator") + "MochaJournal"; java.io.File file = new java.io.File(szPath); if (!file.exists()) file.mkdirs(); file = new java.io.File(file, "user.dat"); if (!file.exists()) file.createNewFile(); java.io.FileOutputStream pw = new java.io.FileOutputStream(file); iSize = m_PwdList.size(); for (int iIndex = 0; iIndex < iSize; iIndex++) { md.reset(); md.update(((String) m_UsrList.get(iIndex)).getBytes()); byte[] DESUSR = md.digest(); byte alpha = 0; for (int i = 0; i < DESUSR.length; i++) alpha += DESUSR[i]; String pwd = (String) m_PwdList.get(iIndex); if (pwd.length() > 0) { java.util.Arrays.fill(MD5PWD, (byte) 0); int iLen = pwd.length(); pw.write(iLen); for (int i = 0; i < iLen; i++) { int iDiff = (int) pwd.charAt(i) + (int) alpha; int c = iDiff % 256; MD5PWD[i] = (byte) c; pw.write((byte) c); } } else pw.write(0); } pw.flush(); } } catch (java.security.NoSuchAlgorithmException e) { System.err.println(e); } catch (java.io.IOException e3) { System.err.println(e3); } }
private void getRandomGUID(boolean secure) throws NoSuchAlgorithmException { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); throw 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); } }
900,553
0
public void addUser(String name, String unit, String organizeName, int userId, int orgId, String email) { Connection connection = null; PreparedStatement ps = null; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { connection = dbo.getConnection(); ps = connection.prepareStatement(INSERT_USER); ps.setInt(1, AddrslistMainDao.getNewID()); ps.setInt(2, -100); ps.setString(3, name.substring(0, 1)); ps.setString(4, name.substring(1)); ps.setString(5, unit); ps.setString(6, organizeName); ps.setString(7, ""); ps.setString(8, email); ps.setString(9, ""); ps.setString(10, ""); ps.setString(11, ""); ps.setString(12, ""); ps.setString(13, ""); ps.setString(14, ""); ps.setString(15, ""); ps.setString(16, ""); ps.setString(17, ""); ps.setString(18, ""); ps.setInt(19, userId); ps.setInt(20, orgId); ps.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { ps.close(); connection.close(); dbo.close(); } catch (Exception e) { } } }
private void handleServerIntroduction(DataPacket serverPacket) { DataPacketIterator iter = serverPacket.getDataPacketIterator(); String version = iter.nextString(); int serverReportedUDPPort = iter.nextUByte2(); _authKey = iter.nextUByte4(); _introKey = iter.nextUByte4(); _clientKey = makeClientKey(_authKey, _introKey); String passwordKey = iter.nextString(); _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort); DataPacket packet = null; if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) { ParameterBuilder builder = new ParameterBuilder(); builder.appendUByte2(_udpSocket.getLocalPort()); builder.appendString(_user); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ignore) { } md5.update(_serverKey.getBytes()); md5.update(passwordKey.getBytes()); md5.update(_password.getBytes()); for (byte b : md5.digest()) { builder.appendByte(b); } packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter()); } else { packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY); } sendTCPPacket(packet); }
900,554
0
private void insertService(String table, int type) { Connection con = null; log.info(""); log.info("正在生成" + table + "的服务。。。。。。。"); try { con = DODataSource.getDefaultCon(); con.setAutoCommit(false); Statement stmt = con.createStatement(); Statement stmt2 = con.createStatement(); String serviceUid = UUIDHex.getInstance().generate(); DOBO bo = DOBO.getDOBOByName(StringUtil.getDotName(table)); List props = new ArrayList(); StringBuffer mainSql = null; String name = ""; String l10n = ""; String prefix = StringUtil.getDotName(table); Boolean isNew = null; switch(type) { case 1: name = prefix + ".insert"; l10n = name; props = bo.retrieveProperties(); mainSql = getInsertSql(props, table); isNew = Boolean.TRUE; break; case 2: name = prefix + ".update"; l10n = name; props = bo.retrieveProperties(); mainSql = this.getModiSql(props, table); isNew = Boolean.FALSE; break; case 3: DOBOProperty property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); System.out.println("BOBOBO::::::" + bo); System.out.println("Property::::::" + property); if (property == null) { return; } name = prefix + ".delete"; l10n = name; props.add(property); mainSql = new StringBuffer("delete from ").append(table).append(" where objuid = ?"); break; case 4: property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); if (property == null) { return; } name = prefix + ".browse"; l10n = name; props.add(property); mainSql = new StringBuffer("select * from ").append(table).append(" where objuid = ?"); break; case 5: name = prefix + ".list"; l10n = name; mainSql = new StringBuffer("select * from ").append(table); } this.setParaLinkBatch(props, stmt2, serviceUid, isNew); StringBuffer aSql = new StringBuffer("insert into DO_Service(objuid,l10n,name,bouid,mainSql) values(").append("'").append(serviceUid).append("','").append(l10n).append("','").append(name).append("','").append(this.getDOBOUid(table)).append("','").append(mainSql).append("')"); log.info("Servcice's Sql:" + aSql.toString()); stmt.executeUpdate(aSql.toString()); stmt2.executeBatch(); con.commit(); } catch (SQLException ex) { try { con.rollback(); } catch (SQLException ex2) { ex2.printStackTrace(); } ex.printStackTrace(); } finally { try { if (!con.isClosed()) { con.close(); } } catch (SQLException ex1) { ex1.printStackTrace(); } } }
public static String readFromUrl(String url) { URL url_ = null; URLConnection uc = null; BufferedReader in = null; StringBuilder str = new StringBuilder(); try { url_ = new URL(url); uc = url_.openConnection(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) str.append(inputLine); in.close(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); }
900,555
1
public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } }
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
900,556
1
private String listaArquivo() { String arquivo = ""; String linha = ""; try { URL url = new URL(this.getCodeBase(), "./listador?dir=" + "cenarios" + "/" + user); URLConnection con = url.openConnection(); con.setUseCaches(false); InputStream in = con.getInputStream(); DataInputStream result = new DataInputStream(new BufferedInputStream(in)); while ((linha = result.readLine()) != null) { arquivo += linha + "\n"; } return arquivo; } catch (Exception e) { return null; } }
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]); } ; }
900,557
1
protected Set<String> moduleNamesFromReader(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); Set<String> names = new HashSet<String>(); String line; while ((line = reader.readLine()) != null) { line = line.trim(); Matcher m = nonCommentPattern.matcher(line); if (m.find()) { names.add(m.group().trim()); } } return names; }
private static List retrieveQuotes(Report report, Symbol symbol, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
900,558
0
public ActionForward dbExecute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws DatabaseException { Integer key; SubmitUserForm form = (SubmitUserForm) pForm; if (pRequest.getParameter("key") == null) { key = form.getPrimaryKey(); } else { key = Integer.parseInt(pRequest.getParameter("key")); } User currentUser = (User) (pRequest.getSession().getAttribute("login")); if ((currentUser == null) || (!currentUser.getAdminRights() && (currentUser.getPrimaryKey() != key))) { return (pMapping.findForward("denied")); } if (currentUser.getAdminRights()) { pRequest.setAttribute("isAdmin", new Boolean(true)); } if (currentUser.getPDFRights()) { pRequest.setAttribute("pdfRights", Boolean.TRUE); } User user = database.acquireUserByPrimaryKey(key); if (user.isSuperAdmin() && !currentUser.isSuperAdmin()) { return (pMapping.findForward("denied")); } pRequest.setAttribute("user", user); pRequest.setAttribute("taxonomy", database.acquireTaxonomy()); if (form.getAction().equals("none")) { form.setPrimaryKey(user.getPrimaryKey()); } if (form.getAction().equals("edit")) { FormError formError = form.validateFields(); if (formError != null) { if (formError.getFormFieldErrors().get("firstName") != null) { pRequest.setAttribute("FirstNameBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("lastName") != null) { pRequest.setAttribute("LastNameBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("emailAddress") != null) { pRequest.setAttribute("EmailAddressBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("mismatchPassword") != null) { pRequest.setAttribute("mismatchPassword", new Boolean(true)); } if (formError.getFormFieldErrors().get("shortPassword") != null) { pRequest.setAttribute("shortPassword", new Boolean(true)); } return (pMapping.findForward("invalid")); } user.setFirstName(form.getFirstName()); user.setLastName(form.getLastName()); user.setEmailAddress(form.getEmailAddress()); if (!form.getFirstPassword().equals("")) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("Could not hash password for storage: no such algorithm"); } try { md.update(form.getFirstPassword().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new DatabaseException("Could not hash password for storage: no such encoding"); } user.setPassword((new BASE64Encoder()).encode(md.digest())); } user.setTitle(form.getTitle()); user.setDegree(form.getDegree()); user.setAddress(form.getAddress()); user.setNationality(form.getNationality()); user.setLanguages(form.getLanguages()); user.setHomepage(form.getHomepage()); user.setInstitution(form.getInstitution()); if (pRequest.getParameter("hideEmail") != null) { if (pRequest.getParameter("hideEmail").equals("on")) { user.setHideEmail(true); } } else { user.setHideEmail(false); } User storedUser = database.acquireUserByPrimaryKey(user.getPrimaryKey()); if (currentUser.isSuperAdmin()) { if (pRequest.getParameter("admin") != null) { user.setAdminRights(true); } else { if (!storedUser.isSuperAdmin()) { user.setAdminRights(false); } } } else { user.setAdminRights(storedUser.getAdminRights()); } if (currentUser.isAdmin()) if (pRequest.getParameter("PDFRights") != null) user.setPDFRights(true); else user.setPDFRights(false); if (currentUser.isAdmin()) { if (!storedUser.isAdmin() || !storedUser.isSuperAdmin()) { if (pRequest.getParameter("active") != null) { user.setActive(true); } else { user.setActive(false); } } else { user.setActive(storedUser.getActive()); } } if (currentUser.isAdmin() || currentUser.isSuperAdmin()) { String[] categories = pRequest.getParameterValues("categories"); user.setModeratorRights(new Categories()); if (categories != null) { try { for (int i = 0; i < categories.length; i++) { Integer catkey = Integer.parseInt(categories[i]); Category cat = database.acquireCategoryByPrimaryKey(catkey); user.getModeratorRights().add(cat); } } catch (NumberFormatException nfe) { throw new DatabaseException("Invalid category key."); } } } if (!currentUser.isAdmin() && !currentUser.isSuperAdmin()) { user.setAdminRights(false); user.setSuperAdminRights(false); } database.updateUser(user); if (currentUser.getPrimaryKey() == user.getPrimaryKey()) { pRequest.getSession().setAttribute("login", user); } pRequest.setAttribute("helpKey", key); if (currentUser.isAdmin() || currentUser.isSuperAdmin()) { return (pMapping.findForward("adminfinished")); } return (pMapping.findForward("finished")); } return (pMapping.findForward("success")); }
private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } }
900,559
1
private void getRandomGUID(boolean secure, Object o) { 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(o.getClass().getName()); sbValueBeforeMD5.append(":"); 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 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); } }
900,560
1
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
900,561
0
private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } }
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(); }
900,562
1
public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
public synchronized String getSerialNumber() { if (serialNum != null) return serialNum; final StringBuffer buf = new StringBuffer(); Iterator it = classpath.iterator(); while (it.hasNext()) { ClassPathEntry entry = (ClassPathEntry) it.next(); buf.append(entry.getResourceURL().toString()); buf.append(":"); } serialNum = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } } }); return serialNum; }
900,563
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); } }
private boolean importPKC(String keystoreLocation, String pw, String pkcFile, String alias) { boolean imported = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(pkcFile)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); while (bis.available() > 0) { cert = cf.generateCertificate(bis); } } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from file when importing PKC: " + e.getMessage()); } return false; } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(new File(keystoreLocation))); } catch (FileNotFoundException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error accessing key store file when importing certificate: " + e.getMessage()); } return false; } try { if (alias.equals("rootca")) { ks.setCertificateEntry(alias, cert); } else { KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(pw.toCharArray())); ks.setKeyEntry(alias, pkEntry.getPrivateKey(), pw.toCharArray(), new Certificate[] { cert }); } ks.store(bos, pw.toCharArray()); imported = true; } catch (Exception e) { e.printStackTrace(); if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error writing keystore to file when importing key store: " + e.getMessage()); } return false; } return imported; }
900,564
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; }
private void getRandomGuid(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); String 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)); } guid = sb.toString(); }
900,565
1
private void tar(FileHolder fileHolder, boolean gzipIt) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File tarDestFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(tarDestFile); if (gzipIt) { outStream = new GZIPOutputStream(outStream); } TarOutputStream tarOutStream = new TarOutputStream(outStream); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); TarEntry tarEntry = null; try { tarEntry = new TarEntry(selectedFile, selectedFile.getName()); } catch (InvalidHeaderException e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + selectedFile); logger.logError(errEntry); } tarOutStream.putNextEntry(tarEntry); while ((bytes_read = inStream.read(buffer)) != -1) { tarOutStream.write(buffer, 0, bytes_read); } tarOutStream.closeEntry(); inStream.close(); super.processorSyncFlag.restartWaitUntilFalse(); } tarOutStream.close(); } catch (Exception e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + tarDestFile); logger.logError(errEntry); } }
public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
900,566
0
@SuppressWarnings("unchecked") public static void createInstance(ExternProtoDeclare externProtoDeclare) { ExternProtoDeclareImport epdi = new ExternProtoDeclareImport(); HashMap<String, ProtoDeclareImport> protoMap = X3DImport.getTheImport().getCurrentParser().getProtoMap(); boolean loadedFromWeb = false; File f = null; URL url = null; List<String> urls = externProtoDeclare.getUrl(); String tmpUrls = urls.toString(); urls = Util.splitStringToListOfStrings(tmpUrls); String protoName = null; int urlCount = urls.size(); for (int urlIndex = 0; urlIndex < urlCount; urlIndex++) { try { String path = urls.get(urlIndex); if (path.startsWith("\"") && path.endsWith("\"")) path = path.substring(1, path.length() - 1); int hashMarkPos = path.indexOf("#"); int urlLength = path.length(); if (hashMarkPos == -1) path = path.substring(0, urlLength); else { protoName = path.substring(hashMarkPos + 1, urlLength); path = path.substring(0, hashMarkPos); } if (path.toLowerCase().startsWith("http://")) { String filename = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")); String fileext = path.substring(path.lastIndexOf("."), path.length()); f = File.createTempFile(filename, fileext); url = new URL(path); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); url = f.toURI().toURL(); loadedFromWeb = true; } else { if (path.startsWith("/") || (path.charAt(1) == ':')) { } else { File x3dfile = X3DImport.getTheImport().getCurrentParser().getFile(); path = Util.getRealPath(x3dfile) + path; } f = new File(path); url = f.toURI().toURL(); Object testContent = url.getContent(); if (testContent == null) continue; loadedFromWeb = false; } X3DDocument x3dDocument = null; try { x3dDocument = X3DDocument.Factory.parse(f); } catch (XmlException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } Scene scene = x3dDocument.getX3D().getScene(); ProtoDeclare[] protos = scene.getProtoDeclareArray(); ProtoDeclare protoDeclare = null; if (protoName == null) { protoDeclare = protos[0]; } else { for (ProtoDeclare proto : protos) { if (proto.getName().equals(protoName)) { protoDeclare = proto; break; } } } if (protoDeclare == null) continue; ProtoBody protoBody = protoDeclare.getProtoBody(); epdi.protoBody = protoBody; protoMap.put(externProtoDeclare.getName(), epdi); break; } catch (MalformedURLException e) { } catch (IOException e) { } finally { if (loadedFromWeb && f != null) { f.delete(); } } } }
public static String hashMD5(String passw) { String passwHash = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passw.getBytes()); byte[] result = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < result.length; i++) { String tmpStr = "0" + Integer.toHexString((0xff & result[i])); sb.append(tmpStr.substring(tmpStr.length() - 2)); } passwHash = sb.toString(); } catch (NoSuchAlgorithmException ecc) { log.error("Errore algoritmo " + ecc); } return passwHash; }
900,567
1
public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } }
public IUserProfile getUserProfile(String profileID) throws MM4UUserProfileNotFoundException { SimpleUserProfile tempProfile = null; String tempProfileString = this.profileURI + profileID + FILE_SUFFIX; try { URL url = new URL(tempProfileString); Debug.println("Retrieve profile with ID: " + url); tempProfile = new SimpleUserProfile(); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String tempLine = null; tempProfile.add("id", profileID); while ((tempLine = input.readLine()) != null) { Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine); if (tempProperty != null) { tempProfile.addIfNotNull(tempProperty.getKey(), tempProperty.getValue()); } } input.close(); } catch (MalformedURLException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } catch (IOException exception) { throw new MM4UUserProfileNotFoundException(this, "getProfile", "Profile '" + tempProfileString + "' not found."); } return tempProfile; }
900,568
1
public static void copyFile(File src, File dst) throws IOException { LOGGER.info("Copying file '" + src.getAbsolutePath() + "' to '" + dst.getAbsolutePath() + "'"); FileChannel in = null; FileChannel out = null; try { FileInputStream fis = new FileInputStream(src); in = fis.getChannel(); FileOutputStream fos = new FileOutputStream(dst); out = fos.getChannel(); out.transferFrom(in, 0, in.size()); } finally { try { if (in != null) in.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (out != null) { try { out.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } }
900,569
1
public void testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); }
public void removerTopicos(Topicos topicos) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Topicos\" " + " WHERE \"id_Topicos\" = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, topicos.getIdTopicos()); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
900,570
1
public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
public static void copyFile(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(); long count = 0; long size = source.size(); while ((count += destination.transferFrom(source, 0, size - count)) < size) ; } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
900,571
0
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
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()); } } } } }
900,572
1
public String postEvent(EventDocument eventDoc, Map attachments) { if (eventDoc == null || eventDoc.getEvent() == null) return null; if (jmsTemplate == null) { sendEvent(eventDoc, attachments); return eventDoc.getEvent().getEventId(); } if (attachments != null) { Iterator iter = attachments.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); if (entry.getValue() instanceof DataHandler) { File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey()); try { IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file)); entry.setValue(file); } catch (IOException err) { err.printStackTrace(); } } } } InternalEventObject eventObj = new InternalEventObject(); eventObj.setEventDocument(eventDoc); eventObj.setAttachments(attachments); eventObj.setSessionContext(SessionContextUtil.getCurrentContext()); eventDoc.getEvent().setEventId(GuidUtil.generate()); if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj); return eventDoc.getEvent().getEventId(); }
private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
900,573
1
private String generateUniqueIdMD5(Run run, HttpServletRequest request, String groupIdString) { String portalUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String uniqueportalUrl = portalUrl + "run:" + run.getId().toString() + "group:" + groupIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(uniqueportalUrl.getBytes(), 0, uniqueportalUrl.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
protected static String encodePassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); return HexString.bufferToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
900,574
0
public HttpURLConnection getConnection(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection connection = null; if (_proxy == null) { connection = (HttpURLConnection) url.openConnection(); } else { URLConnection con = url.openConnection(_proxy); String encodedUserPwd = new String(Base64.encodeBase64((_username + ":" + _password).getBytes())); con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); connection = (HttpURLConnection) con; } return connection; }
private String getRenderedBody(String spec) throws Exception { log.entering(Rss2MailTask.class.getName(), "getRenderedBody"); final URL url = new URL(spec); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); final InputStream inputStream = connection.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; final StringBuffer bf = new StringBuffer(); while (line != null) { line = reader.readLine(); if (line != null) { bf.append(line); } } log.exiting(Rss2MailTask.class.getName(), "getRenderedBody"); return bf.toString(); }
900,575
1
public void display(WebPage page, HttpServletRequest req, HttpServletResponse resp) throws DisplayException { page.getDisplayInitialiser().initDisplay(new HttpRequestDisplayContext(req), req); StreamProvider is = (StreamProvider) req.getAttribute(INPUTSTREAM_KEY); if (is == null) { throw new IllegalStateException("No OutputStreamDisplayHandlerXML.InputStream found in request attribute" + " OutputStreamDisplayHandlerXML.INPUTSTREAM_KEY"); } resp.setContentType(is.getMimeType()); resp.setHeader("Content-Disposition", "attachment;filename=" + is.getName()); try { InputStream in = is.getInputStream(); OutputStream out = resp.getOutputStream(); if (in != null) { IOUtils.copy(in, out); } is.write(resp.getOutputStream()); resp.flushBuffer(); } catch (IOException e) { throw new DisplayException("Error writing input stream to response", e); } }
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; }
900,576
0
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
900,577
0
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")) { } }
private static String getSuitableWCSVersion(String host, String _version) throws ConnectException, IOException { String request = WCSProtocolHandler.buildCapabilitiesSuitableVersionRequest(host, _version); String version = new String(); StringReader reader = null; DataInputStream dis = null; try { URL url = new URL(request); byte[] buffer = new byte[1024]; dis = new DataInputStream(url.openStream()); dis.readFully(buffer); reader = new StringReader(new String(buffer)); KXmlParser kxmlParser = null; kxmlParser = new KXmlParser(); kxmlParser.setInput(reader); kxmlParser.nextTag(); if (kxmlParser.getEventType() != KXmlParser.END_DOCUMENT) { if ((kxmlParser.getName().compareTo(CapabilitiesTags.WCS_CAPABILITIES_ROOT1_0_0) == 0)) { version = kxmlParser.getAttributeValue("", CapabilitiesTags.VERSION); } } reader.close(); dis.close(); return version; } catch (ConnectException conEx) { throw new ConnectException(conEx.getMessage()); } catch (IOException ioEx) { throw new IOException(ioEx.getMessage()); } catch (XmlPullParserException xmlEx) { xmlEx.printStackTrace(); return ""; } finally { if (reader != null) { try { reader.close(); } catch (Exception ex) { ex.printStackTrace(); } } if (dis != null) { try { dis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
900,578
1
public DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
private void copyMerge(Path[] sources, OutputStream out) throws IOException { Configuration conf = getConf(); for (int i = 0; i < sources.length; ++i) { FileSystem fs = sources[i].getFileSystem(conf); InputStream in = fs.open(sources[i]); try { IOUtils.copyBytes(in, out, conf, false); } finally { in.close(); } } }
900,579
1
private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } }
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
900,580
0
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException { EXISchemaFactory schemaCompiler = new EXISchemaFactory(); schemaCompiler.setCompilerErrorHandler(compilerErrorHandler); InputSource inputSource = null; if (fileName != null) { URL url; if ((url = cls.getResource(fileName)) != null) { inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); } else throw new RuntimeException("File '" + fileName + "' not found."); } EXISchema compiled = schemaCompiler.compile(inputSource); InputStream serialized = serializeSchema(compiled); return loadSchema(serialized); }
900,581
0
protected List<String> execute(String queryString, String sVar, String filter) throws UnsupportedEncodingException, IOException { String query = URLEncoder.encode(queryString, "UTF-8"); String urlString = "http://sparql.bibleontology.com/sparql.jsp?sparql=" + query + "&type1=xml"; URL url; BufferedReader br = null; ArrayList<String> values = new ArrayList<String>(); try { url = new URL(urlString); URLConnection conn = url.openConnection(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { String sURI = getURI(line); if (sURI != null) { sURI = checkURISyntax(sURI); if (filter == null || sURI.startsWith(filter)) { values.add(sURI); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { br.close(); } return values; }
@Deprecated public static Collection<SearchKeyResult> searchKey(String iText, String iKeyServer) throws Exception { List<SearchKeyResult> outVec = new ArrayList<SearchKeyResult>(); String uri = iKeyServer + "/pks/lookup?search=" + URLEncoder.encode(iText, UTF8); URL url = new URL(uri); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); Pattern regex = Pattern.compile("pub.*?<a\\s+href\\s*=\"(.*?)\".*?>\\s*(\\w+)\\s*</a>.*?(\\d+-\\d+-\\d+).*?<a\\s+href\\s*=\".*?\".*?>\\s*(.+?)\\s*</a>", Pattern.CANON_EQ); String line; while ((line = input.readLine()) != null) { Matcher regexMatcher = regex.matcher(line); while (regexMatcher.find()) { String id = regexMatcher.group(2); String downUrl = iKeyServer + regexMatcher.group(1); String downDate = regexMatcher.group(3); String name = decodeHTML(regexMatcher.group(4)); outVec.add(new SearchKeyResult(id, name, downDate, downUrl)); } } IOUtils.closeQuietly(input); return outVec; }
900,582
1
public String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } }
public static File copyFile(String path) { File src = new File(path); File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
900,583
0
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!"); }
private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); }
900,584
0
private void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into sharesend.com"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } NULogger.getLogger().log(Level.INFO, "Upload Response : {0}", uploadresponse); NULogger.getLogger().log(Level.INFO, "Download Link : http://sharesend.com/{0}", uploadresponse); downloadlink = "http://sharesend.com/" + uploadresponse; downURL = downloadlink; httpclient.getConnectionManager().shutdown(); uploadFinished(); }
public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } }
900,585
1
private static String format(String check) throws NoSuchAlgorithmException, UnsupportedEncodingException { check = check.replaceAll(" ", ""); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(check.getBytes("ISO-8859-1")); byte[] end = md5.digest(); String digest = ""; for (int i = 0; i < end.length; i++) { digest += ((end[i] & 0xff) < 16 ? "0" : "") + Integer.toHexString(end[i] & 0xff); } return digest; }
private void createPropertyName(String objectID, String value, String propertyName, Long userID) throws JspTagException { rObject object = new rObject(new Long(objectID), userID); ClassProperty classProperty = new ClassProperty(propertyName, object.getClassName()); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } 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()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(classProperty.getID(), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
900,586
1
private static final void addFile(ZipArchiveOutputStream os, File file, String prefix) throws IOException { ArchiveEntry entry = os.createArchiveEntry(file, file.getAbsolutePath().substring(prefix.length() + 1)); os.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, os); fis.close(); os.closeArchiveEntry(); }
@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); } } }
900,587
1
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
@Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
900,588
1
public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); }
public 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); }
900,589
1
@Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } }
protected int doWork() { SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT)); reader.getFileHeader().setSortOrder(SORT_ORDER); SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT); Iterator<SAMRecord> iterator = reader.iterator(); while (iterator.hasNext()) writer.addAlignment(iterator.next()); reader.close(); writer.close(); return 0; }
900,590
0
public static String getMD5Hash(String hashthis) throws NoSuchAlgorithmException { byte[] key = "PATIENTISAUTHENTICATION".getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(hashthis.getBytes()); return new String(HashUtility.base64Encode(md5.digest(key))); }
public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
900,591
0
public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } }
public static void copyFile(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(); } } }
900,592
0
void copyFile(String sInput, String sOutput) throws IOException { File inputFile = new File(sInput); File outputFile = new File(sOutput); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
private void initJarURL() { try { URL url = getKwantuJarURLInMavenRepo(artifactId, version); File tempJarFile = File.createTempFile(artifactId + "-" + version, ".jar"); OutputStream out = new FileOutputStream(tempJarFile); InputStream in = url.openStream(); int length = 0; byte[] bytes = new byte[2048]; while ((length = in.read(bytes)) > 0) { out.write(bytes, 0, length); } in.close(); out.close(); jarURL = tempJarFile.toURI().toURL(); } catch (IOException ex) { throw new KwantuFaultException(ex); } }
900,593
1
@Override public void executeInterruptible() { encodingTerminated = false; File destinationFile = null; try { Runtime runtime = Runtime.getRuntime(); IconAndFileListElement element; while ((element = getNextFileElement()) != null) { File origFile = element.getFile(); destinationFile = new File(encodeFileCard.getDestinationFolder().getValue(), origFile.getName()); if (!destinationFile.getParentFile().exists()) { destinationFile.getParentFile().mkdirs(); } actualFileLabel.setText(origFile.getName()); actualFileModel.setMaximum((int) origFile.length()); actualFileModel.setValue(0); int bitrate; synchronized (bitratePattern) { Matcher bitrateMatcher = bitratePattern.matcher(encodeFileCard.getBitrate().getValue()); bitrateMatcher.find(); bitrate = Integer.parseInt(bitrateMatcher.group(1)); } List<String> command = new LinkedList<String>(); command.add(encoderFile.getCanonicalPath()); command.add("--mp3input"); command.add("-m"); command.add("j"); String sampleFreq = Settings.getSetting("encode.sample.freq"); if (Util.isNotEmpty(sampleFreq)) { command.add("--resample"); command.add(sampleFreq); } QualityElement quality = (QualityElement) ((JComboBox) encodeFileCard.getQuality().getValueComponent()).getSelectedItem(); command.add("-q"); command.add(Integer.toString(quality.getValue())); command.add("-b"); command.add(Integer.toString(bitrate)); command.add("--cbr"); command.add("-"); command.add(destinationFile.getCanonicalPath()); if (LOG.isDebugEnabled()) { StringBuilder commandLine = new StringBuilder(); boolean first = true; for (String part : command) { if (!first) commandLine.append(" "); commandLine.append(part); first = false; } LOG.debug("Command line: " + commandLine.toString()); } encodingProcess = runtime.exec(command.toArray(new String[0])); lastPosition = 0l; InputStream fileStream = null; try { fileStream = new PositionNotifierInputStream(new FileInputStream(origFile), origFile.length(), 2048, this); IOUtils.copy(fileStream, encodingProcess.getOutputStream()); encodingProcess.getOutputStream().close(); } finally { IOUtils.closeQuietly(fileStream); if (LOG.isDebugEnabled()) { InputStream processOut = null; try { processOut = encodingProcess.getInputStream(); StringWriter sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process output stream:\n" + sw); IOUtils.closeQuietly(processOut); processOut = encodingProcess.getErrorStream(); sw = new StringWriter(); IOUtils.copy(processOut, sw); LOG.debug("Process error stream:\n" + sw); } finally { IOUtils.closeQuietly(processOut); } } } int result = encodingProcess.waitFor(); encodingProcess = null; if (result != 0) { LOG.warn("Encoder process returned error code " + result); } if (Boolean.parseBoolean(encodeFileCard.getCopyTag().getValue())) { MP3File mp3Input = new MP3File(origFile); MP3File mp3Output = new MP3File(destinationFile); boolean write = false; if (mp3Input.hasID3v2tag()) { ID3v2Tag id3v2Tag = new ID3v2Tag(); for (ID3v2Frame frame : mp3Input.getID3v2tag().getAllframes()) { id3v2Tag.addFrame(frame); } mp3Output.setID3v2tag(id3v2Tag); write = true; } if (mp3Input.hasID3v11tag()) { mp3Output.setID3v11tag(mp3Input.getID3v11tag()); write = true; } if (write) mp3Output.write(); } } actualFileLabel.setText(Messages.getString("operations.file.encode.execute.actualfile.terminated")); actualFileModel.setValue(actualFileModel.getMaximum()); } catch (Exception e) { LOG.error("Cannot encode files", e); if (!(e instanceof IOException && encodingTerminated)) MainWindowInterface.showError(e); if (destinationFile != null) destinationFile.delete(); } }
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
900,594
0
public void writeToFtp(String login, String password, String address, String directory, String filename) { String newline = System.getProperty("line.separator"); try { URL url = new URL("ftp://" + login + ":" + password + "@ftp." + address + directory + filename + ".html" + ";type=i"); URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); OutputStreamWriter stream = new OutputStreamWriter(urlConn.getOutputStream()); stream.write("<html><title>" + title + "</title>" + newline); stream.write("<h1><b>" + title + "</b></h1>" + newline); stream.write("<h2>Table Of Contents:</h2><ul>" + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<li><i><a href=\"#"); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k)); stream.write("</a></i></li>" + newline); } stream.write("</ul><hr>" + newline + newline); for (int k = 0; k < rings.size(); k++) { stream.write("<h3><b>"); stream.write("<a name=\""); stream.write(readNoteTitle(k)); stream.write("\">"); stream.write(readNoteTitle(k) + "</a>"); stream.write("</b></h3>" + newline); stream.write(readNoteBody(k) + newline); } stream.write(newline + "<br><hr><a>This was created using Scribe, a free crutch editor.</a></html>"); stream.close(); } catch (IOException error) { System.out.println("There was an error: " + error); } }
public String get(String url) { String buf = null; StringBuilder resultBuffer = new StringBuilder(512); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url); try { URL theURL = new URL(url); URLConnection urlConn = theURL.openConnection(); urlConn.setDoOutput(true); urlConn.setReadTimeout(timeOut); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } } while (buf != null); urlReader.close(); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString()); int xmlNdx = resultBuffer.lastIndexOf("?>"); if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2); } catch (Exception e) { result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e); } return (result); }
900,595
0
public void testSavepoint4() throws Exception { Statement stmt = con.createStatement(); stmt.execute("CREATE TABLE #savepoint4 (data int)"); stmt.close(); con.setAutoCommit(false); for (int i = 0; i < 3; i++) { System.out.println("iteration: " + i); PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)"); pstmt.setInt(1, 1); assertTrue(pstmt.executeUpdate() == 1); Savepoint savepoint = con.setSavepoint(); assertNotNull(savepoint); assertTrue(savepoint.getSavepointId() == 1); try { savepoint.getSavepointName(); assertTrue(false); } catch (SQLException e) { } pstmt.setInt(1, 2); assertTrue(pstmt.executeUpdate() == 1); pstmt.close(); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); ResultSet rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 3); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(savepoint); pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4"); rs = pstmt.executeQuery(); assertTrue(rs.next()); assertTrue(rs.getInt(1) == 1); assertTrue(!rs.next()); pstmt.close(); rs.close(); con.rollback(); } con.setAutoCommit(true); }
protected void setUp() throws Exception { testOutputDirectory = new File(getClass().getResource("/").getPath()); zipFile = new File(this.testOutputDirectory, "/plugin.zip"); zipOutputDirectory = new File(this.testOutputDirectory, "zip"); zipOutputDirectory.mkdir(); logger.fine("zip dir created"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry("css/")); zos.putNextEntry(new ZipEntry("css/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("js/")); zos.putNextEntry(new ZipEntry("js/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/mylib.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/mylib.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); }
900,596
0
private void updateViewerContent(ScrollingGraphicalViewer viewer) { BioPAXGraph graph = (BioPAXGraph) viewer.getContents().getModel(); if (!graph.isMechanistic()) return; Map<String, Color> highlightMap = new HashMap<String, Color>(); for (Object o : graph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (node.isHighlighted()) { highlightMap.put(node.getIDHash(), node.getHighlightColor()); } } for (Object o : graph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (edge.isHighlighted()) { highlightMap.put(edge.getIDHash(), edge.getHighlightColor()); } } HighlightLayer hLayer = (HighlightLayer) ((ChsScalableRootEditPart) viewer.getRootEditPart()).getLayer(HighlightLayer.HIGHLIGHT_LAYER); hLayer.removeAll(); hLayer.highlighted.clear(); viewer.deselectAll(); graph.recordLayout(); PathwayHolder p = graph.getPathway(); if (withContent != null) { p.updateContentWith(withContent); } BioPAXGraph newGraph = main.getRootGraph().excise(p); newGraph.setAsRoot(); viewer.setContents(newGraph); boolean layedout = newGraph.fetchLayout(); if (!layedout) { new CoSELayoutAction(main).run(); } viewer.deselectAll(); GraphAnimation.run(viewer); for (Object o : newGraph.getNodes()) { IBioPAXNode node = (IBioPAXNode) o; if (highlightMap.containsKey(node.getIDHash())) { node.setHighlightColor(highlightMap.get(node.getIDHash())); node.setHighlight(true); } } for (Object o : newGraph.getEdges()) { IBioPAXEdge edge = (IBioPAXEdge) o; if (highlightMap.containsKey(edge.getIDHash())) { edge.setHighlightColor(highlightMap.get(edge.getIDHash())); edge.setHighlight(true); } } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); }
900,597
1
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, Vector images) { int i; lengthOfTask = images.size(); Element dataBaseXML = new Element("dataBase"); for (i = 0; ((i < images.size()) && !stop && !cancel); i++) { Vector imagen = new Vector(2); imagen = (Vector) images.elementAt(i); String element = (String) imagen.elementAt(0); current = i; String pathSrc = System.getProperty("user.dir") + File.separator + "images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(File.separator) + 1, pathSrc.length()); String pathDst = directoryPath + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector<String> keyWords = new Vector<String>(); keyWords = TIGDataBase.asociatedConceptSearch(element); Element image = new Element("image"); image.setAttribute("name", name); if (keyWords.size() != 0) { for (int k = 0; k < keyWords.size(); k++) { Element category = new Element("category"); category.setText(keyWords.get(k).trim()); image.addContent(category); } } dataBaseXML.addContent(image); } Document doc = new Document(dataBaseXML); try { XMLOutputter out = new XMLOutputter(); FileOutputStream f = new FileOutputStream(directoryPath + "images.xml"); out.output(doc, f); f.flush(); f.close(); } catch (Exception e) { e.printStackTrace(); } current = lengthOfTask; }
public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception { if (file != null) { try { HttpServletRequest request = ServletActionContext.getRequest(); HttpSession session = request.getSession(); String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName; File outfile = new File(pathFile); String[] nomPhotoTab = fileName.split("\\."); String extension = nomPhotoTab[nomPhotoTab.length - 1]; StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]); for (int i = 1; i < nomPhotoTab.length - 1; i++) { pathResBuff.append(".").append(nomPhotoTab[i]); } String pathRes = pathResBuff.toString(); String nomPhoto = fileName; for (int i = 0; !outfile.createNewFile(); i++) { nomPhoto = pathRes + "_" + +i + "." + extension; pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto; outfile = new File(pathFile); } logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile); FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outfile).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return outfile; } catch (IOException e) { logger.error("Erreur lors de l'enregistrement de l'image ", e); throw new Exception("Erreur lors de l'enregistrement de l'image "); } } return null; }
900,598
1
private boolean copyOldSetupClass(File lastVerPath, File destPath) throws java.io.FileNotFoundException, IOException { byte[] buf; File oldClass = new File(lastVerPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); if (oldClass.exists()) { FileOutputStream out = new FileOutputStream(destPath.getAbsolutePath() + File.separator + installClassName_ + ".class"); FileInputStream in = new FileInputStream(oldClass); buf = new byte[(new Long(oldClass.length())).intValue()]; int read = in.read(buf, 0, buf.length); out.write(buf, 0, read); out.close(); in.close(); return true; } return false; }
public static void copyFile(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(); } } }
900,599