Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

In this page you can find the example usage for java.util StringTokenizer hasMoreElements.

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:org.eclipse.californium.proxy.HttpTranslator.java

public static Request createCoapRequestDiscovery(String proxyUri) throws TranslationException {
    // create the request -- since HTTP is reliable use CON
    Request coapRequest = new Request(Code.valueOf(1), Type.CON);

    String uri = "";
    if (proxyUri.contains("?")) {
        int index = proxyUri.indexOf("?");
        uri = proxyUri.substring(0, index);
    } else {/*  w  ww .j av a2  s .  c  om*/
        uri = proxyUri;
    }

    String uriNoSchema = uri.substring(7);
    int index = uriNoSchema.indexOf('/', 0);
    String host = uriNoSchema.substring(0, index);
    String resource = uriNoSchema.substring(index + 1);

    StringTokenizer tokenizer = new StringTokenizer(resource, "/");
    String resources = "";

    while (tokenizer.hasMoreElements()) {
        resources = (String) tokenizer.nextElement();
    }

    coapRequest.getOptions().setProxyUri("coap://" + host + "/.well-known/core?title=" + resources);

    // set the proxy as the sender to receive the response correctly
    try {
        // TODO check with multihomed hosts
        InetAddress localHostAddress = InetAddress.getLocalHost();
        coapRequest.setDestination(localHostAddress);
        // TODO: setDestinationPort???
    } catch (UnknownHostException e) {
        LOGGER.warning("Cannot get the localhost address: " + e.getMessage());
        throw new TranslationException("Cannot get the localhost address: " + e.getMessage());
    }

    return coapRequest;
}

