label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public ActionResponse executeAction(ActionRequest request) throws Exception { BufferedReader in = null; try { CurrencyEntityManager em = new CurrencyEntityManager(); String id = (String) request.getProperty("ID"); CurrencyMonitor cm = getCurrencyMonitor(em, Long.valueOf(id)); String code = cm.getCode(); if (code == null || code.length() == 0) code = DEFAULT_SYMBOL; String tmp = URL.replace("@", code); ActionResponse resp = new ActionResponse(); URL url = new URL(tmp); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int status = conn.getResponseCode(); if (status == 200) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder value = new StringBuilder(); while (true) { String line = in.readLine(); if (line == null) break; value.append(line); } cm.setLastUpdateValue(new BigDecimal(value.toString())); cm.setLastUpdateTs(new Date()); em.updateCurrencyMonitor(cm); resp.addResult("CURRENCYMONITOR", cm); } else { resp.setErrorCode(ActionResponse.GENERAL_ERROR); resp.setErrorMessage("HTTP Error [" + status + "]"); } return resp; } catch (Exception e) { String st = MiscUtils.stackTrace2String(e); logger.error(st); throw e; } finally { if (in != null) { in.close(); } } } Code Sample 2: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
11
Code Sample 1: public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } } Code Sample 2: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { LOG.debug("copying file"); String tTempFileName = this.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tTempFileName)); Datastream tDatastream = new LocalDatastream(this.getGenericFileName(pDeposit), this.getContentType(), tTempFileName); List<Datastream> tDatastreams = new ArrayList<Datastream>(); tDatastreams.add(tDatastream); return tDatastreams; }
11
Code Sample 1: public void sendFile(File file, String filename, String contentType) throws SearchLibException { response.setContentType(contentType); response.addHeader("Content-Disposition", "attachment; filename=" + filename); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ServletOutputStream outputStream = getOutputStream(); IOUtils.copy(inputStream, outputStream); outputStream.close(); } catch (FileNotFoundException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } finally { if (inputStream != null) IOUtils.closeQuietly(inputStream); } } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
00
Code Sample 1: public RawCandidate getRawCandidate(long candId) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/" + Long.toHexString(candId)); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof RawCandidate) { RawCandidate p = (RawCandidate) xmlable; return p; } else { throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for candId"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } Code Sample 2: @Override public void backup() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); Date date = new Date(); date.setTime(TimeUtil.addHours(date, -getHours()).getTimeInMillis()); date.setTime(TimeUtil.getTodayAtMidnight().getTimeInMillis()); if (logger.isInfoEnabled()) logger.info("backuping records before: " + date); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + getOrigin() + " where " + getCondition() + ""); java.sql.Date sqlDate = new java.sql.Date(date.getTime()); prestm.setDate(1, sqlDate); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (currentRows > 0) { connection.setAutoCommit(false); prestm = connection.prepareStatement("INSERT INTO " + getDestination() + " SELECT * FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(rows + " rows backupped"); prestm = connection.prepareStatement("DELETE FROM " + getOrigin() + " WHERE " + getCondition()); prestm.setDate(1, sqlDate); rows = prestm.executeUpdate(); prestm.close(); connection.commit(); if (logger.isInfoEnabled()) logger.info(rows + " rows deleted"); } else if (logger.isInfoEnabled()) logger.info("no backup need"); if (logger.isInfoEnabled()) logger.info("backup table " + getOrigin() + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante il backup dei dati della tabella " + getOrigin(), e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
00
Code Sample 1: protected PTask commit_result(Result r, SyrupConnection con) throws Exception { try { int logAction = LogEntry.ENDED; String kk = r.context().task().key(); if (r.in_1_consumed() && r.context().in_1_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, false, null, con); logAction = logAction | LogEntry.IN_1; } if (r.in_2_consumed() && r.context().in_2_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, true, null, con); logAction = logAction | LogEntry.IN_2; } if (r.out_1_result() != null && r.context().out_1_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, false, r.out_1_result(), con); logAction = logAction | LogEntry.OUT_1; } if (r.out_2_result() != null && r.context().out_2_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, true, r.out_2_result(), con); logAction = logAction | LogEntry.OUT_2; } sqlImpl().loggingFunctions().log(r.context().task().key(), logAction, con); boolean isParent = r.context().task().isParent(); if (r instanceof Workflow) { Workflow w = (Workflow) r; Task[] tt = w.tasks(); Link[] ll = w.links(); Hashtable tkeyMap = new Hashtable(); for (int i = 0; i < tt.length; i++) { String key = sqlImpl().creationFunctions().newTask(tt[i], r.context().task(), con); tkeyMap.put(tt[i], key); } for (int j = 0; j < ll.length; j++) { sqlImpl().creationFunctions().newLink(ll[j], tkeyMap, con); } String in_link_1 = sqlImpl().queryFunctions().readInTask(kk, false, con); String in_link_2 = sqlImpl().queryFunctions().readInTask(kk, true, con); String out_link_1 = sqlImpl().queryFunctions().readOutTask(kk, false, con); String out_link_2 = sqlImpl().queryFunctions().readOutTask(kk, true, con); sqlImpl().updateFunctions().rewireInLink(kk, false, w.in_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireInLink(kk, true, w.in_2_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, false, w.out_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, true, w.out_2_binding(), tkeyMap, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateDone(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateDone(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_2, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_2, con); isParent = true; } sqlImpl().updateFunctions().checkAndUpdateDone(kk, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kk, con); PreparedStatement s3 = null; s3 = con.prepareStatementFromCache(sqlImpl().sqlStatements().updateTaskModificationStatement()); java.util.Date dd = new java.util.Date(); s3.setLong(1, dd.getTime()); s3.setBoolean(2, isParent); s3.setString(3, r.context().task().key()); s3.executeUpdate(); sqlImpl().loggingFunctions().log(kk, LogEntry.ENDED, con); con.commit(); return sqlImpl().queryFunctions().readPTask(kk, con); } finally { con.rollback(); } } Code Sample 2: 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!"); }
00
Code Sample 1: public static XMLShowInfo NzbSearch(TVRageShowInfo tvrage, XMLShowInfo xmldata, int latestOrNext) { String newzbin_query = "", csvData = "", hellaQueueDir = "", newzbinUsr = "", newzbinPass = ""; String[] tmp; DateFormat tvRageDateFormat = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat tvRageDateFormatFix = new SimpleDateFormat("yyyy-MM-dd"); newzbin_query = "?q=" + xmldata.showName + "+"; if (latestOrNext == 0) { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.latestSeasonNum + "x" + tvrage.latestEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.latestSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.latestAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.latestTitle; } else { if (xmldata.searchBy.equals("ShowName Season x Episode")) newzbin_query += tvrage.nextSeasonNum + "x" + tvrage.nextEpisodeNum; else if (xmldata.searchBy.equals("Showname SeriesNum")) newzbin_query += tvrage.nextSeriesNum; else if (xmldata.searchBy.equals("Showname YYYY-MM-DD")) { try { Date airTime = tvRageDateFormat.parse(tvrage.nextAirDate); newzbin_query += tvRageDateFormatFix.format(airTime); } catch (ParseException e) { e.printStackTrace(); } } else if (xmldata.searchBy.equals("Showname EpisodeTitle")) newzbin_query += tvrage.nextTitle; } newzbin_query += "&searchaction=Search"; newzbin_query += "&fpn=p"; newzbin_query += "&category=8category=11"; newzbin_query += "&area=-1"; newzbin_query += "&u_nfo_posts_only=0"; newzbin_query += "&u_url_posts_only=0"; newzbin_query += "&u_comment_posts_only=0"; newzbin_query += "&u_v3_retention=1209600"; newzbin_query += "&ps_rb_language=" + xmldata.language; newzbin_query += "&sort=ps_edit_date"; newzbin_query += "&order=desc"; newzbin_query += "&areadone=-1"; newzbin_query += "&feed=csv"; newzbin_query += "&ps_rb_video_format=" + xmldata.format; newzbin_query = newzbin_query.replaceAll(" ", "%20"); System.out.println("http://v3.newzbin.com/search/" + newzbin_query); try { URL url = new URL("http://v3.newzbin.com/search/" + newzbin_query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); csvData = in.readLine(); if (csvData != null) { JavaNZB.searchCount++; if (searchCount == 6) { searchCount = 0; System.out.println("Sleeping for 60 seconds"); try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } } tmp = csvData.split(","); tmp[2] = tmp[2].substring(1, tmp[2].length() - 1); tmp[3] = tmp[3].substring(1, tmp[3].length() - 1); Pattern p = Pattern.compile("[\\\\</:>?\\[|\\]\"]"); Matcher matcher = p.matcher(tmp[3]); tmp[3] = matcher.replaceAll(" "); tmp[3] = tmp[3].replaceAll("&", "and"); URLConnection urlConn; DataOutputStream printout; url = new URL("http://v3.newzbin.com/api/dnzb/"); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "username=" + JavaNZB.newzbinUsr + "&password=" + JavaNZB.newzbinPass + "&reportid=" + tmp[2]; printout.writeBytes(content); printout.flush(); printout.close(); BufferedReader nzbInput = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String format = ""; if (xmldata.format.equals("17")) format = " Xvid"; if (xmldata.format.equals("131072")) format = " x264"; if (xmldata.format.equals("2")) format = " DVD"; if (xmldata.format.equals("4")) format = " SVCD"; if (xmldata.format.equals("8")) format = " VCD"; if (xmldata.format.equals("32")) format = " HDts"; if (xmldata.format.equals("64")) format = " WMV"; if (xmldata.format.equals("128")) format = " Other"; if (xmldata.format.equals("256")) format = " ratDVD"; if (xmldata.format.equals("512")) format = " iPod"; if (xmldata.format.equals("1024")) format = " PSP"; File f = new File(JavaNZB.hellaQueueDir, tmp[3] + format + ".nzb"); BufferedWriter out = new BufferedWriter(new FileWriter(f)); String str; System.out.println("--Downloading " + tmp[3] + format + ".nzb" + " to queue directory--"); while (null != ((str = nzbInput.readLine()))) out.write(str); nzbInput.close(); out.close(); if (latestOrNext == 0) { xmldata.episode = tvrage.latestEpisodeNum; xmldata.season = tvrage.latestSeasonNum; } else { xmldata.episode = tvrage.nextEpisodeNum; xmldata.season = tvrage.nextSeasonNum; } } else System.out.println("No new episode posted"); System.out.println(); } catch (MalformedURLException e) { } catch (IOException e) { System.out.println("IO Exception from NzbSearch"); } return xmldata; } Code Sample 2: @Override public File fetchHSMFile(String fsID, String filePath) throws HSMException { log.debug("fetchHSMFile called with fsID=" + fsID + ", filePath=" + filePath); if (absIncomingDir.mkdirs()) { log.info("M-WRITE " + absIncomingDir); } File tarFile; try { tarFile = File.createTempFile("hsm_", ".tar", absIncomingDir); } catch (IOException x) { throw new HSMException("Failed to create temp file in " + absIncomingDir, x); } log.info("Fetching " + filePath + " from cloud storage"); FileOutputStream fos = null; try { if (s3 == null) createClient(); S3Object object = s3.getObject(new GetObjectRequest(bucketName, filePath)); fos = new FileOutputStream(tarFile); IOUtils.copy(object.getObjectContent(), fos); } catch (AmazonClientException ace) { s3 = null; throw new HSMException("Could not list objects for: " + filePath, ace); } catch (Exception x) { throw new HSMException("Failed to retrieve " + filePath, x); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { log.error("Couldn't close output stream for: " + tarFile); } } } return tarFile; }
00
Code Sample 1: @Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException { if (localFile.isFile()) { long localContentLength = localFile.length(); long localLastModified = localFile.lastModified() / 1000; long contentLength = -1; long lastModified = -1; HttpClient httpclient = createHttpClient(creds); try { HttpHead httphead = new HttpHead(url); HttpResponse response = httpclient.execute(httphead); if (response != null) { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode() / 100; if (status == 2) { Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader.getValue()); } if (lastModifiedHeader != null) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US)); try { lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000; } catch (ParseException e) { logger.error(e); } } } else { return true; } } } finally { httpclient.getConnectionManager().shutdown(); } if (logger.isDebugEnabled()) { logger.debug("local:" + localContentLength + " " + localLastModified); logger.debug("remote:" + contentLength + " " + lastModified); } if (contentLength != -1 && localContentLength != contentLength) return false; if (lastModified != -1 && lastModified != localLastModified) return false; if (contentLength == -1 && lastModified == -1) return false; return true; } return false; }
00
Code Sample 1: private void generate(String salt) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("No MD5", e); } long time = System.currentTimeMillis(); long rand = random.nextLong(); sbValueBeforeMD5.append(systemId); sbValueBeforeMD5.append(salt); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(Long.toString(rand)); md5.update(sbValueBeforeMD5.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); int position = 0; for (int j = 0; j < array.length; ++j) { if (position == 4 || position == 6 || position == 8 || position == 10) { sb.append('-'); } position++; int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b).toUpperCase()); } guidString = sb.toString().toUpperCase(); } Code Sample 2: private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) { LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; final long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } } Code Sample 2: public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException { if ((null == srcFile) || (null == dstFile)) return (-1L); final File dstFolder = dstFile.getParentFile(); if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)"); FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(srcFile).getChannel(); dstChannel = new FileOutputStream(dstFile).getChannel(); final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize); if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L); return copyLen; } finally { FileUtil.closeAll(srcChannel, dstChannel); } }
00
Code Sample 1: public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } } Code Sample 2: public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
00
Code Sample 1: @Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { tmpFile = File.createTempFile("ftp", "dat", new File("./tmp")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); IOUtils.copy(is, bos); bos.flush(); bos.close(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } } Code Sample 2: @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnRegister) { Error.log(6002, "Bot�o cadastrar pressionado por " + login + "."); if (nameUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo nome requerido"); nameUser.setFocusable(true); return; } if (loginUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo login requerido"); loginUser.setFocusable(true); return; } String group = ""; if (groupUser.getSelectedIndex() == 0) group = "admin"; else if (groupUser.getSelectedIndex() == 1) group = "user"; else { JOptionPane.showMessageDialog(null, "Campo grupo n�o selecionado"); return; } if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int i = 1; for (i = 1; i < password1.length(); i++) { if (passwordUser1.getPassword()[i] != c) { break; } c = passwordUser1.getPassword()[i]; } if (i == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } ResultSet rs; Statement stmt; String sql; String result = ""; sql = "select login from Usuarios where login='" + loginUser.getText() + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("login"); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (result.compareTo("") != 0) { JOptionPane.showMessageDialog(null, "Login " + result + " j� existe"); loginUser.setText(""); loginUser.setFocusable(true); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } sql = "insert into Usuarios (login,password,tries_personal,tries_one_use," + "grupo,description) values " + "('" + loginUser.getText() + "','" + outputDigest + "',0,0,'" + group + "','" + nameUser.getText() + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(loginUser.getText() + ".txt", false)); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + loginUser.getText() + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + loginUser.getText() + " foi cadastrado com sucesso."); dispose(); } if (e.getSource() == btnCancel) { Error.log(6003, "Bot�o voltar de cadastrar para o menu principal pressionado por " + login + "."); dispose(); } }
00
Code Sample 1: public void run() { StringBuffer messageStringBuffer = new StringBuffer(); messageStringBuffer.append("Program: \t" + UpdateChannel.getCurrentChannel().getApplicationTitle() + "\n"); messageStringBuffer.append("Version: \t" + Lister.version + "\n"); messageStringBuffer.append("Revision: \t" + Lister.revision + "\n"); messageStringBuffer.append("Channel: \t" + UpdateChannel.getCurrentChannel().getName() + "\n"); messageStringBuffer.append("Date: \t\t" + Lister.date + "\n\n"); messageStringBuffer.append("OS: \t\t" + System.getProperty("os.name") + " (" + System.getProperty("os.version") + ")\n"); messageStringBuffer.append("JAVA: \t\t" + System.getProperty("java.version") + " (" + System.getProperty("java.specification.vendor") + ")\n"); messageStringBuffer.append("Desktop: \t" + System.getProperty("sun.desktop") + "\n"); messageStringBuffer.append("Language: \t" + Language.getCurrentInstance() + "\n\n"); messageStringBuffer.append("------------------------------------------\n"); if (summary != null) { messageStringBuffer.append(summary + "\n\n"); } messageStringBuffer.append("Details:\n"); if (description != null) { messageStringBuffer.append(description); } if (exception != null) { messageStringBuffer.append("\n\nStacktrace:\n"); printStackTrace(exception, messageStringBuffer); } try { if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), false); } URL url = UpdateChannel.getCurrentChannel().getErrorReportURL(); URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); if (sender != null) { outputStreamWriter.write(URLEncoder.encode("sender", "UTF-8") + "=" + URLEncoder.encode(sender, "UTF-8")); outputStreamWriter.write("&"); } outputStreamWriter.write(URLEncoder.encode("report", "UTF-8") + "=" + URLEncoder.encode(messageStringBuffer.toString(), "UTF-8")); if (attachErrorLog) { outputStreamWriter.write("&"); outputStreamWriter.write(URLEncoder.encode("error.log", "UTF-8") + "=" + URLEncoder.encode(Logger.getErrorLogContent(), "UTF-8")); } outputStreamWriter.flush(); urlConnection.getInputStream().close(); outputStreamWriter.close(); if (dialog != null) { dialog.dispose(); } JOptionPane.showMessageDialog(Lister.getCurrentInstance(), Language.translateStatic("MESSAGE_ERRORREPORTSENT")); } catch (Exception exception) { ErrorJDialog.showErrorDialog(dialog, exception); if (dialog != null) { setComponentsEnabled(dialog.getContentPane(), true); } } } Code Sample 2: @Override protected ResourceHandler doGet(final URI resourceUri) throws ResourceException { if (resourceUri.getHost() == null) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.ftp.illegal", resourceUri.toString())); } try { final URL configUrl = resourceUri.toURL(); final URLConnection urlConnection; Proxy httpProxy = null; if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxySet))) { if (context.getBoolean(FileStoreContextBuilder.ProxySet)) { final String proxyHost = context.getString(FileStoreContextBuilder.ProxyHost); final String proxyPort = context.getString(FileStoreContextBuilder.ProxyPort); if (!StringHelper.isEmpty(proxyHost)) { httpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, !StringHelper.isEmpty(proxyPort) ? Integer.parseInt(proxyPort) : 80)); if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.NonProxyHosts))) { System.getProperties().put("ftp.nonProxyHosts", context.getProperty(FileStoreContextBuilder.NonProxyHosts)); } if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyUser)) && !StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyPassword))) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(context.getString(FileStoreContextBuilder.ProxyUser), context.getString(FileStoreContextBuilder.ProxyPassword).toCharArray()); } }); } } } } if (httpProxy == null) { urlConnection = configUrl.openConnection(); } else { urlConnection = configUrl.openConnection(httpProxy); } setUrlConnectionSettings(urlConnection); urlConnection.connect(); try { return createResourceHandler(resourceUri.toString(), urlConnection.getInputStream()); } catch (final FileNotFoundException fnfe) { throw new ResourceNotFoundException(resourceUri.toString()); } } catch (final MalformedURLException mure) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.malformed", resourceUri.toString())); } catch (final ConnectException ce) { throw new ResourceException("store.connection.error", ce, resourceUri.toString()); } catch (final IOException ioe) { if (ioe instanceof ResourceException) { throw (ResourceException) ioe; } else { throw new ResourceException(ioe, resourceUri.toString()); } } }
00
Code Sample 1: public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName); Iterator<LDAPModification> it = mods.iterator(); String sql = "UPDATE " + this.tableName + " SET "; while (it.hasNext()) { LDAPModification mod = it.next(); if (mod.getOp() != LDAPModification.REPLACE) { throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, ""); } sql += ldap2db.get(mod.getAttribute().getName()) + "=? "; } sql += " WHERE " + this.rdnField + "=?"; PreparedStatement ps = con.prepareStatement(sql); it = mods.iterator(); int i = 1; while (it.hasNext()) { LDAPModification mod = it.next(); ps.setString(i, mod.getAttribute().getStringValue()); i++; } String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); ps.setString(i, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
00
Code Sample 1: public static void bubbleSort(String[] a) { Collator myCollator = Collator.getInstance(); boolean switched = true; for (int pass = 0; pass < a.length - 1 && switched; pass++) { switched = false; for (int i = 0; i < a.length - pass - 1; i++) { if (myCollator.compare(a[i], a[i + 1]) > 0) { switched = true; String temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } } } Code Sample 2: public void setUrl(URL url) throws PDFException, PDFSecurityException, IOException { InputStream in = null; try { URLConnection urlConnection = url.openConnection(); in = urlConnection.getInputStream(); String pathOrURL = url.toString(); setInputStream(in, pathOrURL); } finally { if (in != null) { in.close(); } } }
11
Code Sample 1: private void download(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } } Code Sample 2: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } }
00
Code Sample 1: public static JsonNode getJSONFromURL(String httpUrl) throws Exception { URL url; InputStream inputStream = null; DataInputStream dataInputStream; try { url = new URL(httpUrl); inputStream = url.openStream(); dataInputStream = new DataInputStream(new BufferedInputStream(inputStream)); return JsonUtil.getNode(dataInputStream); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ioe) { } } } Code Sample 2: private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new ScalableRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getEditorInput().getAdapter(ScannedMap.class)); return viewer; }
11
Code Sample 1: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } } Code Sample 2: protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; }
11
Code Sample 1: @Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } Code Sample 2: public void execute() { File sourceFile = new File(oarfilePath); File destinationFile = new File(deploymentDirectory + File.separator + sourceFile.getName()); try { FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); byte[] readArray = new byte[2048]; while (fis.read(readArray) != -1) { fos.write(readArray); } fis.close(); fos.flush(); fos.close(); } catch (IOException ioe) { logger.severe("failed to copy the file:" + ioe); } }
00
Code Sample 1: public QueryResult doSearch(String searchTerm, Integer searchInReceivedItems, Integer searchInSentItems, Integer searchInSupervisedItems, Integer startRow, Integer resultCount, Boolean searchArchived, Boolean searchInItemsNeededAttentionOnly) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); QueryResult queryResult = new QueryResult(); SearchRequest request = new SearchRequest(); SearchItemsQuery query = new SearchItemsQuery(); query.setArchiveIncluded(searchArchived); log(INFO, "searchTerm=" + searchTerm); log(INFO, "search in received=" + searchInReceivedItems); log(INFO, "search in sent=" + searchInSentItems); log(INFO, "search in supervised=" + searchInSupervisedItems); List<String> filters = new ArrayList<String>(); if (searchInItemsNeededAttentionOnly == false) { if (searchInReceivedItems != null) { filters.add("ALL_RECEIVED_ITEMS"); } if (searchInSentItems != null) { filters.add("ALL_SENT_ITEMS"); } if (searchInSupervisedItems != null) { filters.add("ALL_SUPERVISED_ITEMS"); } } else { if (searchInReceivedItems != null) { filters.add("RECEIVED_ITEMS_NEEDED_ATTENTION"); } if (searchInSentItems != null) { filters.add("SENT_ITEMS_NEEDED_ATTENTION"); } } query.setFilters(filters); query.setId("1234"); query.setOwner(sessionId); query.setReferenceOnly(false); query.setSearchTerm(searchTerm); query.setUseOR(false); request.setStartRow(startRow); request.setResultCount(resultCount); request.setQuery(query); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("SearchRequest", SearchRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("SearchResponse", SearchResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/search?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); SearchResponse searchResponse = (SearchResponse) reader.fromXML(result); List<Item> items = searchResponse.getItems(); queryResult.setItems(items); queryResult.setTotal(searchResponse.getTotalResultCount()); queryResult.setStartRow(searchResponse.getStartRow()); } return queryResult; } Code Sample 2: private String loadSchemas() { StringWriter writer = new StringWriter(); try { IOUtils.copy(CoreOdfValidator.class.getResourceAsStream("schema_list.properties"), writer); } catch (IOException e) { e.printStackTrace(); } return writer.toString(); }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } } Code Sample 2: public static void copyFile(String fromPath, String toPath) { try { File inputFile = new File(fromPath); String dirImg = (new File(toPath)).getParent(); File tmp = new File(dirImg); if (!tmp.exists()) { tmp.mkdir(); } File outputFile = new File(toPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); } }
00
Code Sample 1: private void doProcess(HttpServletRequest request, HttpServletResponse resp) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Analyzer analyzer = new Analyzer(); ServletContext context = getServletContext(); String xml = context.getRealPath("data\\log.xml"); String xsd = context.getRealPath("data\\log.xsd"); String grs = context.getRealPath("reports\\" + request.getParameter("type") + ".grs"); String pdf = context.getRealPath("html\\report.pdf"); System.out.println("omg: " + request.getParameter("type")); System.out.println("omg: " + request.getParameter("pc")); int pcount = Integer.parseInt(request.getParameter("pc")); String[] params = new String[pcount]; for (int i = 0; i < pcount; i++) { params[i] = request.getParameter("p" + i); } try { analyzer.generateReport(xml, xsd, grs, pdf, params); } catch (Exception e) { e.printStackTrace(); } File file = new File(pdf); byte[] bs = tryLoadFile(pdf); if (bs == null) throw new NullPointerException(); resp.setHeader("Content-Disposition", " filename=\"" + file.getName() + "\";"); resp.setContentLength(bs.length); InputStream is = new ByteArrayInputStream(bs); IOUtils.copy(is, resp.getOutputStream()); } Code Sample 2: public Vector decode(final URL url) throws IOException { LineNumberReader reader; if (owner != null) { reader = new LineNumberReader(new InputStreamReader(new ProgressMonitorInputStream(owner, "Loading " + url, url.openStream()))); } else { reader = new LineNumberReader(new InputStreamReader(url.openStream())); } Vector v = new Vector(); String line; Vector events; try { while ((line = reader.readLine()) != null) { StringBuffer buffer = new StringBuffer(line); for (int i = 0; i < 1000; i++) { buffer.append(reader.readLine()).append("\n"); } events = decodeEvents(buffer.toString()); if (events != null) { v.addAll(events); } } } finally { partialEvent = null; try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } return v; }
11
Code Sample 1: public static void copyCompletely(InputStream input, OutputStream output) throws IOException { if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) { try { FileChannel target = ((FileOutputStream) output).getChannel(); FileChannel source = ((FileInputStream) input).getChannel(); source.transferTo(0, Integer.MAX_VALUE, target); source.close(); target.close(); return; } catch (Exception e) { } } byte[] buf = new byte[8192]; while (true) { int length = input.read(buf); if (length < 0) break; output.write(buf, 0, length); } try { input.close(); } catch (IOException ignore) { } try { output.close(); } catch (IOException ignore) { } } Code Sample 2: public void verRecordatorio() { try { cantidadArchivos = obtenerCantidad() + 1; boolean existe = false; String filenametxt = ""; String filenamezip = ""; String hora = ""; String lugar = ""; String actividad = ""; String linea = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (dia == Integer.parseInt(identificarDato(datoSeleccionado))) { existe = true; hora = input.readLine(); lugar = input.readLine(); while ((linea = input.readLine()) != null) actividad += linea + "\n"; verRecordatorioInterfaz(hora, lugar, actividad); hora = ""; lugar = ""; actividad = ""; } input.close(); } if (!existe) JOptionPane.showMessageDialog(null, "No existe un recordatorio guardado\n" + "para el " + identificarDato(datoSeleccionado) + " de " + meses[mesTemporal].toLowerCase() + " del a�o " + anoTemporal, "No existe", JOptionPane.INFORMATION_MESSAGE); table.clearSelection(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: protected static String readAFewChars(URL url) throws IOException { StringBuffer buf = new StringBuffer(10); Reader reader = new InputStreamReader(url.openStream()); for (int i = 0; i < 10; i++) { int c = reader.read(); if (c == -1) { break; } buf.append((char) c); } reader.close(); return buf.toString(); } Code Sample 2: private boolean cacheUrlFile(String filePath, String realUrl, boolean isOnline) { try { URL url = new URL(realUrl); String encoding = "gbk"; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), encoding)); StringBuilder sb = new StringBuilder(); sb.append(configCenter.getWebRoot()).append(getCacheString(isOnline)).append(filePath); fileEditor.createDirectory(sb.toString()); return fileEditor.saveFile(sb.toString(), in); } catch (IOException e) { } return false; }
11
Code Sample 1: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; } Code Sample 2: 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(); } }
00
Code Sample 1: public static void request() { try { URL url = new URL("http://www.nseindia.com/marketinfo/companyinfo/companysearch.jsp?cons=ghcl&section=7"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); try { URL url = new URL("http://placekitten.com/g/500/250"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setConnectTimeout(3000); conn.setReadTimeout(5000); Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream()); conn.disconnect(); Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500); Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888); output.eraseColor(Color.BLACK); Canvas canvas = new Canvas(output); canvas.drawBitmap(kitten, 125, 125, new Paint()); canvas.drawBitmap(frame, 0, 0, new Paint()); Paint textPaint = new Paint(); textPaint.setColor(Color.WHITE); textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); textPaint.setTextAlign(Align.CENTER); textPaint.setAntiAlias(true); textPaint.setTextSize(36); canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint); textPaint.setTextSize(24); canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint); ImageView imageView = (ImageView) this.findViewById(R.id.imageView); imageView.setImageBitmap(output); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void readBooklist(String filename) { Reader input = null; try { if (filename.startsWith("http:")) { URL url = new URL(filename); URLConnection conn = url.openConnection(); input = new InputStreamReader(conn.getInputStream()); } else { String fileNameAll = filename; try { fileNameAll = new File(filename).getCanonicalPath(); } catch (IOException e) { fileNameAll = new File(filename).getAbsolutePath(); } input = new FileReader(new File(fileNameAll)); } BufferedReader reader = new BufferedReader(input); String line; Date today = new Date(); while ((line = reader.readLine()) != null) { if (shuttingDown) break; String fields[] = line.split("\\|"); Map<String, String> valuesToAdd = new LinkedHashMap<String, String>(); valuesToAdd.put("fund_code_facet", fields[11]); valuesToAdd.put("date_received_facet", fields[0]); DateFormat format = new SimpleDateFormat("yyyyMMdd"); Date dateReceived = format.parse(fields[0], new ParsePosition(0)); if (dateReceived.after(today)) continue; String docID = "u" + fields[9]; try { Map<String, Object> docMap = getDocumentMap(docID); if (docMap != null) { addNewDataToRecord(docMap, valuesToAdd); documentCache.put(docID, docMap); if (doUpdate && docMap != null && docMap.size() != 0) { update(docMap); } } } catch (SolrMarcIndexerException e) { if (e.getLevel() == SolrMarcIndexerException.IGNORE) { logger.error("Indexing routine says record " + docID + " should be ignored"); } else if (e.getLevel() == SolrMarcIndexerException.DELETE) { logger.error("Indexing routine says record " + docID + " should be deleted"); } if (e.getLevel() == SolrMarcIndexerException.EXIT) { logger.error("Indexing routine says processing should be terminated by record " + docID); break; } } } } catch (FileNotFoundException e) { logger.info(e.getMessage()); logger.error(e.getCause()); } catch (IOException e) { logger.info(e.getMessage()); logger.error(e.getCause()); } } Code Sample 2: public ArrayList<Tweet> getTimeLine() { try { HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); return null; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); SAXParserFactory spf = SAXParserFactory.newInstance(); StringReader XMLout = new StringReader(sBuf.toString()); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xmlParserLinkedin gwh = new xmlParserLinkedin(); xr.setContentHandler(gwh); xr.parse(new InputSource(XMLout)); return gwh.getParsedData(); } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (IOException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (ParserConfigurationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (SAXException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } return null; }
11
Code Sample 1: public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
00
Code Sample 1: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } } Code Sample 2: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
11
Code Sample 1: public static File copyFile(String path) { File src = new File(path); File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: 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!"); }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } Code Sample 2: 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(); } }
00
Code Sample 1: public DataSetInfo(String request) throws AddeURLException { URLConnection urlc; BufferedReader reader; debug = debug || request.indexOf("debug=true") >= 0; try { URL url = new URL(request); urlc = url.openConnection(); reader = new BufferedReader(new InputStreamReader(urlc.getInputStream())); } catch (AddeURLException ae) { status = -1; throw new AddeURLException("No datasets found"); } catch (Exception e) { status = -1; throw new AddeURLException("Error opening connection: " + e); } int numBytes = ((AddeURLConnection) urlc).getInitialRecordSize(); if (debug) System.out.println("DataSetInfo: numBytes = " + numBytes); if (numBytes == 0) { status = -1; throw new AddeURLException("No datasets found"); } else { data = new char[numBytes]; try { int start = 0; while (start < numBytes) { int numRead = reader.read(data, start, (numBytes - start)); if (debug) System.out.println("bytes read = " + numRead); start += numRead; } } catch (IOException e) { status = -1; throw new AddeURLException("Error reading dataset info:" + e); } int numNames = data.length / 80; descriptorTable = new Hashtable(numNames); if (debug) System.out.println("Number of descriptors = " + numNames); for (int i = 0; i < numNames; i++) { String temp = new String(data, i * 80, 80); if (debug) System.out.println("Parsing: >" + temp + "<"); if (temp.trim().equals("")) continue; String descriptor = temp.substring(0, 12).trim(); if (debug) System.out.println("Descriptor = " + descriptor); String comment = descriptor; int pos = temp.indexOf('"'); if (debug) System.out.println("Found quote at " + pos); if (pos >= 23) { comment = temp.substring(pos + 1).trim(); if (comment.equals("")) comment = descriptor; } if (debug) System.out.println("Comment = " + comment); descriptorTable.put(comment, descriptor); } } } Code Sample 2: public String getWebcontent(final String link, final String postdata) { final StringBuffer response = new StringBuffer(); try { DisableSSLCertificateCheckUtil.disableChecks(); final URL url = new URL(link); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postdata); wr.flush(); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; while ((content = rd.readLine()) != null) { response.append(content); response.append('\n'); } wr.close(); rd.close(); } catch (final Exception e) { LOG.error("getWebcontent(String link, String postdata): " + e.toString() + "\012" + link + "\012" + postdata); } return response.toString(); }
00
Code Sample 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(); } } Code Sample 2: public static void upper() throws Exception { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); URL url = new URL("https://test.ctpe.net/payment/query"); URLConnection conn = url.openConnection(); String data = "<Request version='1.0'> " + "<Header> " + " <Security sender='ff80808109c5bcc00109c5bce9f1003a'/> " + "</Header> " + "<Query entity='ff80808109c5bcc00109c5bce9f50056' level='CHANNEL' mode='INTEGRATOR_TEST'> " + " <User login='ff80808109c5bcc00109c5bce9f20042' pwd='geheim'/> " + " <Period from='2006-03-04' to='2006-03-04'/> " + " <Types> " + " <Type code='RF'/> " + " <Type code='PA'/> " + " <Type code='RV'/> " + " </Types> " + "</Query> " + "</Request> "; conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("load=" + data); wr.flush(); wr.close(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); }
00
Code Sample 1: @Test public void testPersistor() throws Exception { PreparedStatement ps; ps = connection.prepareStatement("delete from privatadresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from adresse"); ps.executeUpdate(); ps.close(); ps = connection.prepareStatement("delete from person"); ps.executeUpdate(); ps.close(); Persistor p; Adresse csd = new LieferAdresse(); csd.setStrasse("Amalienstrasse 68"); modificationTracker.addNewParticipant(csd); Person markus = new Person(); markus.setName("markus"); modificationTracker.addNewParticipant(markus); markus.getPrivatAdressen().add(csd); Person martin = new Person(); martin.setName("martin"); modificationTracker.addNewParticipant(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); p.persist(); Adresse bia = new LieferAdresse(); modificationTracker.addNewParticipant(bia); bia.setStrasse("dr. boehringer gasse"); markus.getAdressen().add(bia); bia.setPerson(martin); markus.setContactPerson(martin); p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker); try { p.persist(); connection.commit(); } catch (Exception e) { connection.rollback(); throw e; } } Code Sample 2: public String get(String url) { String buf = null; StringBuilder resultBuffer = new StringBuilder(512); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url); try { URL theURL = new URL(url); URLConnection urlConn = theURL.openConnection(); urlConn.setDoOutput(true); urlConn.setReadTimeout(timeOut); BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); do { buf = urlReader.readLine(); if (buf != null) { resultBuffer.append(buf); resultBuffer.append("\n"); } } while (buf != null); urlReader.close(); if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString()); int xmlNdx = resultBuffer.lastIndexOf("?>"); if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2); } catch (Exception e) { result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e); } return (result); }
00
Code Sample 1: public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } Code Sample 2: public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); }
11
Code Sample 1: private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); } Code Sample 2: private void writeGif(String filename, String outputFile) throws IOException { File file = new File(filename); InputStream in = new FileInputStream(file); FileOutputStream fout = new FileOutputStream(outputFile); int totalRead = 0; int readBytes = 0; int blockSize = 65000; long fileLen = file.length(); byte b[] = new byte[blockSize]; while ((long) totalRead < fileLen) { readBytes = in.read(b, 0, blockSize); totalRead += readBytes; fout.write(b, 0, readBytes); } in.close(); fout.close(); }
00
Code Sample 1: private void bubbleSort() { for (int i = 0; i < testfield.length; i++) { for (int j = 0; j < testfield.length - i - 1; j++) if (testfield[j] > testfield[j + 1]) { short temp = testfield[j]; testfield[j] = testfield[j + 1]; testfield[j + 1] = temp; } } } Code Sample 2: private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
11
Code Sample 1: private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } Code Sample 2: public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public void openFtpConnection(String workingDirectory) throws RQLException { try { ftpClient = new FTPClient(); ftpClient.connect(server); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(workingDirectory); } catch (IOException ioex) { throw new RQLException("FTP client could not be created. Please check attributes given in constructor.", ioex); } } Code Sample 2: public static String getHighlightBaseLib() throws Exception { StringBuffer highlightKey = new StringBuffer(); highlightKey.append("<c color=\"" + COLOR_BASELIB + "\">\n\t"); URL url = AbstractRunner.class.getResource("baselib.js"); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is, "UTF-8"); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { if (tmp.indexOf("function") > -1) { highlightKey.append("<w>" + (tmp.substring(tmp.indexOf("function") + 8, tmp.indexOf("(")).trim()) + "</w>\n\t"); } } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } highlightKey.append("</c>"); return highlightKey.toString(); }
11
Code Sample 1: private void writeMessage(ChannelBuffer buffer, File dst) throws IOException { ChannelBufferInputStream is = new ChannelBufferInputStream(buffer); OutputStream os = null; try { os = new FileOutputStream(dst); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); } } Code Sample 2: 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(); } }
00
Code Sample 1: public static String getSHADigest(String input) { if (input == null) return null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (java.security.NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } if (sha == null) throw new RuntimeException("No message digest"); sha.update(input.getBytes()); byte[] data = sha.digest(); StringBuffer buf = new StringBuffer(data.length * 2); for (int i = 0; i < data.length; i++) { int value = data[i] & 0xff; buf.append(hexDigit(value >> 4)); buf.append(hexDigit(value)); } return buf.toString(); } Code Sample 2: public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException e) { } } } }
00
Code Sample 1: @Test public void testConfigurartion() { try { Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties"); log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties")); log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml")); log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml")); if (log.isDebugEnabled()) { while (assemblersToRegister.hasMoreElements()) { URL url = (URL) assemblersToRegister.nextElement(); InputStream in = url.openStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(in)); String line = buff.readLine(); while (line != null) { log.debug(line); line = buff.readLine(); } buff.close(); in.close(); } } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); }
00
Code Sample 1: public static String hexSHA1(String value) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); md.update(value.getBytes("utf-8")); byte[] digest = md.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } } Code Sample 2: @Override protected void setUp() throws Exception { super.setUp(); FTPConf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); FTPConf.setServerTimeZoneId("GMT"); FTP.configure(FTPConf); try { FTP.connect("tgftp.nws.noaa.gov"); FTP.login("anonymous", "[email protected]"); FTP.changeWorkingDirectory("SL.us008001/DF.an/DC.sflnd/DS.metar"); FTP.enterLocalPassiveMode(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); System.exit(1); } BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.gz"))); System.out.println("Writing file"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz")))); String s; while ((s = in2.readLine()) != null) System.out.println(s); } Code Sample 2: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
00
Code Sample 1: public String control(final String allOptions) throws SQLException { connect(); final Statement stmt = connection.createStatement(); final ResultSet rst1 = stmt.executeQuery("SELECT versionId FROM versions WHERE version='" + Concrete.version() + "'"); final long versionId; if (rst1.next()) { versionId = rst1.getInt(1); } else { disconnect(); return ""; } rst1.close(); final MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { logger.throwing(SQLExecutionController.class.getSimpleName(), "control", e1); disconnect(); return ""; } msgDigest.update(allOptions.getBytes()); final ResultSet rst2 = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + Concrete.md5(msgDigest.digest()) + "'"); final long configId; if (rst2.next()) { configId = rst2.getInt(1); } else { disconnect(); return ""; } rst2.close(); final ResultSet rst4 = stmt.executeQuery("SELECT problems.md5 FROM executions " + "LEFT JOIN problems ON executions.problemId = problems.problemId WHERE " + "configId=" + configId + " AND versionId=" + versionId); final StringBuilder stb = new StringBuilder(); while (rst4.next()) { stb.append(rst4.getString(1)).append('\n'); } rst4.close(); stmt.close(); return stb.toString(); } Code Sample 2: public void connect() throws ClientProtocolException, IOException { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); inputStream = entity.getContent(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (HeaderElement encoding : codecs) { if (encoding.getName().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } } } inputStream = new BufferedInputStream(inputStream, 2048); }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
11
Code Sample 1: @Override public byte[] read(String path) throws PersistenceException { path = fmtPath(path); try { S3Object fileObj = s3Service.getObject(bucketObj, path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(fileObj.getDataInputStream(), out); return out.toByteArray(); } catch (Exception e) { throw new PersistenceException("fail to read s3 file - " + path, e); } } Code Sample 2: public static synchronized BaseFont getL2BaseFont() { if (l2baseFont == null) { final ConfigProvider conf = ConfigProvider.getInstance(); try { final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); String fontPath = conf.getNotEmptyProperty("font.path", null); String fontName; String fontEncoding; InputStream tmpIs; if (fontPath != null) { fontName = conf.getNotEmptyProperty("font.name", null); if (fontName == null) { fontName = new File(fontPath).getName(); } fontEncoding = conf.getNotEmptyProperty("font.encoding", null); if (fontEncoding == null) { fontEncoding = BaseFont.WINANSI; } tmpIs = new FileInputStream(fontPath); } else { fontName = Constants.L2TEXT_FONT_NAME; fontEncoding = BaseFont.IDENTITY_H; tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH); } IOUtils.copy(tmpIs, tmpBaos); tmpIs.close(); tmpBaos.close(); l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED, tmpBaos.toByteArray(), null); } catch (Exception e) { e.printStackTrace(); try { l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception ex) { } } } return l2baseFont; }
00
Code Sample 1: public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; } Code Sample 2: 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>&nbsp;<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(); } }
11
Code Sample 1: public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } } Code Sample 2: public static String getHash(String userName, String pass) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes()); hash = ISOUtil.hexString(md.digest(pass.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException e) { } return hash; }
11
Code Sample 1: public final String hashRealmPassword(String username, String realm, String password) throws GeneralSecurityException { MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] hash = md.digest(); return toHex(hash, hash.length); } Code Sample 2: public static String generate(String username, String password) throws PersistenceException { String output = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(username.getBytes()); md.update(password.getBytes()); byte[] rawhash = md.digest(); output = byteToBase64(rawhash); } catch (Exception e) { throw new PersistenceException("error, could not generate password"); } return output; }
00
Code Sample 1: public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); } Code Sample 2: private boolean createFTPConnection() { client = new FTPClient(); System.out.println("Client created"); try { client.connect(this.hostname, this.port); System.out.println("Connected: " + this.hostname + ", " + this.port); client.login(username, password); System.out.println("Logged in: " + this.username + ", " + this.password); this.setupActiveFolder(); return true; } catch (IllegalStateException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPIllegalReplyException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } return false; }
11
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
11
Code Sample 1: private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: private static void copySmallFile(final File sourceFile, final File targetFile) throws PtException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new PtException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(inChannel, outChannel); } }
00
Code Sample 1: public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { String req1xml = jTextArea1.getText(); java.net.URL url = new java.net.URL("http://217.34.8.235:8080/newgenlibctxt/PatronServlet"); 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(); 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); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } 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.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(gip)); String reqxml = ""; while (br.ready()) { String line = br.readLine(); reqxml += line; } try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } }
11
Code Sample 1: public void addUserToRealm(final NewUser user) { try { connection.setAutoCommit(false); final String pass, salt; final List<RealmWithEncryptedPass> realmPass = new ArrayList<RealmWithEncryptedPass>(); Realm realm; String username; username = user.username.toLowerCase(locale); PasswordHasher ph = PasswordFactory.getInstance().getPasswordHasher(); pass = ph.hashPassword(user.password); salt = ph.getSalt(); realmPass.add(new RealmWithEncryptedPass(cm.getRealm("null"), PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, "", user.password))); if (user.realms != null) { for (String realmName : user.realms) { realm = cm.getRealm(realmName); realmPass.add(new RealmWithEncryptedPass(realm, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(username, realm.getFullRealmName(), user.password))); } user.realms = null; } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); psImpl.setString(1, pass); psImpl.setString(2, salt); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); } }); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realm.addUser")); RealmWithEncryptedPass rwep; RealmDb realm; Iterator<RealmWithEncryptedPass> iter1 = realmPass.iterator(); while (iter1.hasNext()) { rwep = iter1.next(); realm = (RealmDb) rwep.realm; psImpl.setInt(1, realm.getRealmId()); psImpl.setInt(2, user.userId); psImpl.setInt(3, user.domainId); psImpl.setString(4, rwep.password); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUser(user.userId); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: private void removeCollection(long oid, Connection conn) throws XMLDBException { try { String sql = "DELETE FROM X_DOCUMENT WHERE X_DOCUMENT.XDB_COLLECTION_OID = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); sql = "DELETE FROM XDB_COLLECTION WHERE XDB_COLLECTION.XDB_COLLECTION_OID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); removeChildCollection(oid, conn); } catch (java.sql.SQLException se) { try { conn.rollback(); } catch (java.sql.SQLException se2) { se2.printStackTrace(); } se.printStackTrace(); } }
00
Code Sample 1: private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); } Code Sample 2: public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
11
Code Sample 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) { ; } } } Code Sample 2: public RawTableData(int selectedId) { selectedProjectId = selectedId; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjectDocuments"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "documents.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&projectid=" + selectedProjectId + "&filename=" + URLEncoder.encode(username, "UTF-8") + "documents.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("doc"); int num = nodelist.getLength(); rawTableData = new String[num][11]; imageNames = new String[num]; for (int i = 0; i < num; i++) { rawTableData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "did")); rawTableData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "t")); rawTableData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); rawTableData[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "d")); rawTableData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "l")); String firstname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "fn")); String lastname = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ln")); rawTableData[i][5] = firstname + " " + lastname; rawTableData[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dln")); rawTableData[i][7] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "rsid")); rawTableData[i][8] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); imageNames[i] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "img")); rawTableData[i][9] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ucin")); rawTableData[i][10] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "dtid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
00
Code Sample 1: private void makeConn(String filename1, String filename2) { String basename = "http://www.bestmm.com/"; String urlname = basename + filename1 + "/pic/" + filename2 + ".jpg"; URL url = null; try { url = new URL(urlname); } catch (MalformedURLException e) { System.err.println("URL Format Error!"); System.exit(1); } try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.err.println("Error IO"); System.exit(2); } } Code Sample 2: public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
00
Code Sample 1: public synchronized void checkout() throws SQLException, InterruptedException { Connection con = this.session.open(); con.setAutoCommit(false); String sql_stmt = DB2SQLStatements.shopping_cart_getAll(this.customer_id); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet res = stmt.executeQuery(sql_stmt); res.last(); int rowcount = res.getRow(); res.beforeFirst(); ShoppingCartItem[] resArray = new ShoppingCartItem[rowcount]; int i = 0; while (res.next()) { resArray[i] = new ShoppingCartItem(); resArray[i].setCustomer_id(res.getInt("customer_id")); resArray[i].setDate_start(res.getDate("date_start")); resArray[i].setDate_stop(res.getDate("date_stop")); resArray[i].setRoom_type_id(res.getInt("room_type_id")); resArray[i].setNumtaken(res.getInt("numtaken")); resArray[i].setTotal_price(res.getInt("total_price")); i++; } this.wait(4000); try { for (int j = 0; j < rowcount; j++) { sql_stmt = DB2SQLStatements.room_date_update(resArray[j]); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } } catch (SQLException e) { e.printStackTrace(); con.rollback(); } for (int j = 0; j < rowcount; j++) { System.out.println(j); sql_stmt = DB2SQLStatements.booked_insert(resArray[j], 2); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); } sql_stmt = DB2SQLStatements.shopping_cart_deleteAll(this.customer_id); stmt = con.createStatement(); stmt.executeUpdate(sql_stmt); con.commit(); this.session.close(con); } Code Sample 2: public void deleteScript(Integer id) { InputStream is = null; try { URL url = new URL(strServlet + getSessionIDSuffix() + "?deleteScript=" + id); System.out.println("requesting: " + url); is = url.openStream(); while (is.read() != -1) ; } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e) { } } }
11
Code Sample 1: public static void copy(File toCopy, File dest) throws IOException { FileInputStream src = new FileInputStream(toCopy); FileOutputStream out = new FileOutputStream(dest); try { while (src.available() > 0) { out.write(src.read()); } } finally { src.close(); out.close(); } } Code Sample 2: 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); } }
11
Code Sample 1: public String generateKey(Message msg) { String text = msg.getDefaultMessage(); String meaning = msg.getMeaning(); if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
00
Code Sample 1: private String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); uc.setRequestProperty("Cookie", NetLoadAccount.getPhpsessioncookie()); br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; } Code Sample 2: public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
00
Code Sample 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!"); } Code Sample 2: private ArrayList execAtParentServer(ArrayList paramList) throws Exception { ArrayList outputList = null; String message = ""; try { HashMap serverUrlMap = InitXml.getInstance().getServerMap(); Iterator it = serverUrlMap.keySet().iterator(); while (it.hasNext()) { String server = (String) it.next(); String serverUrl = (String) serverUrlMap.get(server); serverUrl = serverUrl + Primer3Manager.servletName; URL url = new URL(serverUrl); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("actionType=designparent"); for (int i = 0; i < paramList.size(); i++) { Primer3Param param = (Primer3Param) paramList.get(i); if (i == 0) { buf.append("&sequence=" + param.getSequence()); buf.append("&upstream_size" + upstreamSize); buf.append("&downstreamSize" + downstreamSize); buf.append("&MARGIN_LENGTH=" + marginLength); buf.append("&OVERLAP_LENGTH=" + overlapLength); buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize()); buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize()); buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize()); buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability()); buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming()); buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming()); buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize()); buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize()); buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize()); buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm()); buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm()); buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm()); buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm()); buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc()); buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent()); buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc()); buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny()); buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd()); buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted()); buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX()); buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp()); } buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]); } PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); outputList = (ArrayList) ois.readObject(); ois.close(); } } catch (IOException e1) { e1.printStackTrace(); } if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) { throw new Exception(message); } return outputList; }
00
Code Sample 1: private static void addFile(File file, TarArchiveOutputStream taos) throws IOException { String filename = null; filename = file.getName(); TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } Code Sample 2: private RemoteObject createRemoteObject(final VideoEntry videoEntry, final RemoteContainer container) throws RemoteException { MessageDigest instance; try { instance = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RemoteException(StatusCreator.newStatus("Error creating MD5", e)); } StringWriter sw = new StringWriter(); YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup(); if (mediaGroup != null) { if (mediaGroup.getDescription() != null) { sw.append(mediaGroup.getDescription().getPlainTextContent()); } List<MediaCategory> keywordsGroup = mediaGroup.getCategories(); StringBuilder sb = new StringBuilder(); if (keywordsGroup != null) { for (MediaCategory mediaCategory : keywordsGroup) { sb.append(mediaCategory.getContent()); } } } instance.update(sw.toString().getBytes()); RemoteObject remoteVideo = InfomngmntFactory.eINSTANCE.createRemoteObject(); remoteVideo.setHash(asHex(instance.digest())); remoteVideo.setId(SiteInspector.getId(videoEntry.getHtmlLink().getHref())); remoteVideo.setName(videoEntry.getTitle().getPlainText()); remoteVideo.setRepositoryTypeObjectId(KEY_VIDEO); remoteVideo.setWrappedObject(videoEntry); setInternalUrl(remoteVideo, container); return remoteVideo; }
00
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: public static String getSHA1Hash(String plainText) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(plainText.getBytes()); byte[] mdbytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { String hex = Integer.toHexString(0xFF & mdbytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString().toUpperCase(); }
11
Code Sample 1: public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; } Code Sample 2: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); }
00
Code Sample 1: public boolean saveVideoXMLOnWebserver() { String text = ""; boolean erg = false; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/videofile.jsp?id=" + this.getId()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { text += zeile + "\n"; } in.close(); http.disconnect(); erg = saveVideoXMLOnWebserver(text); System.err.println("Job " + this.getId() + " erfolgreich bearbeitet!"); } catch (MalformedURLException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Verbindung konnte nicht aufgebaut werden."); return false; } catch (IOException e) { System.err.println("Job " + this.getId() + ": Konnte video.xml nicht erstellen. Konnte Daten nicht lesen/schreiben."); return false; } return erg; } Code Sample 2: public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); }
11
Code Sample 1: private String hashmd5(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { } } try { digest.update(data.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { } return encodeHex(digest.digest()); }
11
Code Sample 1: public final String encrypt(String input) throws Exception { try { MessageDigest messageDigest = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); messageDigest.reset(); messageDigest.update(input.getBytes()); String output = convert(messageDigest.digest()); return output; } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Fatal Error while digesting input string", ex); } } return input; } Code Sample 2: public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
11
Code Sample 1: public static void decryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } Code Sample 2: private static boolean copyFile(File srcFile, File tagFile) throws IOException { if (srcFile == null || tagFile == null) { return false; } int length = 2097152; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(tagFile); FileChannel inC = in.getChannel(); FileChannel outC = out.getChannel(); int i = 0; while (true) { if (inC.position() == inC.size()) { inC.close(); outC.close(); break; } if ((inC.size() - inC.position()) < 20971520) length = (int) (inC.size() - inC.position()); else length = 20971520; inC.transferTo(inC.position(), length, outC); inC.position(inC.position() + length); i++; } return true; }
00
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: private String getBytes(String in) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); byte[] passWordBytes = md5.digest(); String s = "["; for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", "; s = s.substring(0, s.length() - 2); s += "]"; return s; } Code Sample 2: private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } }
00
Code Sample 1: public synchronized void connect() throws FTPException, IOException { if (eventAggregator != null) { eventAggregator.setConnId(ftpClient.getId()); ftpClient.setMessageListener(eventAggregator); ftpClient.setProgressMonitor(eventAggregator); ftpClient.setProgressMonitorEx(eventAggregator); } statistics.clear(); configureClient(); log.debug("Configured client"); ftpClient.connect(); log.debug("Client connected"); if (masterContext.isAutoLogin()) { log.debug("Logging in"); ftpClient.login(masterContext.getUserName(), masterContext.getPassword()); log.debug("Logged in"); configureTransferType(masterContext.getContentType()); } else { log.debug("Manual login enabled"); } } Code Sample 2: public static String getMD5(String password) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String pwd = new BigInteger(1, md5.digest()).toString(16); return pwd; } catch (Exception e) { logger.error(e.getMessage()); } return password; }
00
Code Sample 1: public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; byte BUFFER[] = new byte[100]; java.net.URL fileurl; URLConnection conn; fileurl = new java.net.URL(url); conn = fileurl.openConnection(); long fullsize = conn.getContentLength(); long onepercent = fullsize / 100; MessageFrame.setTotalDownloadSize(fullsize); bi = new BufferedInputStream(conn.getInputStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int read = 0; int sum = 0; long i = 0; while ((read = bi.read(BUFFER)) != -1) { bo.write(BUFFER, 0, read); sum += read; i += read; if (i > onepercent) { i = 0; MessageFrame.setDownloadProgress(sum); } } bi.close(); bo.close(); MessageFrame.setDownloadProgress(fullsize); return true; } Code Sample 2: public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,nextval('pilot_id_seq'))"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
00
Code Sample 1: public void setUp() { configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml"); getProject().executeTarget("setup"); tmpDir = getProject().getProperty("tmp.dir"); ftp = new FTPClient(); ftpFileSep = getProject().getProperty("ftp.filesep"); myFTPTask.setSeparator(ftpFileSep); myFTPTask.setProject(getProject()); remoteTmpDir = myFTPTask.resolveFile(tmpDir); String remoteHost = getProject().getProperty("ftp.host"); int port = Integer.parseInt(getProject().getProperty("ftp.port")); String remoteUser = getProject().getProperty("ftp.user"); String password = getProject().getProperty("ftp.password"); try { ftp.connect(remoteHost, port); } catch (Exception ex) { connectionSucceeded = false; loginSuceeded = false; System.out.println("could not connect to host " + remoteHost + " on port " + port); } if (connectionSucceeded) { try { ftp.login(remoteUser, password); } catch (IOException ioe) { loginSuceeded = false; System.out.println("could not log on to " + remoteHost + " as user " + remoteUser); } } } Code Sample 2: @Test public void test_baseMaterialsForTypeID_NonExistingID() throws Exception { URL url = new URL(baseUrl + "/baseMaterialsForTypeID/1234567890"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
11
Code Sample 1: public static void main(String[] args) { try { FileReader reader = new FileReader(args[0]); FileWriter writer = new FileWriter(args[1]); html2xhtml(reader, writer); writer.close(); reader.close(); } catch (Exception e) { freemind.main.Resources.getInstance().logException(e); } } Code Sample 2: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setInt(2, q.getDisciplina().getIdDisciplina()); stmt.setInt(3, idTopico); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } }
11
Code Sample 1: public static void copy_file(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static boolean copyFile(String fromfile, String tofile) { File from = new File(fromfile); File to = new File(tofile); if (!from.exists()) return false; if (to.exists()) { log.error(tofile + "exists already"); return false; } BufferedInputStream in = null; BufferedOutputStream out = null; FileInputStream fis = null; FileOutputStream ois = null; boolean flag = true; try { to.createNewFile(); fis = new FileInputStream(from); ois = new FileOutputStream(to); in = new BufferedInputStream(fis); out = new BufferedOutputStream(ois); byte[] buf = new byte[2048]; int readBytes = 0; while ((readBytes = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, readBytes); } } catch (IOException e) { log.error(e); flag = false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { log.error(e); flag = false; } } return flag; }
11
Code Sample 1: public void configureKerberos(boolean overwriteExistingSetup) throws Exception { OutputStream keyTabOut = null; InputStream keyTabIn = null; OutputStream krb5ConfOut = null; try { keyTabIn = loadKeyTabResource(keyTabResource); File file = new File(keyTabRepository + keyTabResource); if (!file.exists() || overwriteExistingSetup) { keyTabOut = new FileOutputStream(file, false); if (logger.isDebugEnabled()) logger.debug("Installing keytab file to : " + file.getAbsolutePath()); IOUtils.copy(keyTabIn, keyTabOut); } File krb5ConfFile = new File(System.getProperty("java.security.krb5.conf", defaultKrb5Config)); if (logger.isDebugEnabled()) logger.debug("Using Kerberos config file : " + krb5ConfFile.getAbsolutePath()); if (!krb5ConfFile.exists()) throw new Exception("Kerberos config file not found : " + krb5ConfFile.getAbsolutePath()); FileInputStream fis = new FileInputStream(krb5ConfFile); Wini krb5Conf = new Wini(KerberosConfigUtil.toIni(fis)); Ini.Section krb5Realms = krb5Conf.get("realms"); String windowsDomainSetup = krb5Realms.get(kerberosRealm); if (kerberosRealm == null || overwriteExistingSetup) { windowsDomainSetup = "{ kdc = " + keyDistributionCenter + ":88 admin_server = " + keyDistributionCenter + ":749 default_domain = " + kerberosRealm.toLowerCase() + " }"; krb5Realms.put(kerberosRealm, windowsDomainSetup); } Ini.Section krb5DomainRealms = krb5Conf.get("domain_realm"); String domainRealmSetup = krb5DomainRealms.get(kerberosRealm.toLowerCase()); if (domainRealmSetup == null || overwriteExistingSetup) { krb5DomainRealms.put(kerberosRealm.toLowerCase(), kerberosRealm); krb5DomainRealms.put("." + kerberosRealm.toLowerCase(), kerberosRealm); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); krb5Conf.store(baos); InputStream bios = new ByteArrayInputStream(baos.toByteArray()); bios = KerberosConfigUtil.toKrb5(bios); krb5ConfOut = new FileOutputStream(krb5ConfFile, false); IOUtils.copy(bios, krb5ConfOut); } catch (Exception e) { logger.error("Error while configuring Kerberos :" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(keyTabOut); IOUtils.closeQuietly(keyTabIn); IOUtils.closeQuietly(krb5ConfOut); } } Code Sample 2: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
00
Code Sample 1: void sort(int a[]) throws Exception { for (int i = a.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (stopRequested) { return; } if (a[j] > a[j + 1]) { int T = a[j]; a[j] = a[j + 1]; a[j + 1] = T; flipped = true; } pause(i, j); } if (!flipped) { return; } } } Code Sample 2: private synchronized void ensureParsed() throws IOException, BadIMSCPException { if (cp != null) return; if (on_disk == null) { on_disk = createTemporaryFile(); OutputStream to_disk = new FileOutputStream(on_disk); IOUtils.copy(in.getInputStream(), to_disk); to_disk.close(); } try { ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser(); parser.parse(on_disk); cp = parser.getPackage(); } catch (BadParseException x) { throw new BadIMSCPException("Cannot parse content package", x); } }
00
Code Sample 1: public static void fileCopy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: private void checkServerAccess() throws IOException { URL url = new URL("https://testnetbeans.org/bugzilla/index.cgi"); try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); } catch (IOException exc) { disableMessage = "Bugzilla is not accessible"; } url = new URL(BugzillaConnector.SERVER_URL); try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.connect(); } catch (IOException exc) { disableMessage = "Bugzilla Service is not accessible"; } }
11
Code Sample 1: private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public void copy(File aSource, File aDestDir) throws IOException { FileInputStream myInFile = new FileInputStream(aSource); FileOutputStream myOutFile = new FileOutputStream(new File(aDestDir, aSource.getName())); FileChannel myIn = myInFile.getChannel(); FileChannel myOut = myOutFile.getChannel(); boolean end = false; while (true) { int myBytes = myIn.read(theBuffer); if (myBytes != -1) { theBuffer.flip(); myOut.write(theBuffer); theBuffer.clear(); } else break; } myIn.close(); myOut.close(); myInFile.close(); myOutFile.close(); long myEnd = System.currentTimeMillis(); }
11
Code Sample 1: public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; } Code Sample 2: public Vector<String> getVoiceServersNames() { Vector<String> result = new Vector<String>(); boolean serverline = false; String line; String[] splitline; try { URL url = new URL(voiceaddress); URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { if (serverline) { splitline = line.split(":"); result.add(splitline[0]); } if (line.startsWith("!VOICE SERVERS")) { serverline = true; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
00
Code Sample 1: public static String getInstanceUserdata() throws IOException { int retries = 0; while (true) { try { URL url = new URL("http://169.254.169.254/latest/user-data/"); InputStreamReader rdr = new InputStreamReader(url.openStream()); StringWriter wtr = new StringWriter(); char[] buf = new char[1024]; int bytes; while ((bytes = rdr.read(buf)) > -1) { if (bytes > 0) { wtr.write(buf, 0, bytes); } } rdr.close(); return wtr.toString(); } catch (IOException ex) { if (retries == 5) { logger.debug("Problem getting user data, retries exhausted..."); return null; } else { logger.debug("Problem getting user data, retrying..."); try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException e) { } retries++; } } } } Code Sample 2: public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: java xyzImpl inputfile"); System.exit(0); } XYZ xyz = null; try { URL url = new URL(Util.makeAbsoluteURL(args[0])); BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream())); int idx = args[0].indexOf("."); String id = (idx == -1) ? args[0] : args[0].substring(0, idx); idx = id.lastIndexOf("\\"); if (idx != -1) id = id.substring(idx + 1); xyz = new XYZImpl(bReader, id); CMLMolecule mol = xyz.getMolecule(); StringWriter sw = new StringWriter(); mol.debug(sw); System.out.println(sw.toString()); SpanningTree sTree = new SpanningTreeImpl(mol); System.out.println(sTree.toSMILES()); Writer w = new OutputStreamWriter(new FileOutputStream(id + ".xml")); PMRDelegate.outputEventStream(mol, w, PMRNode.PRETTY, 0); w.close(); w = new OutputStreamWriter(new FileOutputStream(id + "-new.mol")); xyz.setOutputCMLMolecule(mol); xyz.output(w); w.close(); } catch (Exception e) { System.out.println("xyz failed: " + e); e.printStackTrace(); System.exit(0); } }
11
Code Sample 1: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } } Code Sample 2: 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); } } }
00
Code Sample 1: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } Code Sample 2: private void downloadThread() { int c; status = false; try { URLConnection urlc = resource.url.openConnection(); File f = resource.createFile(); boolean resume = false; resource.resetBytesDown(); if (f.exists()) { if (f.lastModified() > resource.date.getTime()) { if ((resource.getFileSize() == f.length())) { status = true; return; } else { urlc.setRequestProperty("Range", "bytes=" + f.length() + "-"); resume = true; resource.incrementBytesDown(f.length()); System.out.println("Resume download"); System.out.println("file length: " + f.length()); } } } urlc.connect(); bin = new BufferedInputStream(urlc.getInputStream()); file_out = new FileOutputStream(f.getPath(), resume); while (life) { if (bin.available() > 0) { c = bin.read(); if (c == -1) { break; } file_out.write(c); if (resource.incrementBytesDown()) { break; } else { continue; } } sleep(WAIT_FOR_A_BYTE_TIME); } file_out.flush(); status = true; } catch (IOException e) { System.out.println("excepcion cpoy file"); } catch (InterruptedException e) { System.out.println("InterruptException download"); System.out.println(e); } }
00
Code Sample 1: private void RotaDraw(GeoPoint orig, GeoPoint dest, int color, MapView mapa) { StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.google.com/maps?f=d&hl=en"); urlString.append("&saddr="); urlString.append(Double.toString((double) orig.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) orig.getLongitudeE6() / 1.0E6)); urlString.append("&daddr="); urlString.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6)); urlString.append("&ie=UTF8&0&om=0&output=kml"); Document doc = null; HttpURLConnection urlConnection = null; URL url = null; try { url = new URL(urlString.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(urlConnection.getInputStream()); if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) { String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue(); Log.d("xxx", "path=" + path); String[] pairs = path.split(" "); String[] lngLat = pairs[0].split(","); GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(startGP, startGP, 1)); GeoPoint gp1; GeoPoint gp2 = startGP; for (int i = 1; i < pairs.length; i++) { lngLat = pairs[i].split(","); gp1 = gp2; gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(gp1, gp2, 2, color)); Log.d("xxx", "pair:" + pairs[i]); } mapa.getOverlays().add(new CamadaGS(dest, dest, 3)); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } Code Sample 2: 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!"); }
11
Code Sample 1: protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); } Code Sample 2: protected void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).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(); } } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public boolean download(String url) { HttpGet httpGet = new HttpGet(url); String filename = FileUtils.replaceNonAlphanumericCharacters(url); String completePath = directory + File.separatorChar + filename; int retriesLeft = MAX_RETRIES; while (retriesLeft > 0) { try { HttpResponse response = httpClient.execute(httpGet); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { logger.info("Downloading file from " + url + " -> " + completePath); IOUtils.copy(resEntity.getContent(), new FileOutputStream(completePath)); logger.info("File " + filename + " was downloaded successfully."); setFileSize(new File(completePath).length()); setFilename(filename); return true; } else { logger.warn("Trouble downloading file from " + url + ". Status was: " + response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error("Protocol error. This is probably serious, and there's no need " + "to continue trying to download this file.", e); return false; } catch (IOException e) { logger.warn("IO trouble: " + e.getMessage() + ". Retries left: " + retriesLeft); } retriesLeft--; } return false; }
00
Code Sample 1: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; ClassdiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((ClassdiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } } Code Sample 2: public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
11
Code Sample 1: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; } Code Sample 2: public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long time = System.currentTimeMillis(); String text = request.getParameter("text"); String parsedQueryString = request.getQueryString(); if (text == null) { String[] fonts = new File(ctx.getRealPath("/WEB-INF/fonts/")).list(); text = "accepted params: text,font,size,color,background,nocache,aa,break"; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<p>"); out.println("Usage: " + request.getServletPath() + "?params[]<BR>"); out.println("Acceptable Params are: <UL>"); out.println("<LI><B>text</B><BR>"); out.println("The body of the image"); out.println("<LI><B>font</B><BR>"); out.println("Available Fonts (in folder '/WEB-INF/fonts/') <UL>"); for (int i = 0; i < fonts.length; i++) { if (!"CVS".equals(fonts[i])) { out.println("<LI>" + fonts[i]); } } out.println("</UL>"); out.println("<LI><B>size</B><BR>"); out.println("An integer, i.e. size=100"); out.println("<LI><B>color</B><BR>"); out.println("in rgb, i.e. color=255,0,0"); out.println("<LI><B>background</B><BR>"); out.println("in rgb, i.e. background=0,0,255"); out.println("transparent, i.e. background=''"); out.println("<LI><B>aa</B><BR>"); out.println("antialias (does not seem to work), aa=true"); out.println("<LI><B>nocache</B><BR>"); out.println("if nocache is set, we will write out the image file every hit. Otherwise, will write it the first time and then read the file"); out.println("<LI><B>break</B><BR>"); out.println("An integer greater than 0 (zero), i.e. break=20"); out.println("</UL>"); out.println("</UL>"); out.println("Example:<BR>"); out.println("&lt;img border=1 src=\"" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100\"&gt;<BR>"); out.println("<img border=1 src='" + request.getServletPath() + "?font=arial.ttf&text=testing&color=255,0,0&size=100'><BR>"); out.println("</body>"); out.println("</html>"); return; } String myFile = (request.getQueryString() == null) ? "empty" : PublicEncryptionFactory.digestString(parsedQueryString).replace('\\', '_').replace('/', '_'); myFile = Config.getStringProperty("PATH_TO_TITLE_IMAGES") + myFile + ".png"; File file = new File(ctx.getRealPath(myFile)); if (!file.exists() || (request.getParameter("nocache") != null)) { StringTokenizer st = null; Iterator i = hm.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String key = (String) entry.getKey(); if (parsedQueryString.indexOf(key) > -1) { String val = (String) entry.getValue(); parsedQueryString = UtilMethods.replace(parsedQueryString, key, val); } } st = new StringTokenizer(parsedQueryString, "&"); while (st.hasMoreTokens()) { try { String x = st.nextToken(); String key = x.split("=")[0]; String val = x.split("=")[1]; if ("text".equals(key)) { text = val; } } catch (Exception e) { } } text = URLDecoder.decode(text, "UTF-8"); Logger.debug(this.getClass(), "building title image:" + file.getAbsolutePath()); file.createNewFile(); try { String font_file = "/WEB-INF/fonts/arial.ttf"; if (request.getParameter("font") != null) { font_file = "/WEB-INF/fonts/" + request.getParameter("font"); } font_file = ctx.getRealPath(font_file); float size = 20.0f; if (request.getParameter("size") != null) { size = Float.parseFloat(request.getParameter("size")); } Color background = Color.white; if (request.getParameter("background") != null) { if (request.getParameter("background").equals("transparent")) try { background = new Color(Color.TRANSLUCENT); } catch (Exception e) { } else try { st = new StringTokenizer(request.getParameter("background"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); background = new Color(x, y, z); } catch (Exception e) { } } Color color = Color.black; if (request.getParameter("color") != null) { try { st = new StringTokenizer(request.getParameter("color"), ","); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int z = Integer.parseInt(st.nextToken()); color = new Color(x, y, z); } catch (Exception e) { Logger.info(this, e.getMessage()); } } int intBreak = 0; if (request.getParameter("break") != null) { try { intBreak = Integer.parseInt(request.getParameter("break")); } catch (Exception e) { } } java.util.ArrayList<String> lines = null; if (intBreak > 0) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); int start = 0; String line = null; int offSet; for (; ; ) { try { for (; isWhitespace(text.charAt(start)); ++start) ; if (isWhitespace(text.charAt(start + intBreak - 1))) { lines.add(text.substring(start, start + intBreak)); start += intBreak; } else { for (offSet = -1; !isWhitespace(text.charAt(start + intBreak + offSet)); ++offSet) ; lines.add(text.substring(start, start + intBreak + offSet)); start += intBreak + offSet; } } catch (Exception e) { if (text.length() > start) lines.add(leftTrim(text.substring(start))); break; } } } else { java.util.StringTokenizer tokens = new java.util.StringTokenizer(text, "|"); if (tokens.hasMoreTokens()) { lines = new java.util.ArrayList<String>(10); lines.ensureCapacity(10); for (; tokens.hasMoreTokens(); ) lines.add(leftTrim(tokens.nextToken())); } } Font font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream(font_file)); font = font.deriveFont(size); BufferedImage buffer = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = buffer.createGraphics(); if (request.getParameter("aa") != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } FontRenderContext fc = g2.getFontRenderContext(); Rectangle2D fontBounds = null; Rectangle2D textLayoutBounds = null; TextLayout tl = null; boolean useTextLayout = false; useTextLayout = Boolean.parseBoolean(request.getParameter("textLayout")); int width = 0; int height = 0; int offSet = 0; if (1 < lines.size()) { int heightMultiplier = 0; int maxWidth = 0; for (; heightMultiplier < lines.size(); ++heightMultiplier) { fontBounds = font.getStringBounds(lines.get(heightMultiplier), fc); tl = new TextLayout(lines.get(heightMultiplier), font, fc); textLayoutBounds = tl.getBounds(); if (maxWidth < Math.ceil(fontBounds.getWidth())) maxWidth = (int) Math.ceil(fontBounds.getWidth()); } width = maxWidth; int boundHeigh = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); height = boundHeigh * lines.size(); offSet = ((int) (boundHeigh * 0.2)) * (lines.size() - 1); } else { fontBounds = font.getStringBounds(text, fc); tl = new TextLayout(text, font, fc); textLayoutBounds = tl.getBounds(); width = (int) fontBounds.getWidth(); height = (int) Math.ceil((!useTextLayout ? fontBounds.getHeight() : textLayoutBounds.getHeight())); } buffer = new BufferedImage(width, height - offSet, BufferedImage.TYPE_INT_ARGB); g2 = buffer.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(font); g2.setColor(background); if (!background.equals(new Color(Color.TRANSLUCENT))) g2.fillRect(0, 0, width, height); g2.setColor(color); if (1 < lines.size()) { for (int numLine = 0; numLine < lines.size(); ++numLine) { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(lines.get(numLine), 0, -y * (numLine + 1)); } } else { int y = (int) Math.ceil((!useTextLayout ? fontBounds.getY() : textLayoutBounds.getY())); g2.drawString(text, 0, -y); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(buffer, "png", out); out.close(); } catch (Exception ex) { Logger.info(this, ex.toString()); } } response.setContentType("image/png"); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); OutputStream os = response.getOutputStream(); byte[] buf = new byte[4096]; int i = 0; while ((i = bis.read(buf)) != -1) { os.write(buf, 0, i); } os.close(); bis.close(); Logger.debug(this.getClass(), "time to build title: " + (System.currentTimeMillis() - time) + "ms"); return; }
00
Code Sample 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!"); } Code Sample 2: public static void updateTableData(Connection dest, TableMetaData tableMetaData) throws Exception { PreparedStatement ps = null; try { dest.setAutoCommit(false); String sql = "UPDATE " + tableMetaData.getSchema() + "." + tableMetaData.getTableName() + " SET "; for (String columnName : tableMetaData.getColumnsNames()) { sql += columnName + " = ? ,"; } sql = sql.substring(0, sql.length() - 1); sql += " WHERE "; for (String pkColumnName : tableMetaData.getPkColumns()) { sql += pkColumnName + " = ? AND "; } sql = sql.substring(0, sql.length() - 4); ps = dest.prepareStatement(sql); for (Row r : tableMetaData.getData()) { int param = 1; for (String columnName : tableMetaData.getColumnsNames()) { if (dest instanceof OracleConnection) { if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("BLOB")) { BLOB blob = new BLOB((OracleConnection) dest, (byte[]) r.getRowData().get(columnName)); ((OraclePreparedStatement) ps).setBLOB(param, blob); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("CLOB")) { ((OraclePreparedStatement) ps).setStringForClob(param, (String) r.getRowData().get(columnName)); } else if (tableMetaData.getColumnsTypes().get(columnName).equalsIgnoreCase("LONG")) { ps.setBytes(param, (byte[]) r.getRowData().get(columnName)); } } else { ps.setObject(param, r.getRowData().get(columnName)); } param++; } for (String pkColumnName : tableMetaData.getPkColumns()) { ps.setObject(param, r.getRowData().get(pkColumnName)); param++; } if (ps.executeUpdate() != 1) { dest.rollback(); throw new Exception(); } ps.clearParameters(); } dest.commit(); dest.setAutoCommit(true); } finally { if (ps != null) ps.close(); } }
11
Code Sample 1: public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); } Code Sample 2: public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: public static boolean update(Funcionario objFuncionario) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "update funcionario " + " set nome = ? , cpf = ? , telefone = ? , email = ?, senha = ?, login = ?, id_cargo = ?" + " where id_funcionario = ?"; pst = c.prepareStatement(sql); pst.setString(1, objFuncionario.getNome()); pst.setString(2, objFuncionario.getCpf()); pst.setString(3, objFuncionario.getTelefone()); pst.setString(4, objFuncionario.getEmail()); pst.setString(5, objFuncionario.getSenha()); pst.setString(6, objFuncionario.getLogin()); pst.setLong(7, (objFuncionario.getCargo()).getCodigo()); pst.setLong(8, objFuncionario.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e1.getMessage()); } System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } } Code Sample 2: public static void main(String[] args) { FTPClient f = new FTPClient(); String host = "ftpdatos.aemet.es"; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); final String datestamp = sdf.format(new Date()); System.out.println(datestamp); String pathname = "datos_observacion/observaciones_diezminutales/" + datestamp + "_diezminutales/"; try { InetAddress server = InetAddress.getByName(host); f.connect(server); String username = "anonymous"; String password = "[email protected]"; f.login(username, password); FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() { @Override public boolean accept(FTPFile file) { return file.getName().startsWith(datestamp); } }); FTPFile file = files[files.length - 2]; f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); boolean download = false; String remote = pathname + "/" + file.getName(); if (download) { File out = new File("/home/randres/Desktop/" + file.getName()); FileOutputStream fout = new FileOutputStream(out); System.out.println(f.retrieveFile(remote, fout)); fout.flush(); fout.close(); } else { GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote)); LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250")); String line = null; while ((line = lreader.readLine()) != null) { Aeminuto.processLine(line); } lreader.close(); } f.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getproducts"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); HttpGet request1 = new HttpGet(SERVICE_URI + "/json/getroutes/3165"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient1 = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringID = new String(); String tempStringName = new String(); String tempStringPrice = new String(); String tempStringSymbol = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray; nameArray = json.getJSONArray("getProductsResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringID = nameArray.getJSONObject(i).getString("ID"); tempStringName = nameArray.getJSONObject(i).getString("Name"); tempStringPrice = nameArray.getJSONObject(i).getString("Price"); tempStringSymbol = nameArray.getJSONObject(i).getString("Symbol"); this.dm.insertIntoProducts(tempStringID, tempStringName, tempStringPrice, tempStringSymbol); tempString = nameArray.getJSONObject(i).getString("Name") + "\n" + nameArray.getJSONObject(i).getString("Price") + "\n" + nameArray.getJSONObject(i).getString("Symbol"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); } catch (Exception e) { e.printStackTrace(); } try { HttpResponse response1 = httpClient1.execute(request1); HttpEntity response1Entity = response1.getEntity(); InputStream stream1 = response1Entity.getContent(); BufferedReader reader1 = new BufferedReader(new InputStreamReader(stream1)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString1 = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder1 = new StringBuilder(); String line1; while ((line1 = reader1.readLine()) != null) { builder1.append(line1); } stream1.close(); theString = builder1.toString(); JSONObject json1 = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json1.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray1; nameArray1 = json1.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray1.length(); i++) { tempStringAgent = nameArray1.getJSONObject(i).getString("Agent"); tempStringClient = nameArray1.getJSONObject(i).getString("Client"); tempStringRoute = nameArray1.getJSONObject(i).getString("Route"); tempStringZone = nameArray1.getJSONObject(i).getString("Zone"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString1 = nameArray1.getJSONObject(i).getString("Client") + "\n" + nameArray1.getJSONObject(i).getString("Route") + "\n" + nameArray1.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString1)); } int orderCount1 = vectorOfStrings.size(); String[] orderTimeStamps1 = new String[orderCount1]; vectorOfStrings.copyInto(orderTimeStamps1); } catch (Exception a) { a.printStackTrace(); } } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
00
Code Sample 1: protected void performInsertTest() throws Exception { Connection conn = connect(); EntityDescriptor ed = repository.getEntityDescriptor(User.class); User testUser = new User(); Date now = new Date(); conn.setAutoCommit(false); testUser.setUsername("rednose"); testUser.setUCreated("dbUtilTest"); testUser.setUModified("dbUtilTest"); testUser.setDtCreated(now); testUser.setDtModified(now); String sql = dbUtil.genInsert(ed, testUser); Statement st = conn.createStatement(); long id = 0; System.err.println("Insert: " + sql); int rv = st.executeUpdate(sql, dbUtil.supportsGeneratedKeyQuery() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); if (rv > 0) { if (dbUtil.supportsGeneratedKeyQuery()) { ResultSet rs = st.getGeneratedKeys(); if (rs.next()) id = rs.getLong(1); } else { id = queryId(ed, now, "dbUtilTest", conn, dbUtil); } if (id > 0) testUser.setId(id); else rv = 0; } conn.rollback(); assertTrue("oups, insert failed?", id != 0); System.err.println("successfully created user with id #" + id + " temporarily"); } Code Sample 2: public static void copy(File file1, File file2) throws IOException { FileReader in = new FileReader(file1); FileWriter out = new FileWriter(file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: @Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } } Code Sample 2: private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; }
00
Code Sample 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(); } } Code Sample 2: public static String generateHashSE(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest md; md = MessageDigest.getInstance("SHA-256"); byte[] hashSHA256 = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md.digest(hashSHA256, 0, text.length()); return convertToHex(hashSHA256); }
11
Code Sample 1: @Test public void testWriteAndReadSecondLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile directory2 = new RFile(directory1, "directory2"); RFile file = new RFile(directory2, "testreadwrite2nd.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } } Code Sample 2: public static void copyFile(File source, File target) { try { target.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }