label
int64 0
1
| func1
stringlengths 173
53.1k
| func2
stringlengths 173
53.1k
| id
int64 0
901k
|
---|---|---|---|
1 | public static void copyFile(File source, File target) throws Exception { if (source == null || target == null) { throw new IllegalArgumentException("The arguments may not be null."); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dtnChannel = new FileOutputStream(target).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dtnChannel); srcChannel.close(); dtnChannel.close(); } catch (Exception e) { String message = "Unable to copy file '" + source.getName() + "' to '" + target.getName() + "'."; logger.error(message, e); throw new Exception(message, e); } } | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | 900 |
0 | private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } } | public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream stream = url.openStream(); AudioFileFormat format; try { format = getAudioFileFormat(new BufferedInputStream(stream)); } finally { stream.close(); } return format; } | 901 |
0 | public static String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.uniprot.org/uniprot/" + id + ".fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); String[] first = header.split("OS="); return new String[] { id, first[0].split("\\s")[1], first[1].split("GN=")[0], seq.toString() }; } | @SuppressWarnings("unchecked") private void doService(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String url = request.getRequestURL().toString(); if (url.endsWith("/favicon.ico")) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (url.contains("/delay")) { final String delay = StringUtils.substringBetween(url, "/delay", "/"); final int ms = Integer.parseInt(delay); if (LOG.isDebugEnabled()) { LOG.debug("Sleeping for " + ms + " before to deliver " + url); } Thread.sleep(ms); } final URL requestedUrl = new URL(url); final WebRequest webRequest = new WebRequest(requestedUrl); webRequest.setHttpMethod(HttpMethod.valueOf(request.getMethod())); for (final Enumeration<String> en = request.getHeaderNames(); en.hasMoreElements(); ) { final String headerName = en.nextElement(); final String headerValue = request.getHeader(headerName); webRequest.setAdditionalHeader(headerName, headerValue); } final List<NameValuePair> requestParameters = new ArrayList<NameValuePair>(); for (final Enumeration<String> paramNames = request.getParameterNames(); paramNames.hasMoreElements(); ) { final String name = paramNames.nextElement(); final String[] values = request.getParameterValues(name); for (final String value : values) { requestParameters.add(new NameValuePair(name, value)); } } if ("PUT".equals(request.getMethod()) && request.getContentLength() > 0) { final byte[] buffer = new byte[request.getContentLength()]; request.getInputStream().readLine(buffer, 0, buffer.length); webRequest.setRequestBody(new String(buffer)); } else { webRequest.setRequestParameters(requestParameters); } final WebResponse resp = MockConnection_.getResponse(webRequest); response.setStatus(resp.getStatusCode()); for (final NameValuePair responseHeader : resp.getResponseHeaders()) { response.addHeader(responseHeader.getName(), responseHeader.getValue()); } if (WriteContentAsBytes_) { IOUtils.copy(resp.getContentAsStream(), response.getOutputStream()); } else { final String newContent = getModifiedContent(resp.getContentAsString()); final String contentCharset = resp.getContentCharset(); response.setCharacterEncoding(contentCharset); response.getWriter().print(newContent); } response.flushBuffer(); } | 902 |
0 | private static void compressZip(String source, String dest) throws Exception { File baseFolder = new File(source); if (baseFolder.exists()) { if (baseFolder.isDirectory()) { List<File> fileList = getSubFiles(new File(source)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest)); zos.setEncoding("GBK"); ZipEntry entry = null; byte[] buf = new byte[2048]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { File file = fileList.get(i); if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 1024)) != -1) { zos.write(buf, 0, readLen); } in.close(); } } zos.close(); } else { throw new Exception("Can not do this operation!."); } } else { baseFolder.mkdirs(); compressZip(source, dest); } } | public void savaUserPerm(String userid, Collection user_perm_collect) throws DAOException, SQLException { ConnectionProvider cp = null; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; PrivilegeFactory factory = PrivilegeFactory.getInstance(); Operation op = factory.createOperation(); try { cp = ConnectionProviderFactory.getConnectionProvider(Constants.DATA_SOURCE); conn = cp.getConnection(); pstmt = conn.prepareStatement(DEL_USER_PERM); pstmt.setString(1, userid); pstmt.executeUpdate(); if ((user_perm_collect == null) || (user_perm_collect.size() <= 0)) { return; } else { conn.setAutoCommit(false); pstmt = conn.prepareStatement(ADD_USER_PERM); Iterator user_perm_ir = user_perm_collect.iterator(); while (user_perm_ir.hasNext()) { UserPermission userPerm = (UserPermission) user_perm_ir.next(); pstmt.setString(1, String.valueOf(userPerm.getUser_id())); pstmt.setString(2, String.valueOf(userPerm.getResource_id())); pstmt.setString(3, String.valueOf(userPerm.getResop_id())); pstmt.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); } } catch (Exception e) { e.printStackTrace(); conn.rollback(); throw new DAOException(); } finally { try { if (conn != null) { conn.close(); } if (pstmt != null) { pstmt.close(); } } catch (Exception e) { } } } | 903 |
0 | @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } | @Override public TDSModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); TDSModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); } | 904 |
1 | public List<DemandeChargement> getArtistToLoadFromWiki() throws Exception { URL fileURL = new URL("http://beastchild.free.fr/wiki/doku.php?id=music"); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; List<DemandeChargement> dem = new ArrayList<DemandeChargement>(); while ((ligne = br.readLine()) != null) { if (ligne.indexOf("<@@@>") != -1) { String maidS = ligne.substring(ligne.indexOf("<@@@>") + 11, ligne.indexOf("</@@@>")).trim(); try { long maid = Long.parseLong(maidS); log.info("MAID to load : " + maid); dem.add(new DemandeChargement(maid)); } catch (Exception e) { log.error("Impossible de recuperer le MAID : " + maidS); } } } br.close(); httpStream.close(); return dem; } | public OperandToken evaluate(Token[] operands, GlobalValues globals) { String s = ""; String lineFile = ""; ; if (getNArgIn(operands) != 1) throwMathLibException("urlread: number of arguments < 1"); if (!(operands[0] instanceof CharToken)) throwMathLibException("urlread: argument must be String"); String urlString = ((CharToken) operands[0]).toString(); URL url = null; try { url = new URL(urlString); } catch (Exception e) { throwMathLibException("urlread: malformed url"); } try { BufferedReader inReader = new BufferedReader(new InputStreamReader(url.openStream())); while ((lineFile = inReader.readLine()) != null) { s += lineFile + "\n"; } inReader.close(); } catch (Exception e) { throwMathLibException("urlread: error input stream"); } return new CharToken(s); } | 905 |
0 | public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } } | public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } } | 906 |
0 | @Test public void testRegister() { try { String username = "muchu"; String password = "123"; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String passwordMd5 = new String(md5.digest()); LogService logServiceMock = EasyMock.createMock(LogService.class); DbService dbServiceMock = EasyMock.createMock(DbService.class); userServ.setDbServ(dbServiceMock); userServ.setLogger(logServiceMock); IFeelerUser user = new FeelerUserImpl(); user.setUsername(username); user.setPassword(passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(null); dbServiceMock.addFeelerUser(username, passwordMd5); logServiceMock.info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); EasyMock.expect(dbServiceMock.queryFeelerUser(username)).andReturn(user); EasyMock.replay(dbServiceMock, logServiceMock); Assert.assertTrue(userServ.register(username, password)); EasyMock.verify(dbServiceMock, logServiceMock); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } | public static void downloadURLNow(URL url, File to, SHA1Sum sha1, boolean force) throws Exception { { String sep = System.getProperty("file.separator"); String folders = to.getPath(); String path = ""; for (int i = 0; i < folders.length(); i++) { path += folders.charAt(i); if (path.endsWith(sep)) { File f = new File(path); if (!f.exists()) f.mkdir(); if (!f.isDirectory()) { Out.error(URLDownloader.class, path + " is not a directory!"); return; } } } } Out.info(URLDownloader.class, "Downloading " + url.toExternalForm()); URLConnection uc = url.openConnection(); DataInputStream is = new DataInputStream(new BufferedInputStream(uc.getInputStream())); FileOutputStream os = new FileOutputStream(to); byte[] b = new byte[1024]; int fileLength = uc.getHeaderFieldInt("Content-Length", 0) / b.length; Task task = null; if (fileLength > 0) task = TaskManager.createTask(url.toExternalForm(), fileLength, "kB"); do { int c = is.read(b); if (c == -1) break; os.write(b, 0, c); if (task != null) task.advanceProgress(); } while (true); if (task != null) task.complete(); os.close(); is.close(); } | 907 |
1 | private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } | private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } | 908 |
0 | public void run() { runCounter++; try { LOGGER.info("Fetching feed [" + runCounter + "] " + _feedInfo); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); disableSSLCertificateChecking(httpClient); if (_proxy != null && _feedInfo.getUseProxy()) { LOGGER.info("Configuring proxy " + _proxy); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxy); } if (_feedInfo.getUsername() != null) { Credentials credentials; if (_feedInfo.getUsername().contains("/")) { String username = _feedInfo.getUsername().substring(_feedInfo.getUsername().indexOf("/") + 1); String domain = _feedInfo.getUsername().substring(0, _feedInfo.getUsername().indexOf("/")); String workstation = InetAddress.getLocalHost().getHostName(); LOGGER.info("Configuring NT credentials : username=[" + username + "] domain=[" + domain + "] workstation=[" + workstation + "]"); credentials = new NTCredentials(username, _feedInfo.getPassword(), workstation, domain); httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory()); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } else { credentials = new UsernamePasswordCredentials(_feedInfo.getUsername(), _feedInfo.getPassword()); LOGGER.info("Configuring Basic credentials " + credentials); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } } if (_feedInfo.getCookie() != null) { BasicClientCookie cookie = new BasicClientCookie(_feedInfo.getCookie().getName(), _feedInfo.getCookie().getValue()); cookie.setVersion(0); if (_feedInfo.getCookie().getDomain() != null) cookie.setDomain(_feedInfo.getCookie().getDomain()); if (_feedInfo.getCookie().getPath() != null) cookie.setPath(_feedInfo.getCookie().getPath()); LOGGER.info("Adding cookie " + cookie); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } HttpGet httpget = new HttpGet(_feedInfo.getUrl()); HttpResponse response = httpClient.execute(httpget, localContext); LOGGER.info("Response Status : " + response.getStatusLine()); LOGGER.debug("Headers : " + Arrays.toString(response.getAllHeaders())); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOGGER.error("Request was unsuccessful for " + _feedInfo + " : " + response.getStatusLine()); } else { SyndFeedInput input = new SyndFeedInput(); XmlReader reader = new XmlReader(response.getEntity().getContent()); SyndFeed feed = input.build(reader); if (feed.getTitle() != null) _feedInfo.setTitle(feed.getTitle()); LOGGER.debug("Feed : " + new SyndFeedOutput().outputString(feed)); LOGGER.info("Feed [" + feed.getTitle() + "] contains " + feed.getEntries().size() + " entries"); @SuppressWarnings("unchecked") List<SyndEntry> entriesList = feed.getEntries(); Collections.sort(entriesList, new SyndEntryPublishedDateComparator()); for (SyndEntry entry : entriesList) { if (VisitedEntries.getInstance().isAlreadyVisited(entry.getUri())) { LOGGER.debug("Already received " + entry.getUri()); } else { _feedInfo.addEntry(entry); LOGGER.debug("New entry " + entry.toString()); _entryDisplay.displayEntry(feed, entry, firstRun); } } LOGGER.info("Completing entries for feed " + feed.getTitle()); if (firstRun) firstRun = false; } } catch (IllegalArgumentException e) { LOGGER.error(e.getMessage(), e); } catch (FeedException e) { LOGGER.error(e.getMessage(), e); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } catch (KeyManagementException e) { LOGGER.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOGGER.error(e.getMessage(), e); } } | @Test public void testTrim() throws Exception { TreeNode ast = TestUtil.readFileInAST("resources/SimpleTestFile.java"); DecoratorSelection ds = new DecoratorSelection(); XmlFileSystemRepository rep = new XmlFileSystemRepository(); XmlToFormatContentConverter converter = new XmlToFormatContentConverter(rep); URI url = new File("resources/javaDefaultFormats.xml").toURI(); InputStream is = url.toURL().openStream(); converter.convert(is); File f = new File("resources/javaDefaultFormats.xml").getAbsoluteFile(); converter.convert(f); String string = new File("resources/query.xml").getAbsolutePath(); Document qDoc = XmlUtil.loadXmlFromFile(string); Query query = new Query(qDoc); Format format = XfsrFormatManager.getInstance().getFormats("java", "signature only"); TokenAutoTrimmer.create("Java", "resources/java.autotrim"); Document doc = rep.getXmlContentTree(ast, query, format, ds).getOwnerDocument(); String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><sourcecode>main(String[])</sourcecode>"; ByteArrayOutputStream bout = new ByteArrayOutputStream(); XmlUtil.outputXml(doc, bout); String actual = bout.toString(); assertEquals(expected, actual); } | 909 |
1 | private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | 910 |
0 | public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); } | public static NSImage getImage(URL url) { InputStream in = null; try { in = url.openStream(); } catch (IOException e) { Log.error(e.getMessage(), e); } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buff = new byte[10 * 1024]; int len; try { if (in != null) { while ((len = in.read(buff)) != -1) { out.write(buff, 0, len); } in.close(); } out.close(); } catch (IOException e) { Log.error(e.getMessage(), e); } NSData data = new NSData(out.toByteArray()); return new NSImage(data); } | 911 |
0 | private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } } | public void readURL(URL url) throws IOException, ParserConfigurationException, SAXException { URLConnection connection; if (proxy == null) { connection = url.openConnection(); } else { connection = url.openConnection(proxy); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.connect(); InputStream in = connection.getInputStream(); readInputStream(in); } | 912 |
0 | private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } } | private Properties loadDefaultProperties() throws IOException { Properties merged = new Properties(); try { merged.setProperty("user", System.getProperty("user.name")); } catch (java.lang.SecurityException se) { } ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { logger.debug("Can't find a classloader for the Driver; not loading driver configuration"); return merged; } logger.debug("Loading driver configuration via classloader " + cl); ArrayList urls = new ArrayList(); Enumeration urlEnum = cl.getResources("org/postgresql/driverconfig.properties"); while (urlEnum.hasMoreElements()) { urls.add(urlEnum.nextElement()); } for (int i = urls.size() - 1; i >= 0; i--) { URL url = (URL) urls.get(i); logger.debug("Loading driver configuration from: " + url); InputStream is = url.openStream(); merged.load(is); is.close(); } return merged; } | 913 |
1 | public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); } | public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs) throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException { InputSource source = new InputSource(inputUrl.openStream()); Document logDoc = DomUtil.getNewDom(); XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs); reader.parse(source); InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8"); System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"..."); OutputStream fos = new FileOutputStream(messageFile); IOUtils.copy(logStream, fos); return logDoc; } | 914 |
0 | public static File getClassLoaderFile(String filename) throws IOException { Resource resource = new ClassPathResource(filename); try { return resource.getFile(); } catch (IOException e) { } InputStream is = null; FileOutputStream os = null; try { String tempFilename = RandomStringUtils.randomAlphanumeric(20); File file = File.createTempFile(tempFilename, null); is = resource.getInputStream(); os = new FileOutputStream(file); IOUtils.copy(is, os); return file; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } | public void deleteUser(User portalUserBean, AuthSession authSession) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (portalUserBean.getUserId() == null) throw new IllegalArgumentException("id of portal user is null"); String sql = "update WM_LIST_USER " + "set is_deleted=1 " + "where ID_USER=? and is_deleted = 0 and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setLong(num++, portalUserBean.getUserId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) { dbDyn.rollback(); } } catch (Exception e001) { } String es = "Error delete of portal user"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } | 915 |
0 | public String performRequest(TreeMap<String, String> params, boolean isAuthenticated) { params.put("format", "json"); try { URL url = new URL(getApiUrl(params, isAuthenticated)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); Reader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = ""; while (reader.ready()) { response += (char) reader.read(); } response = response.replaceFirst("jsonVimeoApi\\(", ""); response = response.substring(0, response.length() - 2); return response; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } | 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; } | 916 |
0 | public int readLines() { int i = 0; if (istream == null) return 0; try { String s1; if ((new String("http")).compareTo(url.getProtocol()) == 0) { istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { last_contentLenght = istream.getContentLength(); istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println("Trace2Png: ContentLength: " + Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); String s; while ((s = reader.readLine()) != null) { bytes_read = bytes_read + s.length() + 1; t2pProcessLine(trace, s); i++; } } } else { while ((s1 = reader.readLine()) != null) { bytes_read = bytes_read + s1.length() + 1; t2pProcessLine(trace, s1); i++; } } t2pHandleEventPairs(trace); t2pSort(trace, sortby); } catch (IOException ioexception) { System.out.println("Trace2Png: IOException !!!"); } return i; } | private void sort() { for (int i = 0; i < density.length; i++) { for (int j = density.length - 2; j >= i; j--) { if (density[j] > density[j + 1]) { KDNode n = nonEmptyNodesArray[j]; nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1]; nonEmptyNodesArray[j + 1] = n; double d = density[j]; density[j] = density[j + 1]; density[j + 1] = d; } } } } | 917 |
0 | public void copyDependancyFiles() { for (String[] depStrings : getDependancyFiles()) { String source = depStrings[0]; String target = depStrings[1]; try { File sourceFile = PluginManager.getFile(source); IOUtils.copyEverything(sourceFile, new File(WEB_ROOT + target)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } | public void run() { try { URL url = new URL(myListURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; Pattern folderPattern = Pattern.compile(".*DIR.*<a href=.(.*)/.>(.*)</a>.*"); Pattern folderPatternCloudmake = Pattern.compile(".*<li><a href=./(.*)#breadcrumbs. class=.folder.>(.*)</a></li>.*"); Pattern filePatternCloudmake = Pattern.compile(".*<a href=.(.*).bz2. class=.default.>(.*).osm(.*).bz2</a> <span class=\"file-size\">(.*)</span>.*"); while ((line = reader.readLine()) != null) { Matcher matcher = folderPattern.matcher(line); if (matcher.matches()) { String dirUrl = myListURL + matcher.group(1) + "/"; String name = matcher.group(2); if (name.equalsIgnoreCase("Parent Directory")) { continue; } DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = folderPatternCloudmake.matcher(line); if (matcher.matches()) { String dirUrl = myListURL.substring(0, myListURL.indexOf(".com/") + ".com/".length()) + matcher.group(1); String name = matcher.group(2); DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = filePatternCloudmake.matcher(line); if (matcher.matches()) { String fileUrl = myListURL.substring(0, myListURL.indexOf(".com") + ".com".length()) + matcher.group(1) + ".bz2"; final int typeAt = 3; final int nameAt = 2; String type = matcher.group(typeAt); String name = matcher.group(nameAt); if (type.length() > 0) { if (type.startsWith(".")) { type = type.substring(1); } name += "-" + type; } JMenuItem subMenu = new JMenuItem(name); subMenu.addActionListener(new DownloadActionListener(fileUrl, name)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); continue; } int index = line.indexOf("<a href=\""); if (index < 0) { continue; } index += "<a href=\"".length(); int index2 = line.indexOf("</a"); if (index2 < 0) { continue; } int index1 = line.indexOf(".osm.bz2\">"); if (index1 < 0) { continue; } index1 += ".osm.bz2".length(); String fileUrl = line.substring(index, index1); if (!fileUrl.contains(".osm")) continue; if (!fileUrl.startsWith("http")) fileUrl = myListURL + fileUrl; index1 += "\">".length(); String fileName = line.substring(index1, index2); JMenuItem subMenu = new JMenuItem(fileName); subMenu.addActionListener(new DownloadActionListener(fileUrl, fileName)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); } } catch (Exception e) { LOG.log(Level.SEVERE, "[Exception] Problem in " + getClass().getName(), e); } LOG.info("Done with async download of list of downloadable maps for " + getText() + "..."); remove(isLoadingMenuItem); if (myTreeNode != null) { myTreeNode.doneLoading(); } } | 918 |
1 | public ArrayList parseFile(File newfile) throws IOException { String s; String firstname; String secondname; String direction; String header; String name = null; String[] tokens; boolean readingHArrays = false; boolean readingVArrays = false; boolean readingAArrays = false; ArrayList xturndat = new ArrayList(); ArrayList yturndat = new ArrayList(); ArrayList ampturndat = new ArrayList(); int nvalues; URL url = newfile.toURI().toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); s = br.readLine(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues < 1) continue; firstname = tokens[0]; secondname = tokens[1]; if (secondname.startsWith("BPM")) { if (readingHArrays) dumpxData(name, xturndat); else if (readingVArrays) dumpyData(name, yturndat); else if (readingAArrays) dumpampData(name, ampturndat); direction = tokens[4]; if (direction.equals("HORIZONTAL")) { readingHArrays = true; readingVArrays = false; readingAArrays = false; } if (direction.equals("VERTICAL")) { readingVArrays = true; readingHArrays = false; readingAArrays = false; } if (direction.equals("AMPLITUDE")) { readingVArrays = false; readingHArrays = false; readingAArrays = true; } name = tokens[3]; xturndat.clear(); yturndat.clear(); ampturndat.clear(); } if (secondname.startsWith("WAVEFORM")) continue; if (nvalues == 3) { if (readingHArrays) xturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingVArrays) yturndat.add(new Double(Double.parseDouble(tokens[2]))); else if (readingAArrays) ampturndat.add(new Double(Double.parseDouble(tokens[2]))); } } dumpampData(name, ampturndat); data.add(xdatamap); data.add(ydatamap); data.add(ampdatamap); return data; } | public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; } | 919 |
1 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | public void extractPrincipalClasses(String[] info, int numFiles) { String methodName = ""; String finalClass = ""; String WA; String MC; String RA; int[] readCount = new int[numFiles]; int[] writeCount = new int[numFiles]; int[] methodCallCount = new int[numFiles]; int writeMax1; int writeMax2; int readMax; int methodCallMax; int readMaxIndex = 0; int writeMaxIndex1 = 0; int writeMaxIndex2; int methodCallMaxIndex = 0; try { MethodsDestClass = new BufferedWriter(new FileWriter("InfoFiles/MethodsDestclass.txt")); FileInputStream fstreamWriteAttr = new FileInputStream("InfoFiles/WriteAttributes.txt"); DataInputStream inWriteAttr = new DataInputStream(fstreamWriteAttr); BufferedReader writeAttr = new BufferedReader(new InputStreamReader(inWriteAttr)); FileInputStream fstreamMethodsCalled = new FileInputStream("InfoFiles/MethodsCalled.txt"); DataInputStream inMethodsCalled = new DataInputStream(fstreamMethodsCalled); BufferedReader methodsCalled = new BufferedReader(new InputStreamReader(inMethodsCalled)); FileInputStream fstreamReadAttr = new FileInputStream("InfoFiles/ReadAttributes.txt"); DataInputStream inReadAttr = new DataInputStream(fstreamReadAttr); BufferedReader readAttr = new BufferedReader(new InputStreamReader(inReadAttr)); while ((WA = writeAttr.readLine()) != null && (RA = readAttr.readLine()) != null && (MC = methodsCalled.readLine()) != null) { WA = writeAttr.readLine(); RA = readAttr.readLine(); MC = methodsCalled.readLine(); while (WA.compareTo("EndOfClass") != 0 && RA.compareTo("EndOfClass") != 0 && MC.compareTo("EndOfClass") != 0) { methodName = writeAttr.readLine(); readAttr.readLine(); methodsCalled.readLine(); WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); while (true) { if (WA.compareTo("EndOfMethod") == 0 && RA.compareTo("EndOfMethod") == 0 && MC.compareTo("EndOfMethod") == 0) { break; } if (WA.compareTo("EndOfMethod") != 0) { if (WA.indexOf(".") > 0) { WA = WA.substring(0, WA.indexOf(".")); } } if (RA.compareTo("EndOfMethod") != 0) { if (RA.indexOf(".") > 0) { RA = RA.substring(0, RA.indexOf(".")); } } if (MC.compareTo("EndOfMethod") != 0) { if (MC.indexOf(".") > 0) { MC = MC.substring(0, MC.indexOf(".")); } } for (int i = 0; i < numFiles && info[i] != null; i++) { if (info[i].compareTo(WA) == 0) { writeCount[i]++; } if (info[i].compareTo(RA) == 0) { readCount[i]++; } if (info[i].compareTo(MC) == 0) { methodCallCount[i]++; } } if (WA.compareTo("EndOfMethod") != 0) { WA = writeAttr.readLine(); } if (MC.compareTo("EndOfMethod") != 0) { MC = methodsCalled.readLine(); } if (RA.compareTo("EndOfMethod") != 0) { RA = readAttr.readLine(); } } WA = writeAttr.readLine(); MC = methodsCalled.readLine(); RA = readAttr.readLine(); writeMax1 = writeCount[0]; writeMaxIndex1 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax1) { writeMax1 = writeCount[i]; writeMaxIndex1 = i; } } writeCount[writeMaxIndex1] = 0; writeMax2 = writeCount[0]; writeMaxIndex2 = 0; for (int i = 1; i < numFiles; i++) { if (writeCount[i] > writeMax2) { writeMax2 = writeCount[i]; writeMaxIndex2 = i; } } readMax = readCount[0]; readMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (readCount[i] > readMax) { readMax = readCount[i]; readMaxIndex = i; } } methodCallMax = methodCallCount[0]; methodCallMaxIndex = 0; for (int i = 1; i < numFiles; i++) { if (methodCallCount[i] > methodCallMax) { methodCallMax = methodCallCount[i]; methodCallMaxIndex = i; } } boolean isNotEmpty = false; if (writeMax1 > 0 && writeMax2 == 0) { finalClass = info[writeMaxIndex1]; isNotEmpty = true; } else if (writeMax1 == 0) { if (readMax != 0) { finalClass = info[readMaxIndex]; isNotEmpty = true; } else if (methodCallMax != 0) { finalClass = info[methodCallMaxIndex]; isNotEmpty = true; } } if (isNotEmpty == true) { MethodsDestClass.write(methodName); MethodsDestClass.newLine(); MethodsDestClass.write(finalClass); MethodsDestClass.newLine(); isNotEmpty = false; } for (int j = 0; j < numFiles; j++) { readCount[j] = 0; writeCount[j] = 0; methodCallCount[j] = 0; } } } writeAttr.close(); methodsCalled.close(); readAttr.close(); MethodsDestClass.close(); int sizeInfoArray = 0; sizeInfoArray = infoArraySize(); boolean classWritten = false; principleClass = new String[100]; principleMethod = new String[100]; principleMethodsClass = new String[100]; String infoArray[] = new String[sizeInfoArray]; String field; int counter = 0; FileInputStream fstreamDestMethod = new FileInputStream("InfoFiles/MethodsDestclass.txt"); DataInputStream inDestMethod = new DataInputStream(fstreamDestMethod); BufferedReader destMethod = new BufferedReader(new InputStreamReader(inDestMethod)); PrincipleClassGroup = new BufferedWriter(new FileWriter("InfoFiles/PrincipleClassGroup.txt")); while ((field = destMethod.readLine()) != null) { infoArray[counter] = field; counter++; } for (int i = 0; i < numFiles; i++) { for (int j = 0; j < counter - 1 && info[i] != null; j++) { if (infoArray[j + 1].compareTo(info[i]) == 0) { if (classWritten == false) { PrincipleClassGroup.write(infoArray[j + 1]); PrincipleClassGroup.newLine(); principleClass[principleClassCount] = infoArray[j + 1]; principleClassCount++; classWritten = true; } PrincipleClassGroup.write(infoArray[j]); principleMethod[principleMethodCount] = infoArray[j]; principleMethodsClass[principleMethodCount] = infoArray[j + 1]; principleMethodCount++; PrincipleClassGroup.newLine(); } } if (classWritten == true) { PrincipleClassGroup.write("EndOfClass"); PrincipleClassGroup.newLine(); classWritten = false; } } destMethod.close(); PrincipleClassGroup.close(); readFileCount = readFileCount(); writeFileCount = writeFileCount(); methodCallFileCount = methodCallFileCount(); readArray = new String[readFileCount]; writeArray = new String[writeFileCount]; callArray = new String[methodCallFileCount]; initializeArrays(); constructFundamentalView(); constructInteractionView(); constructAssociationView(); } catch (IOException e) { e.printStackTrace(); } } | 920 |
0 | private void createPolicy(String policyName) throws SPLException { URL url = getClass().getResource(policyName + ".spl"); StringBuffer contents = new StringBuffer(); try { BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } input.close(); System.out.println(policyName); System.out.println(contents.toString()); boolean createReturn = jspl.createPolicy(policyName, contents.toString()); System.out.println("Policy Created : " + policyName + " - " + createReturn); System.out.println(""); } catch (IOException ex) { ex.printStackTrace(); } } | public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); } | 921 |
1 | public Long addPortletName(PortletNameBean portletNameBean) { PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_PORTAL_PORTLET_NAME"); seq.setTableName("WM_PORTAL_PORTLET_NAME"); seq.setColumnName("ID_SITE_CTX_TYPE"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_PORTAL_PORTLET_NAME " + "( ID_SITE_CTX_TYPE, TYPE ) " + "values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ?" + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); RsetTools.setLong(ps, 1, sequenceValue); ps.setString(2, portletNameBean.getPortletName()); ps.executeUpdate(); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new portlet name "; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } | @Override public boolean putDescription(String uuid, String description) throws DatabaseException { if (uuid == null) throw new NullPointerException("uuid"); if (description == null) throw new NullPointerException("description"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } boolean found = true; try { PreparedStatement findSt = getConnection().prepareStatement(SELECT_COMMON_DESCRIPTION_STATEMENT); PreparedStatement updSt = null; findSt.setString(1, uuid); ResultSet rs = findSt.executeQuery(); found = rs.next(); int modified = 0; updSt = getConnection().prepareStatement(found ? UPDATE_COMMON_DESCRIPTION_STATEMENT : INSERT_COMMON_DESCRIPTION_STATEMENT); updSt.setString(1, description); updSt.setString(2, uuid); modified = updSt.executeUpdate(); if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + findSt + "\" and \"" + updSt + "\""); } else { getConnection().rollback(); LOGGER.error("DB has not been updated -> rollback! Queries: \"" + findSt + "\" and \"" + updSt + "\""); found = false; } } catch (SQLException e) { LOGGER.error(e); found = false; } finally { closeConnection(); } return found; } | 922 |
1 | public static String send(String ipStr, int port, String password, String command, InetAddress localhost, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty { StringBuffer response = new StringBuffer(); try { rconSocket = new Socket(); rconSocket.bind(new InetSocketAddress(localhost, localPort)); rconSocket.connect(new InetSocketAddress(ipStr, port), RESPONSE_TIMEOUT); out = rconSocket.getOutputStream(); in = rconSocket.getInputStream(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(in)); rconSocket.setSoTimeout(RESPONSE_TIMEOUT); String digestSeed = ""; boolean loggedIn = false; boolean keepGoing = true; while (keepGoing) { String receivedContent = buffRead.readLine(); if (receivedContent.startsWith("### Digest seed: ")) { digestSeed = receivedContent.substring(17, receivedContent.length()); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(digestSeed.getBytes()); md5.update(password.getBytes()); String digestStr = "login " + digestedToHex(md5.digest()) + "\n"; out.write(digestStr.getBytes()); } catch (NoSuchAlgorithmException e1) { response.append("MD5 algorithm not available - unable to complete RCON request."); keepGoing = false; } } else if (receivedContent.startsWith("error: not authenticated: you can only invoke 'login'")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication failed.")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication successful, rcon ready.")) { keepGoing = false; loggedIn = true; } } if (loggedIn) { String cmd = "exec " + command + "\n"; out.write(cmd.getBytes()); readResponse(buffRead, response); if (response.length() == 0) { throw new ResponseEmpty(); } } } catch (SocketTimeoutException timeout) { throw timeout; } catch (UnknownHostException e) { response.append("UnknownHostException: " + e.getMessage()); } catch (IOException e) { response.append("Couldn't get I/O for the connection: " + e.getMessage()); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (rconSocket != null) { rconSocket.close(); } } catch (IOException e1) { } } return response.toString(); } | private static String getBase64(String text, String algorithm) throws NoSuchAlgorithmException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); String base64; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(text.getBytes()); base64 = new BASE64Encoder().encode(md.digest()); return base64; } | 923 |
0 | public static final String Digest(String credentials, String algorithm, String encoding) { try { MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); if (encoding == null) { md.update(credentials.getBytes()); } else { md.update(credentials.getBytes(encoding)); } return (HexUtils.convert(md.digest())); } catch (Exception ex) { log.error(ex); return credentials; } } | public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); } | 924 |
1 | public void xtestURL1() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } | public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } | 925 |
0 | static String getMD5Hash(String str) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < b.length; i++) { int v = (int) b[i]; v = v < 0 ? 0x100 + v : v; String cc = Integer.toHexString(v); if (cc.length() == 1) sb.append('0'); sb.append(cc); } return sb.toString(); } | public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } } | 926 |
0 | public void sendMessageToServer(String msg, Map<String, String> args, StringCallback cb, URLConstructor ctor) { try { int tmpPort = port; for (; tmpPort < port + 10; tmpPort++) { Socket tmpSock; try { tmpSock = socketsManager.connect(new InetSocketAddress(host, port), 5000); tmpSock.close(); break; } catch (IOException e) { } } Map<String, String> newArgs = new HashMap<String, String>(args); newArgs.put("_f", String.valueOf(System.currentTimeMillis())); String request = ctor.constructURL(msg, newArgs); HttpClient client = new SimpleLimeHttpClient(); HttpGet get = new HttpGet("http://" + host + ":" + port + "/" + request); HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1); HttpResponse response = client.execute(get); String res = ""; if (response.getEntity() != null) { String result; if (response.getEntity() != null) { result = EntityUtils.toString(response.getEntity()); } else { result = null; } res = result; } cb.process(res); } catch (IOException e) { fail(e); } catch (HttpException e) { fail(e); } catch (URISyntaxException e) { fail(e); } catch (InterruptedException e) { fail(e); } } | public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); } | 927 |
0 | @Override protected String doInBackground(Location... params) { if (params == null || params.length == 0 || params[0] == null) { return null; } Location location = params[0]; String address = ""; String cachedAddress = DataService.GetInstance(mContext).getAddressFormLocationCache(location.getLatitude(), location.getLongitude()); if (!TextUtils.isEmpty(cachedAddress)) { address = cachedAddress; } else { StringBuilder jsonText = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = String.format(GoogleMapAPITemplate, location.getLatitude(), location.getLongitude()); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { jsonText.append(line); } JSONObject result = new JSONObject(jsonText.toString()); String status = result.getString(GoogleMapStatusSchema.status); if (GoogleMapStatusCodes.OK.equals(status)) { JSONArray addresses = result.getJSONArray(GoogleMapStatusSchema.results); if (addresses.length() > 0) { address = addresses.getJSONObject(0).getString(GoogleMapStatusSchema.formatted_address); if (!TextUtils.isEmpty(currentBestLocationAddress)) { DataService.GetInstance(mContext).updateAddressToLocationCache(location.getLatitude(), location.getLongitude(), currentBestLocationAddress); } } } } else { Log.e("Error", "Failed to get address via google map API."); } } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } } return address; } | @Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); } | 928 |
1 | public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; } | public ChatClient registerPlayer(int playerId, String playerLogin) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(playerLogin.getBytes("UTF-8"), 0, playerLogin.length()); byte[] accountToken = md.digest(); byte[] token = generateToken(accountToken); ChatClient chatClient = new ChatClient(playerId, token); players.put(playerId, chatClient); return chatClient; } | 929 |
0 | 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; } | @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; }; } } | 930 |
1 | public String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } } | public boolean save(Object obj) { boolean bool = false; this.result = null; if (obj == null) return bool; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, obj); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; } | 931 |
1 | private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } | public void extractProfile(String parentDir, String fileName, String profileName) { try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; if (createProfileDirectory(profileName, parentDir)) { debug("the profile directory created .starting the profile extraction"); String profilePath = parentDir + File.separator + fileName; zipinputstream = new ZipInputStream(new FileInputStream(profilePath)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(parentDir + File.separator + profileName + File.separator + newFile.getName()); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); debug("deleting the profile.zip file"); File newFile = new File(profilePath); if (newFile.delete()) { debug("the " + "[" + profilePath + "]" + " deleted successfully"); } else { debug("profile" + "[" + profilePath + "]" + "deletion fail"); throw new IllegalArgumentException("Error: deletion error!"); } } else { debug("error creating the profile directory"); } } catch (Exception e) { e.printStackTrace(); } } | 932 |
1 | public void overwriteTest() throws Exception { SRBAccount srbAccount = new SRBAccount("srb1.ngs.rl.ac.uk", 5544, this.cred); srbAccount.setDefaultStorageResource("ral-ngs1"); SRBFileSystem client = new SRBFileSystem(srbAccount); client.setFirewallPorts(64000, 65000); String home = client.getHomeDirectory(); System.out.println("home: " + home); SRBFile file = new SRBFile(client, home + "/test.txt"); assertTrue(file.exists()); File filefrom = new File("/tmp/from.txt"); assertTrue(filefrom.exists()); SRBFileOutputStream to = null; InputStream from = null; try { to = new SRBFileOutputStream((SRBFile) file); from = new FileInputStream(filefrom); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } to.flush(); } finally { try { if (to != null) { to.close(); } } catch (Exception ex) { } try { if (from != null) { from.close(); } } catch (Exception ex) { } } } | public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } } | 933 |
0 | public static void insert(Connection c, MLPApprox net, int azioneId, String descrizione, int[] indiciID, int output, Date from, Date to) throws SQLException { try { PreparedStatement ps = c.prepareStatement(insertNet, PreparedStatement.RETURN_GENERATED_KEYS); ArrayList<Integer> indexes = new ArrayList<Integer>(indiciID.length); for (int i = 0; i < indiciID.length; i++) indexes.add(indiciID[i]); ps.setObject(1, net); ps.setInt(2, azioneId); ps.setObject(3, indexes); ps.setInt(4, output); ps.setDate(5, from); ps.setDate(6, to); ps.setString(7, descrizione); ps.executeUpdate(); ResultSet key = ps.getGeneratedKeys(); if (key.next()) { int id = key.getInt(1); for (int i = 0; i < indiciID.length; i++) { PreparedStatement psIndex = c.prepareStatement(insertNetIndex); psIndex.setInt(1, indiciID[i]); psIndex.setInt(2, id); psIndex.executeUpdate(); } } } catch (SQLException e) { e.printStackTrace(); try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw e1; } throw e; } } | @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } } | 934 |
0 | @Override public void onClick(View v) { GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation(); int cid = gcl.getCid(); int lac = gcl.getLac(); int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3)); int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5)); try { JSONObject holder = new JSONObject(); holder.put("version", "1.1.0"); holder.put("host", "maps.google.com"); holder.put("request_address", true); JSONArray array = new JSONArray(); JSONObject data = new JSONObject(); data.put("cell_id", cid); data.put("location_area_code", lac); data.put("mobile_country_code", mcc); data.put("mobile_network_code", mnc); array.put(data); holder.put("cell_towers", array); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.google.com/loc/json"); StringEntity se = new StringEntity(holder.toString()); post.setEntity(se); HttpResponse resp = client.execute(post); HttpEntity entity = resp.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuffer sb = new StringBuffer(); String result = br.readLine(); while (result != null) { sb.append(result); result = br.readLine(); } JSONObject jsonObject = new JSONObject(sb.toString()); JSONObject jsonObject1 = new JSONObject(jsonObject.getString("location")); getAddress(jsonObject1.getString("latitude"), jsonObject1.getString("longitude")); } catch (Exception e) { } } | boolean isTextPage(URL url) { try { String ct = url.openConnection().getContentType().toLowerCase(); String s = url.toString(); Loro.log("LoroEDI: " + " content-type: " + ct); if (!ct.startsWith("text/") || s.endsWith(".jar") || s.endsWith(".lar")) { javax.swing.JOptionPane.showOptionDialog(null, Str.get("gui.1_browser_cannot_show_link", s), "", javax.swing.JOptionPane.DEFAULT_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, null, null); Loro.log("LoroEDI: " + " unable to display"); return false; } } catch (Exception ex) { Loro.log("LoroEDI: " + " Exception: " + ex.getMessage()); return false; } return true; } | 935 |
0 | @Override public String fetchElectronicEdition(Publication pub) { final String url = baseURL + pub.getKey() + ".html"; logger.info("fetching pub ee from local cache at: " + url); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; } | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/jar"); byte[] bufor = new byte[BUF_LEN]; ServletContext context = getServletContext(); URL url = context.getResource(FILE_NAME); InputStream in = url.openStream(); OutputStream out = response.getOutputStream(); while (in.read(bufor) != -1) out.write(bufor); in.close(); out.close(); } | 936 |
0 | protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } } | public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } } | 937 |
1 | protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = super.getDatastreams(pDeposit); FileInputStream tInput = null; String tFileName = ((LocalDatastream) tDatastreams.get(0)).getPath(); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".thum")); tInput.close(); Datastream tThum = new LocalDatastream("THUMBRES_IMG", this.getContentType(), tTempFileName + ".thum"); tDatastreams.add(tThum); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".mid")); tInput.close(); Datastream tMid = new LocalDatastream("MEDRES_IMG", this.getContentType(), tTempFileName + ".mid"); tDatastreams.add(tMid); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".high")); tInput.close(); Datastream tLarge = new LocalDatastream("HIGHRES_IMG", this.getContentType(), tTempFileName + ".high"); tDatastreams.add(tLarge); IOUtils.copy(tInput = new FileInputStream(tFileName), new FileOutputStream(tTempFileName + ".vhigh")); tInput.close(); Datastream tVLarge = new LocalDatastream("VERYHIGHRES_IMG", this.getContentType(), tTempFileName + ".vhigh"); tDatastreams.add(tVLarge); return tDatastreams; } | public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); 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(); } } | 938 |
0 | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | public String sendRequest(java.lang.String servletName, java.lang.String request) { String reqxml = ""; org.jdom.Document retdoc = null; String myurl = java.util.prefs.Preferences.systemRoot().get("serverurl", ""); String myport = ""; myport = java.util.prefs.Preferences.systemRoot().get("portno", "8080"); if (myport == null || myport.trim().equals("")) { myport = "80"; } if (this.serverURL == null) { try { java.net.URL codebase = newgen.presentation.NewGenMain.getAppletInstance().getCodeBase(); if (codebase != null) serverURL = codebase.getHost(); else serverURL = "localhost"; } catch (Exception exp) { exp.printStackTrace(); serverURL = "localhost"; } newgen.presentation.component.IPAddressPortNoDialog ipdig = new newgen.presentation.component.IPAddressPortNoDialog(myurl, myport); ipdig.show(); serverURL = myurl = ipdig.getIPAddress(); myport = ipdig.getPortNo(); java.util.prefs.Preferences.systemRoot().put("serverurl", serverURL); java.util.prefs.Preferences.systemRoot().put("portno", myport); System.out.println(serverURL); } try { System.out.println("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URL url = new java.net.URL("http://" + serverURL + ":" + myport + "/newgenlibctxt/" + servletName); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); String req1xml = request; java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println("#########***********$$$$$$$$##########" + req1xml); dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.InputStreamReader br = new java.io.InputStreamReader(gip, "UTF-8"); retdoc = (new org.jdom.input.SAXBuilder()).build(br); } catch (java.net.ConnectException conexp) { javax.swing.JOptionPane.showMessageDialog(null, newgen.presentation.NewGenMain.getAppletInstance().getMyResource().getString("ConnectExceptionMessage"), "Critical error", javax.swing.JOptionPane.ERROR_MESSAGE); } catch (Exception exp) { exp.printStackTrace(System.out); TroubleShootConnectivity troubleShoot = new TroubleShootConnectivity(); } System.out.println(reqxml); return (new org.jdom.output.XMLOutputter()).outputString(retdoc); } | 939 |
1 | public String kodetu(String testusoila) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(testusoila.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { new MezuLeiho("Ez da zifraketa algoritmoa aurkitu", "Ados", "Zifraketa Arazoa", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (UnsupportedEncodingException e) { new MezuLeiho("Errorea kodetzerakoan", "Ados", "Kodeketa Errorea", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } | public static String md5(String plain) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { PApplet.println("[ERROR]: md5() " + e); return ""; } md5.reset(); md5.update(plain.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i += 1) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); } | 940 |
0 | @Override public synchronized void deleteHttpSessionStatistics(String contextName, String project, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHttpSessionInvocationsSchemaAndTableName() + " FROM " + this.getHttpSessionInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHttpSessionElementsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (project != null) { queryString = queryString + " project LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (project != null) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting HTTP session statistics.", e); } finally { this.releaseConnection(connection); } } | public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } } | 941 |
1 | private void processData(InputStream raw) { String fileName = remoteName; if (localName != null) { fileName = localName; } try { FileOutputStream fos = new FileOutputStream(new File(fileName), true); IOUtils.copy(raw, fos); LOG.info("ok"); } catch (IOException e) { LOG.error("error writing file", e); } } | public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; String review = request.getParameter("review"); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = request.getParameter("inforId"); request.setAttribute("id", inforId); String str_postFIX = ""; int i_p = 0; if (null == review) { FormFile file = vo.getFile(); if (file != null) { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); return "editsave"; } else { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); FormFile file = vo.getFile(); FormFile file2 = vo.getFile2(); FormFile file3 = vo.getFile3(); t_infor_review newreview = new t_infor_review(); String content = request.getParameter("content"); newreview.setContent(content); if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId)); newreview.setInsert_day(new Date()); UserDetails user = LoginUtils.getLoginUser(request); newreview.setCreate_name(user.getUsercode()); if (null != file.getFileName() && !"".equals(file.getFileName())) { newreview.setAttachname1(file.getFileName()); String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX); saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX); } if (null != file2.getFileName() && !"".equals(file2.getFileName())) { newreview.setAttachname2(file2.getFileName()); String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file2.getFileName().lastIndexOf("."); str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length()); newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX); saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX); } if (null != file3.getFileName() && !"".equals(file3.getFileName())) { newreview.setAttachname3(file3.getFileName()); String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file3.getFileName().lastIndexOf("."); str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length()); newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX); saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX); } t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap(); reviewEdit.add(newreview); request.setAttribute("review", "1"); return "aftersave"; } } | 942 |
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); } } | public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; } | 943 |
0 | 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) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } | PathElement(String path) throws MaxError { this.path = path; if (path.startsWith("http:")) { try { url = new URL(path); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); valid = (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { valid = false; } } else { if (path.startsWith("jmax:")) file = new File(Registry.resolveJMaxURI(path)); else file = new File(path); valid = file.exists(); } } | 944 |
0 | public static void downloadXrefTask(String url, String file) { int n, progressi, progressn; if (debug) System.err.println("Downloading " + url + " into " + file); Progress progress = Progress.crNew(null, "Downloading xref task"); FileOutputStream oo = null; InputStream ii = null; try { URLConnection con = new URL(url).openConnection(); ii = con.getInputStream(); File of = new File(file); if (!of.getParentFile().exists()) { of.getParentFile().mkdir(); } oo = new FileOutputStream(of); byte buffer[] = new byte[XREF_DOWNLOAD_BUFFER_SIZE]; progressi = 0; progressn = con.getContentLength(); n = 1; while (n >= 0) { n = ii.read(buffer, 0, XREF_DOWNLOAD_BUFFER_SIZE); if (n > 0) { oo.write(buffer, 0, n); progressi += n; } if (!progress.setProgress(progressi * 100 / progressn)) { n = -2; } } ii.close(); oo.close(); fileSetExecPermission(file); if (n == -2) { of.delete(); } } catch (Exception e) { try { if (oo != null) { oo.close(); new File(file).delete(); } if (ii != null) ii.close(); } catch (Exception ee) { } progress.setVisible(false); JOptionPane.showMessageDialog(null, e.toString() + "\nWhile downloading " + url + ".\nMaybe wrong proxy configuration?", "Xrefactory Error", JOptionPane.ERROR_MESSAGE); } progress.setVisible(false); } | public static Document getResponse(HttpClient client, HttpRequestBase request) { try { HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); System.err.println(statusLine.getStatusCode() + " data: " + statusLine.getReasonPhrase()); System.err.println("executing request " + request.getURI()); HttpEntity entity = response.getEntity(); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(entity.getContent()); return doc; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } | 945 |
1 | private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; } | private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } } | 946 |
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 static void createCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { String[] spaceSplit = PerlHelp.split(line); for (int i = 0; i < spaceSplit.length; i++) { if (spaceSplit[i].indexOf('_') >= 0) { s.add(spaceSplit[i].replace('_', ' ')); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "compound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } } | 947 |
0 | public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } | private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } | 948 |
1 | public static void loadConfig(DeviceEntry defaultDevice, EmulatorContext emulatorContext) { Config.defaultDevice = defaultDevice; Config.emulatorContext = emulatorContext; File configFile = new File(getConfigPath(), "config2.xml"); try { if (configFile.exists()) { loadConfigFile("config2.xml"); } else { configFile = new File(getConfigPath(), "config.xml"); if (configFile.exists()) { loadConfigFile("config.xml"); for (Enumeration e = getDeviceEntries().elements(); e.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) e.nextElement(); if (!entry.canRemove()) { continue; } removeDeviceEntry(entry); File src = new File(getConfigPath(), entry.getFileName()); File dst = File.createTempFile("dev", ".jar", getConfigPath()); IOUtils.copyFile(src, dst); entry.setFileName(dst.getName()); addDeviceEntry(entry); } } else { createDefaultConfigXml(); } saveConfig(); } } catch (IOException ex) { Logger.error(ex); createDefaultConfigXml(); } finally { if (configXml == null) { createDefaultConfigXml(); } } urlsMRU.read(configXml.getChildOrNew("files").getChildOrNew("recent")); initSystemProperties(); } | public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } } | 949 |
1 | protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } | public static void toZip(File zippedFile, File[] filesToZip, String zipComment, boolean savePath, int compressionLevel) throws IOException, FileNotFoundException, ZipException { if (zippedFile != null && filesToZip != null) { new File(zippedFile.getParent()).mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new CheckedOutputStream(new FileOutputStream(zippedFile), new CRC32()))); if (ZIP_NO_COMPRESSION <= compressionLevel && compressionLevel <= ZIP_MAX_COMPRESSION) out.setLevel(compressionLevel); else out.setLevel(ZIP_MAX_COMPRESSION); if (zipComment != null) out.setComment(zipComment); for (int i = 0; i < filesToZip.length; i++) { BufferedInputStream in; if (savePath) { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(cleanPath(filesToZip[i].getAbsolutePath()))); } else { in = new BufferedInputStream(new FileInputStream(filesToZip[i])); out.putNextEntry(new ZipEntry(filesToZip[i].getName())); } for (int c = in.read(); c != -1; c = in.read()) out.write(c); in.close(); } out.close(); } else throw new ZipException(MAIN_RESOURCE_BUNDLE.getString("default.ZipException.text")); } | 950 |
0 | private void sendToURL(String URL, String file) throws Exception { URL url = new URL(URL); InputStream is = new BufferedInputStream(new FileInputStream(file)); OutputStream os = url.openConnection().getOutputStream(); copyDocument(is, os); is.close(); os.close(); } | public void run() { try { ThreadGroup transfers = new ThreadGroup("transfers"); URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/"); JarURLConnection juc = (JarURLConnection) url.openConnection(); File top = new File(System.getProperty("user.home"), "jopenrpg"); final JarFile jarfile = juc.getJarFile(); Enumeration enumer = jarfile.entries(); while (enumer.hasMoreElements()) { final JarEntry entry = (JarEntry) enumer.nextElement(); final File f = new File(top, entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); StringBuffer buf = new StringBuffer(); while (br.ready()) { buf.append(br.read()); } bw.write(buf.toString(), 0, buf.length()); bw.close(); br.close(); } catch (Exception ex) { System.out.println(ex); } } }).start(); } } while (transfers.activeCount() > 0) yield(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed."); } }); } catch (Exception ex) { ex.printStackTrace(); } } | 951 |
0 | public void viewFile(int file_nx) { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; ftp.connect("tgftp.nws.noaa.gov"); ftp.login("anonymous", ""); Log.d("WXDroid", "Connected to tgftp.nws.noaa.gov."); Log.d("WXDroid", ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftp.changeWorkingDirectory("fax"); Log.d("WXDroid", "working directory: " + ftp.printWorkingDirectory()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); InputStream img_file = ftp.retrieveFileStream("PYAA10.gif"); String storage_state = Environment.getExternalStorageState(); if (storage_state.contains("mounted")) { String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/NOAAWX/"; File imageDirectory = new File(filepath); File local_file = new File(filepath + "PYAA10.gif"); OutputStream out = new FileOutputStream(local_file); byte[] buffer = new byte[1024]; int count; while ((count = img_file.read(buffer)) != -1) { if (Thread.interrupted() == true) { String functionName = Thread.currentThread().getStackTrace()[2].getMethodName() + "()"; throw new InterruptedException("The function " + functionName + " was interrupted."); } out.write(buffer, 0, count); } wxDroid.showImage(); out.flush(); out.close(); img_file.close(); Log.d("WXDroid", "file saved: " + filepath + " " + local_file); } else { Log.d("WXDroid", "The SD card is not mounted"); } ftp.logout(); ftp.disconnect(); } catch (IOException e) { error = true; e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } | public void updatePortletName(PortletNameBean portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } | 952 |
0 | protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } } | protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); } | 953 |
1 | public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } | public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; } | 954 |
1 | @Override public void run() { try { File[] inputFiles = new File[this.previousFiles != null ? this.previousFiles.length + 1 : 1]; File copiedInput = new File(this.randomFolder, this.inputFile.getName()); IOUtils.copyFile(this.inputFile, copiedInput); inputFiles[inputFiles.length - 1] = copiedInput; if (previousFiles != null) { for (int i = 0; i < this.previousFiles.length; i++) { File prev = this.previousFiles[i]; File copiedPrev = new File(this.randomFolder, prev.getName()); IOUtils.copyFile(prev, copiedPrev); inputFiles[i] = copiedPrev; } } org.happycomp.radiog.Activator activator = org.happycomp.radiog.Activator.getDefault(); if (this.exportedMP3File != null) { EncodingUtils.encodeToWavAndThenMP3(inputFiles, this.exportedWavFile, this.exportedMP3File, this.deleteOnExit, this.randomFolder, activator.getCommandsMap()); } else { EncodingUtils.encodeToWav(inputFiles, this.exportedWavFile, randomFolder, activator.getCommandsMap()); } if (encodeMonitor != null) { encodeMonitor.setEncodingFinished(true); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } | protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } | 955 |
1 | private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; } | private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; } | 956 |
1 | public static void copyFile(final File fromFile, File toFile) throws IOException { try { if (!fromFile.exists()) { throw new IOException("FileCopy: " + "no such source file: " + fromFile.getAbsoluteFile()); } if (!fromFile.isFile()) { throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getAbsoluteFile()); } if (!fromFile.canRead()) { throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getAbsoluteFile()); } if (toFile.isDirectory()) { toFile = new File(toFile, fromFile.getName()); } if (toFile.exists() && !toFile.canWrite()) { throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getAbsoluteFile()); } final FileChannel inChannel = new FileInputStream(fromFile).getChannel(); final FileChannel outChannel = new FileOutputStream(toFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (final IOException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("CopyFile went wrong!", e); } } } | public static void copyFile(File source, File dest) throws Exception { FileInputStream fis = new FileInputStream(source); try { FileOutputStream fos = new FileOutputStream(dest); try { int read = fis.read(); while (read != -1) { fos.write(read); read = fis.read(); } } finally { fos.close(); } } finally { fis.close(); } } | 957 |
0 | private void retrieveData() { StringBuffer obsBuf = new StringBuffer(); try { URL url = new URL(getProperty("sourceURL")); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String lineIn = null; while ((lineIn = in.readLine()) != null) { if (GlobalProps.DEBUG) { logger.log(Level.FINE, "WebSource retrieveData: " + lineIn); } obsBuf.append(lineIn); } String fmt = getProperty("dataFormat"); if (GlobalProps.DEBUG) { logger.log(Level.FINE, "Raw: " + obsBuf.toString()); } if ("NWS XML".equals(fmt)) { obs = new NWSXmlObservation(obsBuf.toString()); } } catch (Exception e) { logger.log(Level.SEVERE, "Can't connect to: " + getProperty("sourceURL")); if (GlobalProps.DEBUG) { e.printStackTrace(); } } } | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | 958 |
1 | public final int connectAndLogin(Uri u, boolean cwd) throws UnknownHostException, IOException, InterruptedException { if (ftp.isLoggedIn()) { if (cwd) { String path = u.getPath(); if (path != null) ftp.setCurrentDir(path); } return WAS_IN; } int port = u.getPort(); if (port == -1) port = 21; String host = u.getHost(); if (ftp.connect(host, port)) { if (theUserPass == null || theUserPass.isNotSet()) theUserPass = new FTPCredentials(u.getUserInfo()); if (ftp.login(theUserPass.getUserName(), theUserPass.getPassword())) { if (cwd) { String path = u.getPath(); if (path != null) ftp.setCurrentDir(path); } return LOGGED_IN; } else { ftp.logout(true); ftp.disconnect(); Log.w(TAG, "Invalid credentials."); return NO_LOGIN; } } return NO_CONNECT; } | public void initGet() throws Exception { cl = new FTPClient(); URL url = new URL(getURL()); cl.setRemoteHost(url.getHost()); cl.connect(); cl.login(user, pass); cl.setType(FTPTransferType.BINARY); cl.setConnectMode(FTPConnectMode.PASV); cl.restart(getPosition()); } | 959 |
1 | public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException(MM.PHRASES.getPhrase("25") + " " + source_name); if (!source_file.canRead()) throw new FileCopyException(MM.PHRASES.getPhrase("26") + " " + MM.PHRASES.getPhrase("27") + ": " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("29") + ": " + dest_name); System.out.print(MM.PHRASES.getPhrase("19") + dest_name + MM.PHRASES.getPhrase("30") + ": "); System.out.flush(); response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new FileCopyException(MM.PHRASES.getPhrase("31")); } else throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("32") + ": " + dest_name); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("33") + ": " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException(MM.PHRASES.getPhrase("28") + " " + MM.PHRASES.getPhrase("34") + ": " + dest_name); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) try { source.close(); } catch (IOException e) { ; } if (destination != null) try { destination.close(); } catch (IOException e) { ; } } } | private void doIt() throws Throwable { GenericDAO<User> dao = DAOFactory.createDAO(User.class); try { final User user = dao.findUniqueByCriteria(Expression.eq("login", login)); if (user == null) throw new IllegalArgumentException("Specified user isn't exist"); if (srcDir.isDirectory() && srcDir.exists()) { final String[] fileList = srcDir.list(new XFilenameFilter() { public boolean accept(XFile dir, String file) { String[] fNArr = file.split("\\."); return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt"))); } }); int pointsCounter = 0; int tracksCounter = 0; int mapsCounter = 0; for (final String fName : fileList) { try { TransactionManager.beginTransaction(); } catch (Throwable e) { logger.error(e); throw e; } final XFile file = new XFile(srcDir, fName); InputStream in = new XFileInputStream(file); try { ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>(); ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>(); final byte[] headerBuf = new byte[1024]; if (in.read(headerBuf) <= 0) continue; final String fileHeader = new String(headerBuf); final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0); final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0); final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0); final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0); if (isOziMAP || isOziPLT || isOziWPT || isKML) { in.close(); in = new XFileInputStream(file); } else continue; WPTPoint wp; if (isOziWPT) { try { wp = new WPTPointParser(in, "Cp1251").parse(); } catch (Throwable t) { wp = null; } if (wp != null) { Set<WayPointRow> rows = wp.getPoints(); for (WayPointRow row : rows) { final UserMapPoint p = BeanFactory.createUserPoint(row, user); logger.info("point:" + p.getGuid()); } pointsCounter += rows.size(); } } else if (isOziPLT) { PLTTrack plt; try { plt = new PLTTrackParser(in, "Cp1251").parse(); } catch (Throwable t) { plt = null; } if (plt != null) { final UserMapTrack t = BeanFactory.createUserTrack(plt, user); tracks.add(new MapTrackPointsScaleRequest(t)); tracksCounter++; logger.info("track:" + t.getGuid()); } } else if (isOziMAP) { MapProjection projection; MAPParser parser = new MAPParser(in, "Cp1251"); try { projection = parser.parse(); } catch (Throwable t) { projection = null; } if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) { GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class); final UserMapOriginal mapOriginal = new UserMapOriginal(); mapOriginal.setName(projection.getTitle()); mapOriginal.setUser(user); mapOriginal.setState(UserMapOriginal.State.UPLOAD); mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE); MapManager.updateProjection(projection, mapOriginal); final XFile srcFile = new XFile(srcDir, projection.getPath()); if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found"); final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid()); mapStorage.mkdir(); XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid()); XFileOutputStream out = new XFileOutputStream(dstFile); XFileInputStream inImg = new XFileInputStream(srcFile); IOUtils.copy(inImg, out); out.flush(); out.close(); inImg.close(); mapDao.save(mapOriginal); maps.add(mapOriginal); srcFile.delete(); mapsCounter++; logger.info("map:" + mapOriginal.getGuid()); } } else logger.warn("unsupported file format: " + file.getName()); TransactionManager.commitTransaction(); for (MapTrackPointsScaleRequest track : tracks) { if (track != null) { try { PoolClientInterface pool = PoolFactory.getInstance().getClientPool(); if (pool == null) throw new IllegalStateException("pool not found"); pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class); } catch (Throwable t) { logger.error(t); } } } } catch (Throwable e) { logger.error("Error importing", e); TransactionManager.rollbackTransaction(); } finally { in.close(); file.delete(); } } logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter); } } catch (Throwable e) { logger.error("Error importing", e); } } | 960 |
0 | public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); } | public void run() { OutputStream out = null; InputStream in = null; boolean success = false; String absoluteFileName = ""; try { String fileName = getFileName(softwareLocation); File downloadFolder = new File(Properties.downloadFolder); if (downloadFolder.exists()) { if (downloadFolder.isDirectory()) { fileName = downloadFolder.getPath() + File.separator + fileName; } } else { downloadFolder.mkdir(); fileName = downloadFolder.getPath() + File.separator + fileName; } File softwareFile = new File(fileName); absoluteFileName = softwareFile.getAbsolutePath(); if (softwareFile.exists() && softwareFile.length() == softwareSize) { XohmLogger.debugPrintln("Software file already exists. Exiting..."); listener.downloadComplete(true, softwareName, absoluteFileName); return; } else { try { File[] oldFiles = downloadFolder.listFiles(); for (int i = 0; i < oldFiles.length; i++) { oldFiles[i].delete(); } } catch (Exception ex) { } } File softwareTempFile = File.createTempFile("XOHMCM", null); URL url = new URL(softwareLocation); out = new BufferedOutputStream(new FileOutputStream(softwareTempFile)); URLConnection connection = url.openConnection(); in = connection.getInputStream(); listener.downloadStarted(softwareName); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; listener.downloadProgressNotification(softwareName, numWritten, softwareSize); } out.flush(); out.close(); in.close(); if (copyFile(softwareTempFile, softwareFile)) { XohmLogger.debugPrintln("Download complete: " + absoluteFileName + "\t" + numWritten); success = true; softwareTempFile.delete(); } } catch (Exception ex) { XohmLogger.warningPrintln("Software Update download failed - " + ex.getMessage(), null, null); ex.printStackTrace(); } listener.downloadComplete(success, softwareName, absoluteFileName); } | 961 |
0 | public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } } | public static final String crypt(final String password, String salt, final String magic) { if (password == null) throw new IllegalArgumentException("Null password!"); if (salt == null) throw new IllegalArgumentException("Null salt!"); if (magic == null) throw new IllegalArgumentException("Null salt!"); byte finalState[]; long l; MessageDigest ctx, ctx1; try { ctx = MessageDigest.getInstance("md5"); ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException ex) { System.err.println(ex); return null; } if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { ctx.update(finalState, 0, pl > 16 ? 16 : pl); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState, 0, 1); } else { ctx.update(password.getBytes(), 0, 1); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { try { ctx1 = MessageDigest.getInstance("md5"); } catch (final NoSuchAlgorithmException e0) { return null; } if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { ctx1.update(finalState, 0, 16); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { ctx1.update(finalState, 0, 16); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } final StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); } | 962 |
0 | public boolean getFile(String pRemoteDirectory, String pLocalDirectory, String pFileName) throws IOException { FTPClient fc = new FTPClient(); fc.connect(getRemoteHost()); fc.login(getUserName(), getPassword()); fc.changeWorkingDirectory(pRemoteDirectory); String workingDirectory = fc.printWorkingDirectory(); FileOutputStream fos = null; logInfo("Connected to remote host=" + getRemoteHost() + "; userName=" + getUserName() + "; " + "; remoteDirectory=" + pRemoteDirectory + "; localDirectory=" + pLocalDirectory + "; workingDirectory=" + workingDirectory); try { fos = new FileOutputStream(pLocalDirectory + "/" + pFileName); boolean retrieved = fc.retrieveFile(pFileName, fos); if (true == retrieved) { logInfo("Successfully retrieved file: " + pFileName); } else { logError("Could not retrieve file: " + pFileName); } return retrieved; } finally { if (null != fos) { fos.flush(); fos.close(); } } } | private ArrayList<String> getYearsAndMonths() { String info = ""; ArrayList<String> items = new ArrayList<String>(); try { obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data")); URL url = new URL(URL_ROUTE_VIEWS); URLConnection conn = url.openConnection(); conn.setDoOutput(false); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (!line.equals("")) info += line + "%"; } obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data")); info = Patterns.removeTags(info); StringTokenizer st = new StringTokenizer(info, "%"); info = ""; boolean alternador = false; int index = 1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!token.trim().equals("")) { int pos = token.indexOf("/"); if (pos != -1) { token = token.substring(1, pos); if (Patterns.hasFormatYYYYdotMM(token)) { items.add(token); } } } } rd.close(); } catch (Exception e) { e.printStackTrace(); } return items; } | 963 |
1 | public static void copyFile(String sourceName, String destName) throws IOException { FileChannel sourceChannel = null; FileChannel destChannel = null; try { sourceChannel = new FileInputStream(sourceName).getChannel(); destChannel = new FileOutputStream(destName).getChannel(); destChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException exception) { throw exception; } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException ex) { } } if (destChannel != null) { try { destChannel.close(); } catch (IOException ex) { } } } } | public 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; } | 964 |
0 | private Document getXMLDoc(Region region) { Document doc; try { InputStream stream; URL url = new URL("http://eve-central.com/api/marketstat?hours=" + HOURS + "&" + getTypes() + "®ionlimit=" + region.getTypeID()); System.out.println(url.toString()); stream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); doc = parser.parse(stream); } catch (MalformedURLException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (SAXException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (IOException e) { e.printStackTrace(); doc = new DefaultDocument(); } catch (ParserConfigurationException e) { e.printStackTrace(); doc = new DefaultDocument(); } return doc; } | 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; } | 965 |
0 | private RSSFeed getFeed(String urlToRssFeed) { try { URL url = new URL(urlToRssFeed); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); XMLReader xmlreader = parser.getXMLReader(); RSSHandler theRssHandler = new RSSHandler(); xmlreader.setContentHandler(theRssHandler); InputSource is = new InputSource(url.openStream()); xmlreader.parse(is); return theRssHandler.getFeed(); } catch (Exception ee) { return null; } } | public static synchronized String getURLContent(URL url) { Log log = LogUtil.getLog(FileManager.class, "getURLContent"); if (url == null) { throw new IllegalArgumentException("url shouldn't be null!"); } String content = (String) urlCache.get(url); if (content != null) { return content; } try { InputStream is = null; if ("file".equals(url.getProtocol())) { is = new java.io.FileInputStream(url.getFile()); } else { is = url.openStream(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(is.available()); pump(is, baos); content = new String(baos.toByteArray()); urlCache.put(url, content); return content; } catch (FileNotFoundException e) { return null; } catch (Exception e) { e.printStackTrace(); log.error(Translator.getString(XDocletMessages.class, XDocletUtilMessages.EXCEPTION_READING_MERGE_FILE, new String[] { e.toString() })); return null; } } | 966 |
1 | private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } | private boolean authenticateWithServer(String user, String password) { Object o; String response; byte[] dataKey; try { o = objectIn.readObject(); if (o instanceof String) { response = (String) o; Debug.netMsg("Connected to JFritz Server: " + response); if (!response.equals("JFRITZ SERVER 1.1")) { Debug.netMsg("Unkown Server version, newer JFritz protocoll version?"); Debug.netMsg("Canceling login attempt!"); } objectOut.writeObject(user); objectOut.flush(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.DECRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(desCipher); if (o instanceof byte[]) { dataKey = (byte[]) o; desKeySpec = new DESKeySpec(dataKey); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealed_ok = new SealedObject("OK", outCipher); objectOut.writeObject(sealed_ok); SealedObject sealed_response = (SealedObject) objectIn.readObject(); o = sealed_response.getObject(inCipher); if (o instanceof String) { if (o.equals("OK")) { return true; } else { Debug.netMsg("Server sent wrong string as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong object as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong type for data key!"); } } } catch (ClassNotFoundException e) { Debug.error("Server authentication response invalid!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (EOFException e) { Debug.error("Server closed Stream unexpectedly!"); Debug.error(e.toString()); e.printStackTrace(); } catch (SocketTimeoutException e) { Debug.error("Read timeout while authenticating with server!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.error("Error reading response during authentication!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IllegalBlockSizeException e) { Debug.error("Illegal block size exception!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.error("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return false; } | 967 |
0 | private DictionaryListParser downloadList(final String url) throws IOException, JSONException { final HttpClient client = new DefaultHttpClient(); final HttpGet httpGet = new HttpGet(url); final HttpResponse response = client.execute(httpGet); final HttpEntity entity = response.getEntity(); if (entity == null) { throw new IOException("HttpResponse.getEntity() IS NULL"); } final boolean isValidType = entity.getContentType().getValue().startsWith(RESPONSE_CONTENT_TYPE); if (!isValidType) { final String message = "CONTENT_TYPE IS '" + entity.getContentType().getValue() + "'"; throw new IOException(message); } final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), RESPONSE_ENCODING)); final StringBuilder stringResult = new StringBuilder(); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { stringResult.append(line); } } finally { reader.close(); } return new DictionaryListParser(stringResult); } | public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } } | 968 |
0 | protected Collection<BibtexEntry> getBibtexEntries(String ticket, String citations) throws IOException { try { URL url = new URL(URL_BIBTEX); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", ticket + "; " + citations); conn.connect(); BibtexParser parser = new BibtexParser(new BufferedReader(new InputStreamReader(conn.getInputStream()))); return parser.parse().getDatabase().getEntries(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } | @Override protected String doInBackground(String... params) { HttpURLConnection conn = null; String localFilePath = params[0]; if (localFilePath == null) { return null; } try { URL url = new URL(ConnectionHandler.getServerURL() + ":" + ConnectionHandler.getServerPort() + "/"); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); DataInputStream fileReader = new DataInputStream(new FileInputStream(localFilePath)); dos.write(toByte(twoHyphens + boundary + lineEnd)); dos.write(toByte("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"redpinfile\"" + lineEnd)); dos.write(toByte("Content-Type: application/octet-stream" + lineEnd)); dos.write(toByte("Content-Length: " + fileReader.available() + lineEnd)); dos.write(toByte(lineEnd)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileReader.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } dos.write(toByte(lineEnd)); dos.write(toByte(twoHyphens + boundary + twoHyphens + lineEnd)); dos.flush(); dos.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } return b.toString(); } } catch (MalformedURLException ex) { Log.w(TAG, "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.w(TAG, "error: " + ioe.getMessage(), ioe); } finally { if (conn != null) { conn.disconnect(); } } return null; } | 969 |
0 | @Override public BufferedImageAndBytes load(T thing) { String iurl = resolver.getUrl(thing); URL url; for (int k = 0; k < nTries; k++) { if (k > 0) { logger.debug("retry #" + k); } try { url = new URL(iurl); URLConnection connection = url.openConnection(); if (userAgent != null) { connection.setRequestProperty("User-Agent", userAgent); } InputStream is = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(40000); int b; while ((b = is.read()) != -1) { baos.write(b); } is.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage image = ImageIO.read(bais); return new BufferedImageAndBytes(image, bytes); } catch (MalformedURLException e) { continue; } catch (IOException e) { continue; } } return null; } | private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; } | 970 |
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(); } } | public void writeBack(File destinationFile, boolean makeCopy) throws IOException { if (makeCopy) { FileChannel sourceChannel = new java.io.FileInputStream(getFile()).getChannel(); FileChannel destinationChannel = new java.io.FileOutputStream(destinationFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } else { getFile().renameTo(destinationFile); } if (getExifTime() != null && getOriginalTime() != null && !getExifTime().equals(getOriginalTime())) { String adjustArgument = "-ts" + m_dfJhead.format(getExifTime()); ProcessBuilder pb = new ProcessBuilder(m_tm.getJheadCommand(), adjustArgument, destinationFile.getAbsolutePath()); pb.directory(destinationFile.getParentFile()); System.out.println(pb.command().get(0) + " " + pb.command().get(1) + " " + pb.command().get(2)); final Process p = pb.start(); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } } | 971 |
1 | private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } | public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; } | 972 |
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(); } } | protected int sendData(String submitName, String submitValue) throws HttpException, IOException, SAXException { PostMethod postMethod = null; try { postMethod = new PostMethod(getDocumentBase().toString()); postMethod.getParams().setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.IGNORE_COOKIES); postMethod.addRequestHeader("Cookie", getWikiPrefix() + "_session=" + getSession() + "; " + getWikiPrefix() + "UserID=" + getUserId() + "; " + getWikiPrefix() + "UserName=" + getUserName() + "; "); List<Part> parts = new ArrayList<Part>(); for (String s : new String[] { "wpSection", "wpEdittime", "wpScrolltop", "wpStarttime", "wpEditToken" }) { parts.add(new StringPart(s, StringEscapeUtils.unescapeJava(getNonNullParameter(s)))); } parts.add(new StringPart("action", "edit")); parts.add(new StringPart("wpTextbox1", getArticleContent())); parts.add(new StringPart("wpSummary", getSummary())); parts.add(new StringPart("wpAutoSummary", Digest.MD5.isImplemented() ? Digest.MD5.encrypt(getSummary()) : "")); parts.add(new StringPart(submitName, submitValue)); MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), postMethod.getParams()); postMethod.setRequestEntity(requestEntity); int status = getHttpClient().executeMethod(postMethod); IOUtils.copyTo(postMethod.getResponseBodyAsStream(), System.err); return status; } catch (HttpException err) { throw err; } catch (IOException err) { throw err; } finally { if (postMethod != null) postMethod.releaseConnection(); } } | 973 |
1 | private void init(URL url) { frame = new JInternalFrame(name); frame.addInternalFrameListener(this); listModel.add(listModel.size(), this); area = new JTextArea(); area.setMargin(new Insets(5, 5, 5, 5)); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String in; while ((in = reader.readLine()) != null) { area.append(in); area.append("\n"); } reader.close(); } catch (Exception e) { e.printStackTrace(); return; } th = area.getTransferHandler(); area.setFont(new Font("monospaced", Font.PLAIN, 12)); area.setCaretPosition(0); area.setDragEnabled(true); area.setDropMode(DropMode.INSERT); frame.getContentPane().add(new JScrollPane(area)); dp.add(frame); frame.show(); if (DEMO) { frame.setSize(300, 200); } else { frame.setSize(400, 300); } frame.setResizable(true); frame.setClosable(true); frame.setIconifiable(true); frame.setMaximizable(true); frame.setLocation(left, top); incr(); SwingUtilities.invokeLater(new Runnable() { public void run() { select(); } }); nullItem.addActionListener(this); setNullTH(); } | private boolean loadSource(URL url) { if (url == null) { if (sourceURL != null) { sourceCodeLinesList.clear(); } return false; } else { if (url.equals(sourceURL)) { return true; } else { sourceCodeLinesList.clear(); try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { sourceCodeLinesList.addElement(line.replaceAll("\t", " ")); } br.close(); return true; } catch (IOException e) { System.err.println("Could not load source at " + url); return false; } } } } | 974 |
1 | @Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } } | public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.close(); } | 975 |
1 | public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } | public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { 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) { e.printStackTrace(); } } | 976 |
1 | @RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; } | public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } | 977 |
1 | public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); } | public void close() { try { if (writer != null) { BufferedReader reader; writer.close(); writer = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < headers.size(); i++) writer.write(headers.get(i) + ","); writer.write("\n"); reader = new BufferedReader(new FileReader(file)); while (reader.ready()) writer.write(reader.readLine() + "\n"); reader.close(); writer.close(); file.delete(); } } catch (java.io.IOException e) { throw new RuntimeException(e); } } | 978 |
1 | public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } | 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; } | 979 |
0 | 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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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()); } | public void run() { try { URL url = new URL("http://localhost:8080/WebGISTileServer/index.jsp?token_timeout=true"); URLConnection uc = url.openConnection(); uc.addRequestProperty("Referer", "http://localhost:8080/index.jsp"); BufferedReader rd = new BufferedReader(new InputStreamReader(uc.getInputStream())); String line; while ((line = rd.readLine()) != null) System.out.println(line); } catch (Exception e) { e.printStackTrace(); } } | 980 |
1 | 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); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } | protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = LocalNameGenerator.class.getResource("/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } } | 981 |
0 | public static IFigure render(IDiagram diagram) { Diagram realDiagram; try { realDiagram = ((Diagram.IDiagramImpl) diagram).getDiagram(); } catch (ClassCastException x) { throw new IllegalArgumentException("invalid diagram parameter"); } ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(RMBenchPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new CustomEditPartFactory()); viewer.setContents(realDiagram); AbstractGraphicalEditPart aep = (AbstractGraphicalEditPart) viewer.getRootEditPart(); refresh(aep); IFigure root = ((AbstractGraphicalEditPart) viewer.getRootEditPart()).getFigure(); setPreferedSize(root); return root; } | @SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } | 982 |
0 | public static String[] check() throws Exception { if (currentVersion == null) throw new Exception(); URL url = new URL(versionURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String str = ""; BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); while (br.ready()) { str = str + br.readLine(); } br.close(); Document document = DocumentHelper.parseText(str); Node node = document.selectSingleNode("//root/version"); String latestVersion = node.valueOf("@id"); Double latest = Double.parseDouble(latestVersion); Double current = Double.parseDouble(currentVersion.substring(0, currentVersion.indexOf("-"))); if (latest > current) { String[] a = { latestVersion, node.valueOf("@url"), node.valueOf("@description") }; return a; } return null; } | public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; } | 983 |
1 | public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; } | public static void main(String[] args) { FTPClient client = new FTPClient(); try { client.connect("192.168.1.10"); boolean login = client.login("a", "123456"); if (login) { System.out.println("Dang nhap thanh cong..."); boolean logout = client.logout(); if (logout) { System.out.println("Da Logout khoi FTP Server..."); } } else { System.out.println("Dang nhap that bai..."); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } | 984 |
0 | public void include(String href) throws ProteuException { try { if (href.toLowerCase().startsWith("http://")) { java.net.URLConnection urlConn = (new java.net.URL(href)).openConnection(); Download.sendInputStream(this, urlConn.getInputStream()); } else { requestHead.set("JCN_URL_INCLUDE", href); Url.build(this); } } catch (ProteuException pe) { throw pe; } catch (Throwable t) { logger.error("Include", t); throw new ProteuException(t.getMessage(), t); } } | public static String getTextFileFromURL(String urlName) { try { StringBuffer textFile = new StringBuffer(""); String line = null; URL url = new URL(urlName); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) textFile = textFile.append(line + "\n"); reader.close(); return textFile.toString(); } catch (Exception e) { Debug.signal(Debug.ERROR, null, "Failed to open " + urlName + ", exception " + e); return null; } } | 985 |
0 | public void importNotesFromServer() { boolean downloaded = true; try { makeBackupFile(); File f = new File(UserSettings.getInstance().getNotesFile()); FileOutputStream fos = new FileOutputStream(f); String urlString = protocol + "://" + UserSettings.getInstance().getServerAddress() + UserSettings.getInstance().getServerDir() + f.getName(); setDefaultAuthenticator(); URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); InputStream is = urlc.getInputStream(); int nextByte = is.read(); while (nextByte != -1) { fos.write(nextByte); nextByte = is.read(); } fos.close(); if (urlc.getResponseCode() != HttpURLConnection.HTTP_OK) { downloaded = false; } } catch (SSLHandshakeException e) { JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.sslcertificateerror"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); downloaded = false; } catch (Exception e) { downloaded = false; } if (downloaded) { deleteBackupFile(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("info.notesfiledownloaded"), I18N.getInstance().getString("info.title"), JOptionPane.INFORMATION_MESSAGE); } else { restoreFileFromBackup(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.notesfilenotdownloaded"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); } } | public RecordIterator(URL fileUrl, ModelDataFile modelDataFile) throws DataFileException { this.modelDataFile = modelDataFile; InputStream urlStream = null; try { urlStream = fileUrl.openStream(); } catch (IOException e) { throw new DataFileException("Error open URL: " + fileUrl.toString(), e); } this.setupStream(urlStream, fileUrl.toString()); } | 986 |
1 | private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } } | public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } | 987 |
1 | private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } } | public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } } | 988 |
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(); } | public ArrayList<Jane16Results> callExternalService(ServiceType type, HashMap<String, String> params) throws Exception { URL url = initURL(type, params); XMLParser parser = initParser(type); InputStream in = url.openStream(); ArrayList<Jane16Results> results = new ArrayList<Jane16Results>(); byte[] buf = new byte[1024]; ArrayList<Byte> arrByte = new ArrayList<Byte>(); int len; while ((len = in.read(buf)) > 0) { for (int i = 0; i < len; i++) { arrByte.add(buf[i]); } } in.close(); byte[] data = new byte[arrByte.size()]; int i = 0; for (Byte b : arrByte) { data[i++] = b; } results = parser.parse(data); return results; } | 989 |
0 | public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { InputStream urlStream = url.openStream(); AudioFileFormat fileFormat = null; try { fileFormat = getFMT(urlStream, false); } finally { urlStream.close(); } return fileFormat; } | public static final String Digest(String credentials, String algorithm, String encoding) { try { MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); if (encoding == null) { md.update(credentials.getBytes()); } else { md.update(credentials.getBytes(encoding)); } return (HexUtils.convert(md.digest())); } catch (Exception ex) { log.error(ex); return credentials; } } | 990 |
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); } } | public byte[] evaluateResponse(byte[] responseBytes) throws SaslException { if (firstEvaluation) { firstEvaluation = false; StringBuilder challenge = new StringBuilder(100); Iterator iter = configurationManager.getRealms().values().iterator(); Realm aRealm; while (iter.hasNext()) { aRealm = (Realm) iter.next(); if (aRealm.getFullRealmName().equals("null")) continue; challenge.append("realm=\"" + aRealm.getFullRealmName() + "\""); challenge.append(","); } String nonceUUID = UUID.randomUUID().toString(); String nonce = null; try { nonce = new String(Base64.encodeBase64(MD5Digest(String.valueOf(System.nanoTime() + ":" + nonceUUID))), "US-ASCII"); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } catch (GeneralSecurityException uee) { throw new SaslException(uee.getMessage(), uee); } nonces.put(nonce, new ArrayList()); nonces.get(nonce).add(Integer.valueOf(1)); challenge.append("nonce=\"" + nonce + "\""); challenge.append(","); challenge.append("qop=\"" + configurationManager.getSaslQOP() + "\""); challenge.append(","); challenge.append("charset=\"utf-8\""); challenge.append(","); challenge.append("algorithm=\"md5-sess\""); if (configurationManager.getSaslQOP().indexOf("auth-conf") != -1) { challenge.append(","); challenge.append("cipher-opts=\"" + configurationManager.getDigestMD5Ciphers() + "\""); } try { return Base64.encodeBase64(challenge.toString().getBytes("US-ASCII")); } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage(), uee); } } else { String nonce = null; if (!Base64.isArrayByteBase64(responseBytes)) { throw new SaslException("Can not decode Base64 Content", new MalformedBase64ContentException()); } responseBytes = Base64.decodeBase64(responseBytes); List<byte[]> splittedBytes = splitByteArray(responseBytes, (byte) 0x3d); int tokenCountMinus1 = splittedBytes.size() - 1, lastCommaPos; Map rawDirectives = new HashMap(); String key = null; Map<String, String> directives; try { key = new String(splittedBytes.get(0), "US-ASCII"); for (int i = 1; i < tokenCountMinus1; i++) { key = responseTokenProcessor(splittedBytes, rawDirectives, key, i, tokenCountMinus1); } responseTokenProcessor(splittedBytes, rawDirectives, key, tokenCountMinus1, tokenCountMinus1); if (rawDirectives.containsKey("charset")) { String value = new String((byte[]) rawDirectives.get("charset"), "US-ASCII").toLowerCase(locale); if (value.equals("utf-8")) { encoding = "UTF-8"; } } if (encoding.equals("ISO-8859-1")) { decodeAllAs8859(rawDirectives); } else { decodeMixed(rawDirectives); } directives = rawDirectives; } catch (UnsupportedEncodingException uee) { throw new SaslException(uee.getMessage()); } if (!directives.containsKey("username") || !directives.containsKey("nonce") || !directives.containsKey("nc") || !directives.containsKey("cnonce") || !directives.containsKey("response")) { throw new SaslException("Digest-Response lacks at least one neccesery key-value pair"); } if (directives.get("username").indexOf('@') != -1) { throw new SaslException("digest-response username field must not include domain name", new AuthenticationException()); } if (!directives.containsKey("qop")) { directives.put("qop", QOP_AUTH); } if (!directives.containsKey("realm") || ((String) directives.get("realm")).equals("")) { directives.put("realm", "null"); } nonce = (String) directives.get("nonce"); if (!nonces.containsKey(nonce)) { throw new SaslException("Illegal nonce value"); } List<Integer> nonceListInMap = nonces.get(nonce); int nc = Integer.parseInt((String) directives.get("nc"), 16); if (nonceListInMap.get(nonceListInMap.size() - 1).equals(Integer.valueOf(nc))) { nonceListInMap.add(Integer.valueOf(++nc)); } else { throw new SaslException("Illegal nc value"); } nonceListInMap = null; if (directives.get("qop").equals(QOP_AUTH_INT)) integrity = true; else if (directives.get("qop").equals(QOP_AUTH_CONF)) privacy = true; if (privacy) { if (!directives.containsKey("cipher")) { throw new SaslException("Message confidentially required but cipher entry is missing"); } sessionCipher = directives.get("cipher").toLowerCase(locale); if ("3des,des,rc4-40,rc4,rc4-56".indexOf(sessionCipher) == -1) { throw new SaslException("Unsupported cipher for message confidentiality"); } } String realm = directives.get("realm").toLowerCase(Locale.getDefault()); String username = directives.get("username").toLowerCase(locale); if (username.indexOf('@') == -1) { if (!directives.get("realm").equals("null")) { username += directives.get("realm").substring(directives.get("realm").indexOf('@')); } else if (directives.get("authzid").indexOf('@') != -1) { username += directives.get("authzid").substring(directives.get("authzid").indexOf('@')); } } DomainWithPassword domainWithPassword = configurationManager.getRealmPassword(realm, username); if (domainWithPassword == null || domainWithPassword.getPassword() == null) { log.warn("The supplied username and/or realm do(es) not match a registered entry"); return null; } if (realm.equals("null") && username.indexOf('@') == -1) { username += "@" + domainWithPassword.getDomain(); } byte[] HA1 = toByteArray(domainWithPassword.getPassword()); for (int i = domainWithPassword.getPassword().length - 1; i >= 0; i--) { domainWithPassword.getPassword()[i] = 0xff; } domainWithPassword = null; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (GeneralSecurityException gse) { throw new SaslException(gse.getMessage()); } md.update(HA1); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); if (directives.containsKey("authzid")) { md.update(":".getBytes()); md.update((directives.get("authzid")).getBytes()); } MD5DigestSessionKey = HA1 = md.digest(); String MD5DigestSessionKeyToHex = toHex(HA1, HA1.length); md.update("AUTHENTICATE".getBytes()); md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } byte[] HA2 = md.digest(); String HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); byte[] responseHash = md.digest(); String HexResponseHash = toHex(responseHash, responseHash.length); if (HexResponseHash.equals(directives.get("response"))) { md.update(":".getBytes()); md.update((directives.get("digest-uri")).getBytes()); if (!directives.get("qop").equals(QOP_AUTH)) { md.update(":".getBytes()); md.update("00000000000000000000000000000000".getBytes()); } HA2 = md.digest(); HA2HEX = toHex(HA2, HA2.length); md.update(MD5DigestSessionKeyToHex.getBytes()); md.update(":".getBytes()); md.update((directives.get("nonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("nc")).getBytes()); md.update(":".getBytes()); md.update((directives.get("cnonce")).getBytes()); md.update(":".getBytes()); md.update((directives.get("qop")).getBytes()); md.update(":".getBytes()); md.update(HA2HEX.getBytes()); responseHash = md.digest(); return finalizeAuthentication.finalize(responseHash, username); } else { log.warn("Improper credentials"); return null; } } } | 991 |
0 | public String getResponse(URL url) throws OAuthException { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (IOException e) { throw new OAuthException("Error getting HTTP response", e); } } | 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(); } | 992 |
1 | public GetMyDocuments() { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMyDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "mydocuments.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "mydocuments.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("document"); int num = nodelist.getLength(); myDocsData = new String[num][4]; myDocsToolTip = new String[num]; myDocumentImageName = new String[num]; myDocIds = new int[num]; for (int i = 0; i < num; i++) { myDocsData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "filename")); myDocsData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "project")); myDocsData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "deadline")); myDocsData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "workingfolder")); myDocsToolTip[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "title")); myDocumentImageName[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "imagename")); myDocIds[i] = (new Integer(new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")))).intValue(); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException ex) { } catch (Exception ex) { System.out.println(ex); } } | public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); } | 993 |
0 | public static String calculateSHA1(String data, String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { data += key; MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(data.getBytes("iso-8859-1"), 0, data.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } | public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; } | 994 |
0 | public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } } | private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); } | 995 |
1 | @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; } | public static PortalConfig install(File xml, File dir) throws IOException, ConfigurationException { if (!dir.exists()) { log.info("Creating directory {}", dir); dir.mkdirs(); } if (!xml.exists()) { log.info("Installing default configuration to {}", xml); OutputStream output = new FileOutputStream(xml); try { InputStream input = ResourceLoader.open("res://" + PORTAL_CONFIG_XML); try { IOUtils.copy(input, output); } finally { input.close(); } } finally { output.close(); } } return create(xml, dir); } | 996 |
0 | private void createTab2(TabLayoutPanel tab) { ScrollingGraphicalViewer viewer; try { viewer = new ScrollingGraphicalViewer(); viewer.createControl(); ScalableFreeformRootEditPart root = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(root); viewer.setEditDomain(new EditDomain()); viewer.setEditPartFactory(new org.drawx.gef.sample.client.tool.example.editparts.MyEditPartFactory()); CanvasModel model = new CanvasModel(); for (int i = 0; i < 1; i++) { MyConnectionModel conn = new MyConnectionModel(); OrangeModel m1 = new OrangeModel(new Point(30, 230)); OrangeModel m2 = new OrangeModel(new Point(0, 0)); model.addChild(m1); model.addChild(m2); m1.addSourceConnection(conn); m2.addTargetConnection(conn); viewer.setContents(model); } DiagramEditor p = new DiagramEditor(viewer); viewer.setContextMenu(new MyContextMenuProvider(viewer, p.getActionRegistry())); VerticalPanel panel = new VerticalPanel(); addToolbox(viewer.getEditDomain(), viewer, panel); panel.add(viewer.getControl().getWidget()); tab.add(panel, "Fixed Size Canvas(+Overview)"); addOverview(viewer, panel); viewer.getControl().setSize(400, 300); } catch (Throwable e) { e.printStackTrace(); } } | public void performSearch(int searchStartIndex) { int index = 0; String searchString = keywords.getText(); searchButton.setEnabled(false); if (!searchString.equals("")) { try { url = new URL(searchURL + "&num=" + maxReturns.getSelectedItem().toString() + "&start=" + searchStartIndex + "&q=" + searchString); System.out.println("Google search = " + url); InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } String googleResultsFile = VueUtil.getDefaultUserFolder().getAbsolutePath() + File.separatorChar + VueResources.getString("save.google.results"); FileWriter fileWriter = new FileWriter(googleResultsFile); fileWriter.write(result); fileWriter.close(); result = ""; GSP gsp = loadGSP(googleResultsFile); Iterator i = gsp.getRES().getResultList().iterator(); Vector resultVector = new Vector(); while (i.hasNext()) { Result r = (Result) i.next(); URLResource urlResource = new URLResource(r.getUrl()); if (r.getTitle() != null) urlResource.setTitle(r.getTitle().replaceAll("</*[a-zA-Z]>", "")); else urlResource.setTitle(r.getUrl().toString()); resultVector.add(urlResource); System.out.println(r.getTitle() + " " + r.getUrl()); } VueDragTree tree = new VueDragTree(resultVector.iterator(), "GoogleSearchResults"); tree.setEditable(true); tree.setRootVisible(false); googleResultsPanel.remove(jsp); jsp = new JScrollPane(tree); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 0)); bottomPanel.add(prevButton); bottomPanel.add(nextButton); googleResultsPanel.add(bottomPanel, BorderLayout.SOUTH); googleResultsPanel.add(jsp, BorderLayout.CENTER); googleResultsPanel.validate(); googlePane.setSelectedComponent(googleResultsPanel); } catch (Exception ex) { System.out.println("cannot connect google"); googleResultsPanel.remove(jsp); JPanel jp = new JPanel(new BorderLayout()); jp.setBackground(Color.WHITE); JLabel jl = new JLabel("No Match Found"); jp.add(jl, BorderLayout.NORTH); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 0)); googleResultsPanel.add(jp, BorderLayout.CENTER); googleResultsPanel.validate(); googlePane.setSelectedComponent(googleResultsPanel); } } searchButton.setEnabled(true); } | 997 |
1 | public void salva(UploadedFile imagem, Usuario usuario) { File destino = new File(pastaImagens, usuario.getId() + ".imagem"); try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (IOException e) { throw new RuntimeException("Erro ao copiar imagem", e); } } | public void extractProfile(String parentDir, String fileName, String profileName) { try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; if (createProfileDirectory(profileName, parentDir)) { debug("the profile directory created .starting the profile extraction"); String profilePath = parentDir + File.separator + fileName; zipinputstream = new ZipInputStream(new FileInputStream(profilePath)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(parentDir + File.separator + profileName + File.separator + newFile.getName()); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); debug("deleting the profile.zip file"); File newFile = new File(profilePath); if (newFile.delete()) { debug("the " + "[" + profilePath + "]" + " deleted successfully"); } else { debug("profile" + "[" + profilePath + "]" + "deletion fail"); throw new IllegalArgumentException("Error: deletion error!"); } } else { debug("error creating the profile directory"); } } catch (Exception e) { e.printStackTrace(); } } | 998 |
0 | public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } | public static boolean checkEncode(String origin, byte[] mDigest, String algorithm) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(origin.getBytes()); if (MessageDigest.isEqual(mDigest, md.digest())) { return true; } else { return false; } } | 999 |