From source file:us.mn.state.health.lims.result.action.ResultsEntryReflexTestPopupAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Result.
    // If there is a parameter present, we should bring up an existing
    // Result to edit.
    String id = request.getParameter(ID);
    String analysisId = (String) request.getParameter("analysisId");
    String listOfSelectedIds = (String) request.getParameter("listOfSelectedIds");
    //bugzilla 1684 
    String listOfSelectedIdAnalytes = (String) request.getParameter("listOfSelectedIdAnalytes");
    //bugzilla 1882
    String listOfSelectedIdAnalyses = (String) request.getParameter("listOfSelectedIdAnalyses");

    String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator();
    StringTokenizer st = new StringTokenizer(listOfSelectedIds, idSeparator);
    List selectedTestResultIds = new ArrayList();

    while (st.hasMoreElements()) {
        String trId = (String) st.nextElement();
        selectedTestResultIds.add(trId);
    }//  w w  w  .  j a v a2  s . co m

    //bugzilla 1684
    StringTokenizer st3 = new StringTokenizer(listOfSelectedIdAnalytes, idSeparator);
    List selectedTestAnalyteIds = new ArrayList();
    while (st3.hasMoreElements()) {
        String taId = (String) st3.nextElement();
        selectedTestAnalyteIds.add(taId);
    }

    //bugzilla 1882
    StringTokenizer st4 = new StringTokenizer(listOfSelectedIdAnalyses, idSeparator);
    List selectedAnalysisIds = new ArrayList();
    while (st4.hasMoreElements()) {
        String aId = (String) st4.nextElement();
        selectedAnalysisIds.add(aId);
    }

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    ResultsEntryReflexTestPopupActionForm dynaForm = (ResultsEntryReflexTestPopupActionForm) form;

    List listOfReflexTests = new ArrayList();
    List listOfReflexTestIds = new ArrayList();
    List listOfReflexTestsDisabledFlags = new ArrayList();
    List listOfParentResults = new ArrayList();
    // preload checkbox selection
    List preSelectedAddedTests = new ArrayList();
    List listOfParentAnalytes = new ArrayList();
    //bugzilla 1882
    List listOfParentAnalyses = new ArrayList();

    TestReflexDAO testReflexDAO = new TestReflexDAOImpl();
    TestResultDAO testResultDAO = new TestResultDAOImpl();
    TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl();
    AnalysisDAO analysisDAO = new AnalysisDAOImpl();

    for (int i = 0; i < selectedTestResultIds.size(); i++) {
        TestResult testResult = new TestResult();
        String testResultId = (String) selectedTestResultIds.get(i);
        testResult.setId(testResultId);
        testResultDAO.getData(testResult);

        //bugzilla 1684
        TestAnalyte testAnalyte = new TestAnalyte();
        String testAnalyteId = (String) selectedTestAnalyteIds.get(i);
        testAnalyte.setId(testAnalyteId);
        testAnalyteDAO.getData(testAnalyte);
        //bugzilla 1882
        Analysis parentAnalysis = new Analysis();
        String aId = (String) selectedAnalysisIds.get(i);
        parentAnalysis.setId(aId);
        analysisDAO.getData(parentAnalysis);

        //bugzilla 1684: added testAnalyte to criteria
        List reflexes = testReflexDAO.getTestReflexesByTestResultAndTestAnalyte(testResult, testAnalyte);
        if (reflexes != null) {
            for (int j = 0; j < reflexes.size(); j++) {
                TestReflex testReflex = (TestReflex) reflexes.get(j);
                String testReflexId = testReflex.getId();
                testReflex.setId(testReflexId);
                testReflexDAO.getData(testReflex);

                if (testReflex != null && testReflex.getAddedTest() != null) {
                    Test addedTest = (Test) testReflex.getAddedTest();
                    if (addedTest.getId() != null) {
                        listOfReflexTestsDisabledFlags.add(NO);
                        preSelectedAddedTests.add(addedTest.getId());
                    }
                    //bugzilla 1684 - check to see if a different result
                    //already generated this reflex test
                    //only add it if not
                    //bugzilla 1802 - display all reflex tests even if
                    //already generated by diff. result
                    //if (!listOfReflexTestIds.contains(addedTest.getId())) {
                    listOfReflexTests.add(addedTest);
                    listOfReflexTestIds.add(addedTest.getId());
                    //}               
                    listOfParentResults.add(testResult);
                    listOfParentAnalytes.add(testAnalyte);
                    //bugzilla 1882
                    listOfParentAnalyses.add(parentAnalysis);
                }
            }
        }
    }

    // initialize the form
    dynaForm.initialize(mapping);

    PropertyUtils.setProperty(dynaForm, "listOfReflexTests", listOfReflexTests);

    PropertyUtils.setProperty(dynaForm, "listOfReflexTestsDisabledFlags", listOfReflexTestsDisabledFlags);
    PropertyUtils.setProperty(dynaForm, "listOfParentResults", listOfParentResults);
    PropertyUtils.setProperty(dynaForm, "listOfParentAnalytes", listOfParentAnalytes);
    //bugzilla 1882
    PropertyUtils.setProperty(dynaForm, "listOfParentAnalyses", listOfParentAnalyses);
    int numberOfPreselectedItems = preSelectedAddedTests.size();
    String[] selectedAddedTests = new String[numberOfPreselectedItems];
    for (int i = 0; i < preSelectedAddedTests.size(); i++) {
        String testId = (String) preSelectedAddedTests.get(i);
        selectedAddedTests[i] = testId;
    }
    PropertyUtils.setProperty(dynaForm, "selectedAddedTests", selectedAddedTests);

    return mapping.findForward(forward);
}

From source file:controller.servlet.PostServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w  w w. java  2s  . c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    PostDAOService postService = PostDAO.getInstance();
    String title = null;
    String shortTitle = null;
    String sCategoryID = null;
    String content = null;
    String link = null;
    String action = null;
    // String pathImage;
    String imageName = "";
    boolean isUploadSuccess = false;
    ServletFileUpload fileUpload = new ServletFileUpload();
    try {
        FileItemIterator itr = fileUpload.getItemIterator(request);
        while (itr.hasNext()) {
            FileItemStream fileItemStream = itr.next();
            if (fileItemStream.isFormField()) {
                String fieldName = fileItemStream.getFieldName();
                InputStream is = fileItemStream.openStream();

                byte[] b = new byte[is.available()];
                is.read(b);
                String value = new String(b, "UTF-8");
                if (fieldName.equals("action")) {
                    action = value;
                }
                if (fieldName.equals("title")) {
                    title = value;
                }
                if (fieldName.equals("content")) {
                    content = value;
                }
                if (fieldName.equals("short-title")) {
                    shortTitle = value;
                }
                if (fieldName.equals("category-id")) {
                    sCategoryID = value;
                }
                if (fieldName.equals("link")) {
                    link = value;
                }

            } else {
                String realPath = getServletContext().getRealPath("/");
                String filePath = realPath.replace("\\build\\web", "\\web\\image\\post");//Duong dan luu file anh
                imageName = fileItemStream.getName();
                StringTokenizer token = new StringTokenizer(imageName, ".");
                String fileNameExtension = "";
                while (token.hasMoreElements()) {
                    fileNameExtension = token.nextElement().toString();
                }
                System.out.println("img: " + imageName);
                if (!imageName.equals("")) {
                    imageName = Support.randomString();
                    isUploadSuccess = FileUpload.processFile(filePath, fileItemStream, imageName,
                            fileNameExtension);
                    imageName += "." + fileNameExtension;
                }
            }
        }
        Post currentPost = new Post();
        currentPost.setPostID(postService.nextID());
        currentPost.setTitle(title);
        currentPost.setShortTitle(shortTitle);
        currentPost.setCategory(new Category(Integer.valueOf(sCategoryID), "", false));
        currentPost.setContent(content);
        currentPost.setDatePost(Support.getDatePost());
        currentPost.setUser((User) request.getSession().getAttribute(Constants.CURRENT_USER));
        currentPost.setLink(link);
        currentPost.setActive(false);
        request.setAttribute(Constants.CURRENT_POST, currentPost);
        request.setAttribute(Constants.LIST_CATEGORY, CategoryDAO.getInstance().getCategories());
        if (action != null) {
            switch (action) {
            case "up-load":
                upLoad(request, response, imageName, isUploadSuccess);
                break;
            case "add-topic":
                addTopic(request, response, currentPost);
                break;
            }
        }
    } catch (IOException | org.apache.tomcat.util.http.fileupload.FileUploadException e) {
        response.getWriter().println(e.toString());
    }
}

From source file:com.sfs.dao.bugreport.JiraBugReportHandler.java

/**
 * Submit the bug report./*from  w w w  .  j  a v a  2  s. c o m*/
 *
 * @param bugReport the bug report to submit
 *
 * @throws SFSDaoException the sfs dao exception
 */
public final void submitReport(final BugReportBean bugReport) throws SFSDaoException {
    if (bugReport == null) {
        throw new SFSDaoException("BugReportBean cannot be null");
    }
    if (jiraBaseUrl == null) {
        throw new SFSDaoException("The Jira base url cannot be null");
    }
    if (jiraUsername == null) {
        throw new SFSDaoException("The Jira username cannot be null");
    }
    if (jiraPassword == null) {
        throw new SFSDaoException("The Jira password cannot be null");
    }
    if (bugReport.getUser() == null) {
        throw new SFSDaoException("Submission of a bug report requires a valid user object");
    }
    if (bugReport.getReportClass() == null) {
        throw new SFSDaoException("The bug report class cannot be null");
    }

    final String jiraReportUrl = buildUrl(XMLRPC_ENDPOINT);

    Hashtable<String, String> issue = new Hashtable<String, String>();

    /** Set the bug report type url parameters **/
    String bugTypeParameters = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Type", bugReport.getReportType(),
                bugReport.getReportClass());
        bugTypeParameters = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    // Convert this string of bug report parameters to the array
    if (StringUtils.isNotBlank(bugTypeParameters)) {
        StringTokenizer st = new StringTokenizer(bugTypeParameters, "&");

        while (st.hasMoreElements()) {
            final String option = st.nextToken();
            final String parameter = option.substring(0, option.indexOf("="));
            final String value = option.substring(option.indexOf("=") + 1, option.length());

            logger.debug("Parameter: " + parameter + ", value: " + value);
            issue.put(parameter, value);
        }
    }

    /** Set the bug priority url parameters **/
    String priority = "";
    try {
        ObjectTypeBean objectType = this.objectTypeDAO.load("Bug Report Priority", "", bugReport.getPriority());
        priority = StringUtils.replace(objectType.getAbbreviation(), "&amp;", "&");
    } catch (SFSDaoException sde) {
        throw new SFSDaoException("Error submitting Jira report: " + sde.getMessage());
    }
    issue.put("priority", priority);

    /** Set the summary **/
    if (StringUtils.isBlank(bugReport.getTitle())) {
        bugReport.setTitle("Untitled issue");
    }
    issue.put("summary", bugReport.getTitle());

    /** Set the description **/
    issue.put("description", bugReport.getDescription());

    /** The username of the reporter **/
    issue.put("reporter", bugReport.getUser().getUserName().toLowerCase());

    /** Set the assignee - if none default set to automatic **/
    if (StringUtils.isNotBlank(this.jiraAssignee)) {
        issue.put("assignee", this.jiraAssignee);
    } else {
        // Set to automatic (-1 in Jira)
        issue.put("assignee", "-1");
    }

    if (!debugMode) {
        /** Post the bug report to Jira **/
        try {
            logger.info("Jira Report - submitting");
            logger.info("Jira URL: " + jiraReportUrl.toString());
            logger.info("Jira Parameters: " + issue.toString());

            final String response = this.performRestRequest(jiraReportUrl.toString(), issue);

            logger.info("Jira response: " + response);

        } catch (XmlRpcException xre) {
            throw new SFSDaoException("Error submitting Jira report via XMLRPC: " + xre.getMessage());
        } catch (MalformedURLException mue) {
            throw new SFSDaoException("Error with the Jira XMLRPC URL: " + mue.getMessage());
        }
    } else {
        logger.debug("Jira Report - debug mode");
        logger.debug("Jira URL: " + jiraReportUrl.toString());
        logger.debug("Jira Parameters: " + issue.toString());
    }
}

From source file:io.hops.leaderElection.experiments.ExperimentDriver.java

private void runCommands(String file) throws FileNotFoundException, IOException, InterruptedException {
    if (!new File(file).exists()) {
        LOG.error("File Does not exists");
        return;/*from ww w.  j  av a2 s .  com*/
    }

    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.startsWith("#") || line.trim().isEmpty()) {
            continue;
        }

        StringTokenizer st = new StringTokenizer(line, " ");
        int numProcesses = -1;
        String timeToRep = st.nextToken();
        int timesToRepeat = Integer.parseInt(timeToRep);
        line = line.substring(timeToRep.length(), line.length());
        String outputFileName = null;

        while (st.hasMoreElements()) {
            if (st.nextElement().equals("-max_processes")) {
                numProcesses = Integer.parseInt(st.nextToken());
                outputFileName = numProcesses + ".log";
                break;
            }
        }
        LOG.info("Going to repeat the experiment of " + timesToRepeat + " times");
        for (int i = 0; i < timesToRepeat; i++) { // run command 10 times
            String command = line + " -output_file_path " + outputFileName;
            LOG.info("Driver going to run command " + command);
            runCommand(command);
        }

        LOG.info("Going to calculate points from file " + outputFileName);
        calculateNumbers(numProcesses, outputFileName);
    }
    br.close();
}

From source file:org.apache.jcs.auxiliary.lateral.http.server.AbstractDeleteCacheServlet.java

/** Description of the Method */
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (!authenticator.authenticate(req, res)) {
        return;/* ww w .  java2s.c o  m*/
    }
    Hashtable params = new Hashtable();
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    try {
        String paramName;
        String paramValue;

        // GET PARAMETERS INTO HASHTABLE
        for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
            paramName = (String) e.nextElement();
            paramValue = req.getParameter(paramName);
            params.put(paramName, paramValue);
            if (log.isDebugEnabled()) {
                log.debug(paramName + "=" + paramValue);
            }
        }
        String hashtableName = req.getParameter("hashtableName");
        String key = req.getParameter("key");

        if (hashtableName == null) {
            hashtableName = req.getParameter("cacheName");
        }
        out.println("<html><body bgcolor=#FFFFFF>");

        if (hashtableName != null) {

            if (log.isDebugEnabled()) {
                log.debug("hashtableName = " + hashtableName);
            }
            out.println("(Last hashtableName = " + hashtableName + ")");

            if (hashtableName.equals("ALL")) {

                // Clear all caches.
                String[] list = cacheMgr.getCacheNames();
                Arrays.sort(list);

                for (int i = 0; i < list.length; i++) {
                    String name = list[i];
                    ICache cache = cacheMgr.getCache(name);
                    cache.removeAll();
                }
                out.println("All caches have been cleared!");
            } else {

                ICache cache = cacheMgr.getCache(hashtableName);

                String task = (String) params.get("task");
                if (task == null) {
                    task = "delete";
                }

                if (task.equalsIgnoreCase("stats")) {

                    //                        out.println( "<br><br>" );
                    //                        out.println( "<b>Stats for " + hashtableName + ":</b><br>" );
                    //                        out.println( cache.getStats() );
                    //                        out.println( "<br>" );

                } else {

                    // Remove the specified cache.

                    if (key != null) {
                        if (key.toUpperCase().equals("ALL")) {
                            cache.removeAll();

                            if (log.isDebugEnabled()) {
                                log.debug("Removed all elements from " + hashtableName);
                            }
                            out.println("key = " + key);
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("key = " + key);
                            }
                            out.println("key = " + key);
                            StringTokenizer toke = new StringTokenizer(key, "_");

                            while (toke.hasMoreElements()) {
                                String temp = (String) toke.nextElement();
                                cache.remove(key);

                                if (log.isDebugEnabled()) {
                                    log.debug("Removed " + temp + " from " + hashtableName);
                                }
                            }
                        }
                    } else {
                        out.println("key is null");
                    }

                }
                // end is task == delete

            }
        } else {
            out.println("(No hashTableName specified.)");
        }

        // PRINT OUT MENU
        out.println("<br>");
        int antiCacheRandom = (int) (10000.0 * Math.random());
        out.println("<a href=?antiCacheRandom=" + antiCacheRandom + ">List all caches</a><br>");
        out.println("<br>");
        out.println("<a href=?hashtableName=ALL&key=ALL&antiCacheRandom=" + antiCacheRandom
                + "><font color=RED>Clear All Cache Regions</font></a><br>");
        out.println("<br>");
        String[] list = cacheMgr.getCacheNames();
        Arrays.sort(list);
        out.println("<div align=CENTER>");
        out.println("<table border=1 width=80%>");
        out.println("<tr bgcolor=#eeeeee><td>Cache Region Name</td><td>Size</td><td>Status</td><td>Stats</td>");
        for (int i = 0; i < list.length; i++) {
            String name = list[i];
            out.println("<tr><td><a href=?hashtableName=" + name + "&key=ALL&antiCacheRandom=" + antiCacheRandom
                    + ">" + name + "</a></td>");
            ICache cache = cacheMgr.getCache(name);
            out.println("<td>");
            out.print(cache.getSize());
            out.print("</td><td>");
            int status = cache.getStatus();
            out.print(status == CacheConstants.STATUS_ALIVE ? "ALIVE"
                    : status == CacheConstants.STATUS_DISPOSED ? "DISPOSED"
                            : status == CacheConstants.STATUS_ERROR ? "ERROR" : "UNKNOWN");
            out.print("</td>");
            out.println("<td><a href=?task=stats&hashtableName=" + name + "&key=NONE&antiCacheRandom="
                    + antiCacheRandom + ">stats</a></td>");
        }
        out.println("</table>");
        out.println("</div>");
    }
    //CATCH EXCEPTIONS
    catch (Exception e) {
        log.error(e);
        //log.logIt( "hashtableName = " + hashtableName );
        //log.logIt( "key = " + key );
    }
    // end try{
    finally {
        String isRedirect = (String) params.get("isRedirect");
        if (isRedirect == null) {
            isRedirect = "N";
        }
        if (log.isDebugEnabled()) {
            log.debug("isRedirect = " + isRedirect);
        }
        String url;
        if (isRedirect.equals("Y")) {
            url = (String) params.get("url");
            if (log.isDebugEnabled()) {
                log.debug("url = " + url);
            }
            res.sendRedirect(url);
            // will not work if there's a previously sent header
            out.println("<br>\n");
            out.println(" <script>");
            out.println(" location.href='" + url + "'; ");
            out.println(" </script> ");
            out.flush();
        } else {
            url = "";
        }
        out.println("</body></html>");
    }
}

From source file:org.codehaus.mojo.fitnesse.FitnesseAbstractMojoTest.java

private void compareTransformFile(InputStream pSrcFile, InputStream pExpectedFile, String pOutputFileName,
        String pStatus) throws FileNotFoundException, IOException, MojoExecutionException {
    String tExpected = FileUtil.getString(pExpectedFile);
    ByteArrayOutputStream tTransform = new ByteArrayOutputStream();
    MojoTest tMojo = getMojo((Log) mMockLog.proxy());
    tMojo.transformHtml(pSrcFile, new OutputStreamWriter(tTransform), pOutputFileName, pStatus);
    StringTokenizer tTokExp = new StringTokenizer(tExpected, "\n");
    StringTokenizer tTokRes = new StringTokenizer(tTransform.toString(), "\n");
    while (tTokExp.hasMoreElements()) {
        String tExpectToken = tTokExp.nextToken();
        String tResultToken = tTokRes.nextToken();
        if (tExpectToken.indexOf(WILD_CART) >= 0) {
            int tStartIndex = tExpectToken.indexOf(WILD_CART);
            assertEquals(tExpectToken.substring(0, tStartIndex), tResultToken.substring(0, tStartIndex));
            int tEndIndex = tExpectToken.lastIndexOf(WILD_CART) + WILD_CART.length();
            String tEndExpectected = tExpectToken.substring(tEndIndex, tExpectToken.length());
            String tEndResult = tResultToken.substring(tEndIndex, tResultToken.length());
            assertEquals(tEndExpectected, tEndResult);
        } else {/*from   www .ja v a2 s .  c  o m*/
            assertEquals(tExpectToken, tResultToken);
        }

    }
    assertFalse(tTokRes.hasMoreElements());
}

From source file:gtu._work.ui.ObnfExceptionLogDownloadUI.java

private void downloadBtnAction() {
    try {//  ww  w  .  j a  v a2 s .  com
        FtpSite ftpSite = (FtpSite) siteFtpComboBox.getSelectedItem();
        if (ftpSite == null) {
            JCommonUtil._jOptionPane_showMessageDialog_error("?");
            return;
        }
        String messageIdAreaText = messageIdArea.getText();
        if (StringUtils.isBlank(messageIdAreaText)) {
            JCommonUtil._jOptionPane_showMessageDialog_error("MessageId");
            return;
        }
        String destDirStr = exportTextField.getText();
        if (StringUtils.isBlank(destDirStr)) {
            JCommonUtil._jOptionPane_showMessageDialog_error("");
            return;
        }
        File destDir = new File(destDirStr);
        if (!destDir.exists() || !destDir.isDirectory()) {
            JCommonUtil._jOptionPane_showMessageDialog_error("??");
            return;
        }
        List<String> findList = new ArrayList<String>();
        StringTokenizer tok = new StringTokenizer(messageIdAreaText);
        while (tok.hasMoreElements()) {
            String messageId = (String) tok.nextElement();
            findList.add(messageId);
        }
        logArea.setText("");
        FtpUtil ftpUtil = new FtpUtil();
        ftpUtil.connect(ftpSite.ip, ftpSite.port, ftpSite.userId, ftpSite.password, false);

        List<FtpFileInfo> fileList = new ArrayList<FtpFileInfo>();
        ftpUtil.scanFindFile(ftpSite.path, ".*", fileList, ftpUtil.getFtp());
        for (FtpFileInfo f : fileList) {
            System.out.println("===>" + f.getAbsolutePath());
        }

        List<FtpFileInfo> findOkList = new ArrayList<FtpFileInfo>();
        for (FtpFileInfo f : fileList) {
            for (int ii = 0; ii < findList.size(); ii++) {
                String messageId = findList.get(ii);
                if (f.getName().contains(messageId)) {
                    findOkList.add(f);
                    findList.remove(ii);
                    ii--;
                    break;
                }
            }
        }

        StringBuffer sb = new StringBuffer();
        for (FtpFileInfo f : findOkList) {
            File downloadFile = new File(destDir, f.getName());
            sb.append("ftp:" + f.getAbsolutePath() + "\n");
            ftpUtil.getFile(f.getAbsolutePath(), new FileOutputStream(downloadFile));
            sb.append(":" + downloadFile + "\n");
        }
        ftpUtil.disconnect();

        for (String messageId : findList) {
            sb.append(messageId + " - ?\n");
        }

        logArea.setText(sb.toString());
        JCommonUtil._jOptionPane_showMessageDialog_info("?, log");
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
        File f = new File(FileUtil.DESKTOP_DIR, "test_log_001.log");
        try {
            PrintWriter pw = new PrintWriter(new FileOutputStream(f));
            ex.printStackTrace(pw);
            pw.flush();
            pw.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

From source file:josejamilena.pfc.servidor.chartserver.ClientHandler.java

/**
 * Mtodo que ejecuta el Thread./*from www  . j av a 2s.co  m*/
 */
@Override
public void run() {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(miSocketServidor.getInputStream()));
        PrintStream out = new PrintStream(new BufferedOutputStream(miSocketServidor.getOutputStream()));

        String s = in.readLine();
        // System.out.println(s);  // Salida para el Log

        // Atiende a servir archivos.
        String filename = "";
        StringTokenizer st = new StringTokenizer(s);
        try {

            // Parsea la peticin desde el comando GET
            if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements()) {
                filename = st.nextToken();
            } else {
                throw new FileNotFoundException();
            }
            // Aade "/" with "index.html"
            if (filename.endsWith("/")) {
                filename += nombreFichero;
            }
            // Quita / del nombre del archivo
            while (filename.indexOf("/") == 0) {
                filename = filename.substring(1);
            }
            // Reemplaza "/" por "\" en el path para servidores en Win32
            filename = filename.replace('/', File.separator.charAt(0));

            /* Comprueba caracteres no permitidos,
             para impedir acceder a directorios superiores */
            if ((filename.indexOf("..") >= 0) || (filename.indexOf(':') >= 0) || (filename.indexOf('|') >= 0)) {
                throw new FileNotFoundException();
            }
            // Si la peticin de acceso a un directorio no tiene "/",
            // envia al cliente un respuesta HTTP
            if (new File(filename).isDirectory()) {
                filename = filename.replace('\\', '/');
                out.print(
                        "HTTP/1.0 301 Movido permantemente \r\n" + "Albergado en: /" + filename + "/\r\n\r\n");
                out.close();
                return;
            }
            // Abriendo el archivo (puede lanzar FileNotFoundException)
            InputStream f = new FileInputStream(filename);
            // Determina el tipe MIME e imprime la cabecera HTTP
            String mimeType = "text/plain";
            if (filename.endsWith(".html") || filename.endsWith(".htm")) {
                mimeType = "text/html";
            } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                mimeType = "image/jpeg";
            } else if (filename.endsWith(".gif")) {
                mimeType = "image/gif";
            } else if (filename.endsWith(".class")) {
                mimeType = "application/octet-stream";
            } else if (filename.endsWith(".jnlp")) {
                mimeType = "application/x-java-jnlp-file";
            }
            out.print("HTTP/1.0 200 OK\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n" + "Content-type: "
                    + mimeType + "\r\n\r\n");
            // Envia el fichero ala cliente, y cierra la conexin
            byte[] a = new byte[bufferSize];
            int n;
            while ((n = f.read(a)) > 0) {
                out.write(a, 0, n);
            }
            f.close();
            out.close();
        } catch (FileNotFoundException x) {
            out.println("HTTP/1.0 404 No encontrado.\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n"
                    + "Content-type: text/html\r\n\r\n" + "<html><head></head><body>" + "El fichero " + filename
                    + " no ha sido encontrado.</body></html>\n");
            out.close();
        }
    } catch (IOException x) {
        System.out.println(x);
    } finally {
        File aborrar = new File(nombreFichero);
        org.apache.commons.io.FileUtils.deleteQuietly(aborrar);
    }
}

From source file:org.opentestsystem.delivery.testreg.upload.FileUploadUtils.java

/**
 * Converting accommodationData( accommodation upload data ) to accommodationMap
 * //from   w ww  .j  a  va  2  s .  co m
 * @param columns               accommodation data from upload file 
 * @param headers               list of all accommodation resource codes 
 * @param headerResourceTypes   masterResourceAccommodation map with key : resourceCode and value : resourceType
 * @return map with data( values ) assigned to its corresponding resource codes(key)
 */
@SuppressWarnings("unchecked")
private Map<String, Object> convertDataToMap(Object[] columns, List<String> headers,
        HashMap<String, String> headerResourceTypes) {

    HashMap<String, Object> accommodationMap = new LinkedHashMap<String, Object>();
    HashMap<String, Object> data = new LinkedHashMap<String, Object>();
    for (String columnHeader : headers) {
        if (columnHeader.equalsIgnoreCase("subject") || columnHeader.equalsIgnoreCase("stateAbbreviation")) {
            accommodationMap.put(columnHeader, columns[headers.indexOf(columnHeader)].toString().toUpperCase());
        } else if (columnHeader.equalsIgnoreCase("studentId")) {
            accommodationMap.put(columnHeader, columns[headers.indexOf(columnHeader)].toString());
        }
    }
    String allAccommodationCodes = columns[3].toString();
    List<String> accommodationCode = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(allAccommodationCodes, "|");
    while (tokenizer.hasMoreElements()) {
        String token = (String) tokenizer.nextElement();
        accommodationCode.add(token.trim());
    }

    HashMap<String, List<String>> masterAccommodationOptions = masterResourceAccommodationService
            .getMasterResourceOptions();

    Set<String> masterCodes = masterAccommodationOptions.keySet();
    for (String uploadCode : accommodationCode) {
        for (String resourceCode : masterCodes) {
            ArrayList<String> options = new ArrayList<String>();
            if (uploadCode.contains("(") && uploadCode.contains(")")) {
                int startIndex = (uploadCode.indexOf("(")) + 1;
                int endIndex = (uploadCode.indexOf(")"));
                String editResource = uploadCode.substring(startIndex, endIndex);
                String matchResource = uploadCode.substring(0, uploadCode.indexOf("("));
                if (resourceCode.equalsIgnoreCase(matchResource)) {
                    data.put(resourceCode, editResource);
                    break;
                }
            } else {
                if (masterAccommodationOptions.get(resourceCode).contains(uploadCode)) {
                    String key = ARTHelpers.convertCodeToUpperCase(resourceCode);
                    if (headerResourceTypes.containsKey(key) && headerResourceTypes.get(key)
                            .equals(AccommodationResourceType.MultiSelectResource.name())) {
                        if (data.containsKey(resourceCode)) {
                            ArrayList<String> tempResourceCodes = (ArrayList<String>) data.get(resourceCode);
                            if (tempResourceCodes != null) {
                                tempResourceCodes.add(uploadCode);
                                data.put(resourceCode, tempResourceCodes);
                                break;
                            }
                        } else {
                            options.add(uploadCode);
                            data.put(resourceCode, options);
                            break;
                        }
                    } else {
                        data.put(resourceCode, uploadCode);
                        break;
                    }
                }
            }
        }
    }
    for (String resourceCode : masterAccommodationOptions.keySet()) {
        Set<String> accommodationResourceCodes = data.keySet();
        if (accommodationResourceCodes.contains(resourceCode)) {
            String key = ARTHelpers.convertToLowerCase(resourceCode);
            accommodationMap.put(key, data.get(resourceCode));
        } else {
            if (headerResourceTypes.containsKey(resourceCode) && headerResourceTypes.get(resourceCode)
                    .equals(AccommodationResourceType.MultiSelectResource.name())) {
                ArrayList<String> accommoList = new ArrayList<String>();
                accommodationMap.put(ARTHelpers.convertToLowerCase(resourceCode), accommoList);
            } else {
                accommodationMap.put(ARTHelpers.convertToLowerCase(resourceCode), "");
            }

        }
    }

    return accommodationMap;
}