Example usage for java.lang NullPointerException toString

List of usage examples for java.lang NullPointerException toString

Introduction

In this page you can find the example usage for java.lang NullPointerException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.prom5.analysis.performance.PerformanceAnalysisGUI.java

/**
 * Creates dialogs in which the user can change the percentages of
 * (place or time-in-between) measurements to be counted as fast-slow-normal
 * and adjusts the metrics to these percentages.
 *//*w w  w.ja  v a  2 s  .co  m*/
private void changeObjectPercentages() {
    if (elt1 instanceof ExtendedPlace) {
        //a place was selected
        //Create a dialog in which the user can fill in the percentage of
        //measurements that is counted as 'fast'
        String perc = JOptionPane.showInputDialog(this,
                "Enter the percentage of measurements\n" + " that is to be counted as 'fast': ");
        if (perc != null) {
            //Cancel button was not pressed
            try {
                fastestPlacePercentage = Double.parseDouble(perc);
                //check if the entered value is between 0 and 100
                if (fastestPlacePercentage < 0 || fastestPlacePercentage > 100) {
                    fastestPlacePercentage = 0;
                }
            } catch (Exception e) {
                //the entered string was not an integer-value
                Message.add("Exception: " + e.toString(), 2);
                fastestPlacePercentage = 0;
            }
            //Create a dialog in which the user can fill in the percentage of
            //measurements that is counted as 'slow'
            String perc2 = JOptionPane.showInputDialog(this,
                    "Enter the percentage of measurements\n" + " that is to be counted as 'slow': ");
            if (perc2 != null) {
                //Cancel was not pressed
                try {
                    slowestPlacePercentage = Double.parseDouble(perc2);
                    //check if the entered value is between 0 and 100 and if
                    //fastest + slowpercentage is below or equal to 100
                    if (slowestPlacePercentage < 0 || slowestPlacePercentage > 100
                            || (slowestPlacePercentage + fastestPlacePercentage) > 100) {
                        slowestPlacePercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    slowestPlacePercentage = 0;
                }
            }
            //display the place metrics
            displayPlaceMetrics((ExtendedPlace) elt1);
        }
    } else {
        if (elt2 instanceof ExtendedTransition) {
            //two transitions selected
            String perc = JOptionPane.showInputDialog(this,
                    "Enter the percentage of cases that is to be" + " counted as 'fast': ");
            if (perc != null) {
                try {
                    fastestBetweenPercentage = Double.parseDouble(perc);
                    if (fastestBetweenPercentage < 0 || fastestBetweenPercentage > 100) {
                        fastestBetweenPercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    fastestBetweenPercentage = 0;
                }
                String perc2 = JOptionPane.showInputDialog(this,
                        "Enter the percentage of cases that is to be" + " counted as 'slow': ");
                if (perc2 != null) {
                    try {
                        slowestBetweenPercentage = Double.parseDouble(perc2);
                        if (slowestBetweenPercentage < 0 || slowestBetweenPercentage > 100
                                || (slowestBetweenPercentage + fastestBetweenPercentage) > 100) {
                            slowestBetweenPercentage = 0;
                        }
                    } catch (Exception e) {
                        Message.add("Exception: " + e.toString(), 2);
                        slowestBetweenPercentage = 0;
                    }
                }
                ExtendedTransition otherTrans = (ExtendedTransition) elt1;
                ExtendedTransition lastTrans = (ExtendedTransition) elt2;

                //display the transition metrics
                displayTransitionMetrics(lastTrans, otherTrans);
            }
        } else {
            //one transition selected
            //if not a place selected, then one or two transitions selected
            String perc = JOptionPane.showInputDialog(this,
                    "Enter the percentage of measurements that is to be" + " counted as 'fast': ");
            if (perc != null) {
                try {
                    fastestActivityPercentage = Double.parseDouble(perc);
                    if (fastestActivityPercentage < 0 || fastestActivityPercentage > 100) {
                        fastestActivityPercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    fastestActivityPercentage = 0;
                }
                String perc2 = JOptionPane.showInputDialog(this,
                        "Enter the percentage of measurements that is" + " to be counted as 'slow': ");
                if (perc2 != null) {
                    try {
                        slowestActivityPercentage = Double.parseDouble(perc2);
                        if (slowestActivityPercentage < 0 || slowestActivityPercentage > 100
                                || (slowestActivityPercentage + fastestActivityPercentage) > 100) {
                            slowestActivityPercentage = 0;
                        }
                    } catch (Exception e) {
                        Message.add("Exception: " + e.toString(), 2);
                        slowestActivityPercentage = 0;
                    }
                }
                ExtendedTransition trans = (ExtendedTransition) elt1;
                //display the transition metrics
                try {
                    displayActivityMetrics(trans.getAssociatedActivity());
                } catch (NullPointerException npe) {
                    Message.add("No activity related to the selected transition.\n" + npe.toString(), 2);
                }
            }
        }
    }
}

From source file:org.processmining.analysis.performance.PerformanceAnalysisGUI.java

/**
 * Creates dialogs in which the user can change the percentages of (place or
 * time-in-between) measurements to be counted as fast-slow-normal and
 * adjusts the metrics to these percentages.
 *///from  w w w.java 2s .c  o  m
private void changeObjectPercentages() {
    if (elt1 instanceof ExtendedPlace) {
        // a place was selected
        // Create a dialog in which the user can fill in the percentage of
        // measurements that is counted as 'fast'
        String perc = JOptionPane.showInputDialog(this,
                "Enter the percentage of measurements\n" + " that is to be counted as 'fast': ");
        if (perc != null) {
            // Cancel button was not pressed
            try {
                fastestPlacePercentage = Double.parseDouble(perc);
                // check if the entered value is between 0 and 100
                if (fastestPlacePercentage < 0 || fastestPlacePercentage > 100) {
                    fastestPlacePercentage = 0;
                }
            } catch (Exception e) {
                // the entered string was not an integer-value
                Message.add("Exception: " + e.toString(), 2);
                fastestPlacePercentage = 0;
            }
            // Create a dialog in which the user can fill in the percentage
            // of
            // measurements that is counted as 'slow'
            String perc2 = JOptionPane.showInputDialog(this,
                    "Enter the percentage of measurements\n" + " that is to be counted as 'slow': ");
            if (perc2 != null) {
                // Cancel was not pressed
                try {
                    slowestPlacePercentage = Double.parseDouble(perc2);
                    // check if the entered value is between 0 and 100 and
                    // if
                    // fastest + slowpercentage is below or equal to 100
                    if (slowestPlacePercentage < 0 || slowestPlacePercentage > 100
                            || (slowestPlacePercentage + fastestPlacePercentage) > 100) {
                        slowestPlacePercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    slowestPlacePercentage = 0;
                }
            }
            // display the place metrics
            displayPlaceMetrics((ExtendedPlace) elt1);
        }
    } else {
        if (elt2 instanceof ExtendedTransition) {
            // two transitions selected
            String perc = JOptionPane.showInputDialog(this,
                    "Enter the percentage of cases that is to be" + " counted as 'fast': ");
            if (perc != null) {
                try {
                    fastestBetweenPercentage = Double.parseDouble(perc);
                    if (fastestBetweenPercentage < 0 || fastestBetweenPercentage > 100) {
                        fastestBetweenPercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    fastestBetweenPercentage = 0;
                }
                String perc2 = JOptionPane.showInputDialog(this,
                        "Enter the percentage of cases that is to be" + " counted as 'slow': ");
                if (perc2 != null) {
                    try {
                        slowestBetweenPercentage = Double.parseDouble(perc2);
                        if (slowestBetweenPercentage < 0 || slowestBetweenPercentage > 100
                                || (slowestBetweenPercentage + fastestBetweenPercentage) > 100) {
                            slowestBetweenPercentage = 0;
                        }
                    } catch (Exception e) {
                        Message.add("Exception: " + e.toString(), 2);
                        slowestBetweenPercentage = 0;
                    }
                }
                ExtendedTransition otherTrans = (ExtendedTransition) elt1;
                ExtendedTransition lastTrans = (ExtendedTransition) elt2;

                // display the transition metrics
                displayTransitionMetrics(lastTrans, otherTrans);
            }
        } else {
            // one transition selected
            // if not a place selected, then one or two transitions selected
            String perc = JOptionPane.showInputDialog(this,
                    "Enter the percentage of measurements that is to be" + " counted as 'fast': ");
            if (perc != null) {
                try {
                    fastestActivityPercentage = Double.parseDouble(perc);
                    if (fastestActivityPercentage < 0 || fastestActivityPercentage > 100) {
                        fastestActivityPercentage = 0;
                    }
                } catch (Exception e) {
                    Message.add("Exception: " + e.toString(), 2);
                    fastestActivityPercentage = 0;
                }
                String perc2 = JOptionPane.showInputDialog(this,
                        "Enter the percentage of measurements that is" + " to be counted as 'slow': ");
                if (perc2 != null) {
                    try {
                        slowestActivityPercentage = Double.parseDouble(perc2);
                        if (slowestActivityPercentage < 0 || slowestActivityPercentage > 100
                                || (slowestActivityPercentage + fastestActivityPercentage) > 100) {
                            slowestActivityPercentage = 0;
                        }
                    } catch (Exception e) {
                        Message.add("Exception: " + e.toString(), 2);
                        slowestActivityPercentage = 0;
                    }
                }
                ExtendedTransition trans = (ExtendedTransition) elt1;
                // display the transition metrics
                try {
                    displayActivityMetrics(trans.getAssociatedActivity());
                } catch (NullPointerException npe) {
                    Message.add("No activity related to the selected transition.\n" + npe.toString(), 2);
                }
            }
        }
    }
}

From source file:com.FFLive.MySQLConnection.java

public Map<String, List<String>> statusCheck() {
    Main.log.log(4, "Checking Status of Stored Leagues...  ");
    Map<String, List<String>> incomplete = new HashMap<String, List<String>>();

    try {/*  w  w w . java  2  s. c o  m*/
        //Check the status table
        Statement statement = conn.createStatement();
        ResultSet status = statement.executeQuery("SELECT * from status");

        Calendar now = Calendar.getInstance();

        //Check Status Table for integrity
        while (status.next()) {
            int leagueID = status.getInt("LeagueID");
            int gw = status.getInt("Gameweek");

            Calendar startDate = (new DateParser(status.getString("starts"))).convertDate();
            Calendar kickOff = (new DateParser(status.getString("kickOff"))).convertDate();
            Calendar endDate = (new DateParser(status.getString("ends"))).convertDate();
            Calendar postDate = (new DateParser(status.getString("ends"))).convertDate();
            //Add 2 Hours on to make sure match has finished
            endDate.add(Calendar.HOUR_OF_DAY, 2);
            startDate.add(Calendar.MINUTE, 30);
            postDate.add(Calendar.DAY_OF_MONTH, 1);

            //Check the Times and update the status table

            if (status.getString("started").equals("Y")) {
                //GW Has Started, are teams store
                if (status.getString("teamsStored").equals("Y")) {
                    //Teams Are Stored, has the gameweek now ended
                    if (status.getString("ended").equals("Y")) {
                        //Gameweek has now ended, has the post GW update been done
                        if (status.getString("postGwUpdate").equals("Y")) {
                            //All Done Nothing to Do.
                        } else if (status.getString("postGwUpdate").equals("F")) {
                            //Past the Post GW Update Time so Ignore
                        }
                        //Ended but is after post date?
                        else if (now.after(postDate)) {
                            //After Post Date, queue for post update
                            if (!incomplete.containsKey("post")) {
                                List<String> post = new ArrayList<String>();
                                post.add(leagueID + "," + gw);
                                incomplete.put("post", post);
                            } else {
                                incomplete.get("post").add(leagueID + "," + gw);
                            }
                        } else {
                            //Not after post date, updated players and scores
                            List<String> prePost = new ArrayList<String>();
                            prePost.add(Integer.toString(gw));
                            incomplete.put("prePost", prePost);
                        }
                    }
                    //Gameweek not marked as ended, check if now ended
                    else if (now.after(endDate)) {
                        //Gameweek has now ended, check if after post date
                        if (now.after(postDate)) {
                            //Started and ended, update status table
                            generalStatusUpdate(leagueID, gw, "Y", "Y");

                            //Now is after post date, update status table and queue for post update

                            if (!incomplete.containsKey("post")) {
                                List<String> post = new ArrayList<String>();
                                post.add(leagueID + "," + gw);
                                incomplete.put("post", post);
                            } else {
                                incomplete.get("post").add(leagueID + "," + gw);
                            }

                        } else {
                            //Not after post date, update status table and mark to do nothing
                            generalStatusUpdate(leagueID, gw, "Y", "Y");

                            List<String> prePost = new ArrayList<String>();
                            prePost.add(Integer.toString(gw));
                            incomplete.put("prePost", prePost);

                        }
                    } else {
                        //Gameweek has stated but not ended, queue to go live

                        if (!incomplete.containsKey("live")) {
                            List<String> live = new ArrayList<String>();
                            live.add(leagueID + "," + gw);
                            incomplete.put("live", live);
                        } else {
                            incomplete.get("live").add(leagueID + "," + gw);
                        }
                    }
                } else {
                    //Gameweek Started but teams not stored, Queue for team update...
                    //Has Gameweek now ended?
                    if (now.after(endDate)) {
                        //Gameweek has now ended, time for post?
                        if (now.after(postDate)) {

                            generalStatusUpdate(leagueID, gw, "Y", "Y");

                            //Has it already failed a status update
                            if (status.getString("postGwUpdate").equals("F")) {
                                //Therefore no teams but no status update, get teams for that gw
                                if (!incomplete.containsKey("teams")) {
                                    List<String> teams = new ArrayList<String>();
                                    teams.add(leagueID + "," + gw);
                                    incomplete.put("teams", teams);
                                } else {
                                    incomplete.get("teams").add(leagueID + "," + gw);
                                }
                            } else {
                                //After Post, Queue for Post and Update status table
                                if (!incomplete.containsKey("post")) {
                                    List<String> post = new ArrayList<String>();
                                    post.add(leagueID + "," + gw);
                                    incomplete.put("post", post);
                                } else {
                                    incomplete.get("post").add(leagueID + "," + gw);
                                }
                            }
                        } else {
                            //Ended but not after post, queue for teams and update status
                            generalStatusUpdate(leagueID, gw, "Y", "Y");

                            if (!incomplete.containsKey("teams")) {
                                List<String> teams = new ArrayList<String>();
                                teams.add(leagueID + "," + gw);
                                incomplete.put("teams", teams);
                            } else {
                                incomplete.get("teams").add(leagueID + "," + gw);
                            }
                        }
                    } else {
                        //Not Ended, Update Status and get teams and go live

                        generalStatusUpdate(leagueID, gw, "Y", "N");
                        if (!incomplete.containsKey("teams")) {
                            List<String> teams = new ArrayList<String>();
                            teams.add(leagueID + "," + gw);
                            incomplete.put("teams", teams);
                        } else {
                            incomplete.get("teams").add(leagueID + "," + gw);
                        }

                        if (!incomplete.containsKey("live")) {
                            List<String> live = new ArrayList<String>();
                            live.add(leagueID + "," + gw);
                            incomplete.put("live", live);
                        } else {
                            incomplete.get("live").add(leagueID + "," + gw);
                        }
                    }
                }
            }
            //Started != Y
            else if (status.getString("teamsStored").equals("Y")) {
                //Gameweek not marked as Started, but teams are stored, check if gameweek has now started
                if (now.after(kickOff)) {
                    //Games Have Kicked off and teams are stored, check if gameweek has ended.
                    if (now.after(endDate)) {
                        //Gameweek has now ended, check if it is time for post update
                        if (now.after(postDate)) {
                            //Now After Post Date, Queue for Post and Update Status Table
                            generalStatusUpdate(leagueID, gw, "Y", "Y");

                            if (!incomplete.containsKey("post")) {
                                List<String> post = new ArrayList<String>();
                                post.add(leagueID + "," + gw);
                                incomplete.put("post", post);
                            } else {
                                incomplete.get("post").add(leagueID + "," + gw);
                            }
                        } else {
                            //After End Date, not time for Post, Update Status Table and Update Scores

                            generalStatusUpdate(leagueID, gw, "Y", "Y");
                            List<String> prePost = new ArrayList<String>();
                            prePost.add(Integer.toString(gw));
                            incomplete.put("prePost", prePost);
                        }
                    } else {
                        //Not After End Date, Update Status Table to Started and Queue for Live

                        generalStatusUpdate(leagueID, gw, "Y", "N");

                        if (!incomplete.containsKey("live")) {
                            List<String> live = new ArrayList<String>();
                            live.add(leagueID + "," + gw);
                            incomplete.put("live", live);
                        } else {
                            incomplete.get("live").add(leagueID + "," + gw);
                        }
                    }
                }
                //Gameweek Not Started, but teams stored, does gameweek start today?
                else if (startDate.get(Calendar.DAY_OF_MONTH) == now.get(Calendar.DAY_OF_MONTH)
                        && startDate.get(Calendar.MONTH) == now.get(Calendar.MONTH)) {
                    //Gameweek does start today, queue for wait, nothing to update the status with

                    if (!incomplete.containsKey("wait")) {
                        List<String> wait = new ArrayList<String>();
                        wait.add("Matches to Kick-Off..");
                        incomplete.put("wait", wait);
                    } else {
                        incomplete.get("wait").add("Matches to Kick-Off..");
                    }
                } else {
                    //Else Gameweek does not start today, nothing to do
                }
            }
            //Started != Y and teamStored != Y
            //Check Dates
            //Check is after Start Date, if it isnt, then it is pre gameweek and nothing to do
            else if (now.after(startDate)) {
                //After StartDate, is after kick off
                if (now.after(kickOff)) {
                    //After Kick Off, is after End Date?
                    if (now.after(endDate)) {
                        //After End date, is after postUpdate?
                        if (now.after(postDate)) {
                            //After Post Date, Update Status table and queue for post

                            generalStatusUpdate(leagueID, gw, "Y", "Y");
                            if (!incomplete.containsKey("post")) {
                                List<String> post = new ArrayList<String>();
                                post.add(leagueID + "," + gw);
                                incomplete.put("post", post);
                            } else {
                                incomplete.get("post").add(leagueID + "," + gw);
                            }
                        } else {
                            //After End Date, update Status and update scores
                            generalStatusUpdate(leagueID, gw, "Y", "Y");
                            List<String> prePost = new ArrayList<String>();
                            prePost.add(Integer.toString(gw));
                            incomplete.put("prePost", prePost);
                        }
                    } else {
                        //After kick off but before end date, update status table queue for live and teams
                        generalStatusUpdate(leagueID, gw, "Y", "N");
                        if (!incomplete.containsKey("teams")) {
                            List<String> teams = new ArrayList<String>();
                            teams.add(leagueID + "," + gw);
                            incomplete.put("teams", teams);
                        } else {
                            incomplete.get("teams").add(leagueID + "," + gw);
                        }

                        if (!incomplete.containsKey("live")) {
                            List<String> live = new ArrayList<String>();
                            live.add(leagueID + "," + gw);
                            incomplete.put("live", live);
                        } else {
                            incomplete.get("live").add(leagueID + "," + gw);
                        }
                    }
                } else {
                    //Not after kick off but after started, queue for teams and wait

                    if (!incomplete.containsKey("teams")) {
                        List<String> teams = new ArrayList<String>();
                        teams.add(leagueID + "," + gw);
                        incomplete.put("teams", teams);
                    } else {
                        incomplete.get("teams").add(leagueID + "," + gw);
                    }
                    if (!incomplete.containsKey("wait")) {
                        List<String> wait = new ArrayList<String>();
                        wait.add("Matches to Kick-Off..");
                        incomplete.put("wait", wait);
                    } else {
                        incomplete.get("wait").add("Matches to Kick-Off..");
                    }
                }
            } else if (startDate.get(Calendar.DAY_OF_MONTH) == now.get(Calendar.DAY_OF_MONTH)
                    && startDate.get(Calendar.MONTH) == now.get(Calendar.MONTH)) {
                //Gameweek does start today, queue for wait, nothing to update the status with
                if (!incomplete.containsKey("wait")) {
                    List<String> wait = new ArrayList<String>();
                    wait.add("Teams to be finalised");
                    incomplete.put("wait", wait);
                } else {
                    incomplete.get("wait").add("Teams to be finalised");
                }
            } else {
                //Pre Gameweek and nothing to do.
            }

        }
        statement.close();

    } catch (SQLException sql) {
        Main.log.ln(1);
        Main.log.log(1, "Critical Error Updating Status.. " + sql + "\n");
        Main.log.log(9, sql);
        System.exit(1003);
    } catch (NullPointerException n) {
        Main.log.ln(1);
        Main.log.log(1, "Critical Data is Missing from the DB, Try Again or Backup and Delete this Table\n");
        Main.log.log(1, n.toString());
        System.exit(1005);
    }
    Main.log.log(4, "Done!\n", 0);
    return incomplete;
}

From source file:org.phaidra.apihooks.APIRESTHooksImpl.java

/**
 * Runs the hook if enabled in fedora.fcfg.
 *
 * @param method The name of the method that calls the hook
 * @param pid The PID that is being accessed
 * @param params Method parameters, depend on the method called
 * @return String Hook verdict. Begins with "OK" if it's ok to proceed.
 * @throws APIHooksException If the remote call went wrong
 *///  w  w  w . j a  v  a2s.  com
public String runHook(String method, DOWriter w, Context context, String pid, Object[] params)
        throws APIHooksException {
    String rval = null;

    // Only do this if the method is enabled in fedora.fcfg
    if (getParameter(method) == null) {
        log.debug("runHook: method |" + method + "| not configured, not calling webservice");
        return "OK";
    }

    Iterator i = context.subjectAttributes();
    String attrs = "";
    while (i.hasNext()) {
        String name = "";
        try {
            name = (String) i.next();
            String[] value = context.getSubjectValues(name);
            for (int j = 0; j < value.length; j++) {
                attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8");
                log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute");
            }
        } catch (NullPointerException ex) {
            log.debug(
                    "runHook: caught NullPointerException while trying to retrieve subject attribute " + name);
        } catch (UnsupportedEncodingException ex) {
            log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute "
                    + name);
        }
    }
    String paramstr = "";
    try {
        for (int j = 0; j < params.length; j++) {
            paramstr += "&param" + Integer.toString(j) + "=";
            if (params[j] != null) {
                String p = params[j].toString();
                paramstr += URLEncoder.encode(p, "UTF-8");
            }
        }
    } catch (UnsupportedEncodingException ex) {
        log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter");
    }

    String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri);

    log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|");
    try {
        // TODO: timeout? retries?
        URL url;
        URLConnection urlConn;
        DataOutputStream printout;
        BufferedReader input;

        url = new URL(getParameter("restmethod"));
        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 = "method=" + URLEncoder.encode(method, "UTF-8") + "&username="
                + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr
                + attrs;
        printout.writeBytes(content);
        printout.flush();
        printout.close();

        // Get response data.
        input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
        String str;
        rval = "";
        while (null != ((str = input.readLine()))) {
            rval += str + "\n";
        }
        input.close();

        String ct = urlConn.getContentType();
        if (ct.startsWith("text/xml")) {
            log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval);
        } else if (ct.startsWith("text/plain")) {
            log.debug("runHook: successful REST invocation for method |" + method
                    + "|, but hook returned an error: " + rval);
            throw new Exception(rval);
        } else {
            throw new Exception("Invalid content type " + ct);
        }
    } catch (Exception ex) {
        log.error("runHook: error calling REST hook: " + ex.toString());
        throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex);
    }

    return processResults(rval, w, context);
}

From source file:org.opencms.setup.CmsSetupBean.java

/**
 * Saves the properties to a file.<p>
 * /*from   ww w. java 2  s .  co m*/
 * @param properties the properties to be saved
 * @param source the source file to get the keys from
 * @param target the target file to save the properties to
 * @param forceWrite the keys of the properties which should always be written, even if they don't exist in the configuration file 
 */
private void save(CmsParameterConfiguration properties, String source, String target, Set<String> forceWrite) {

    try {
        Set<String> alreadyWritten = new HashSet<String>();

        LineNumberReader lnr = new LineNumberReader(new FileReader(new File(m_configRfsPath + source)));

        FileWriter fw = new FileWriter(new File(m_configRfsPath + target));

        while (true) {
            String line = lnr.readLine();
            if (line == null) {
                break;
            }
            line = line.trim();

            if ("".equals(line)) {
                // output empty line
                fw.write("\n");
            } else if (line.startsWith("#")) {
                // output comment
                fw.write(line);
                fw.write("\n");
            } else {

                int index = line.indexOf('=');
                int index1 = line.indexOf("\\=");
                if ((line.indexOf('=') > -1) && (index1 != (index - 1))) {

                    String key = line.substring(0, line.indexOf('=')).trim();
                    if (alreadyWritten.contains(key)) {
                        continue;
                    }
                    // write key
                    fw.write((key + "="));
                    try {
                        Object obj = properties.getObject(key);
                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }

                    } catch (NullPointerException e) {
                        // no value found - do nothing 
                    }
                    // add trailing line feed
                    fw.write("\n");

                    // remember that this properties is already written (multi values)
                    alreadyWritten.add(key);
                }
            }
        }
        if (forceWrite != null) {
            for (String forced : forceWrite) {
                if (!alreadyWritten.contains(forced) && properties.containsKey(forced)) {
                    fw.write("\n\n");
                    fw.write(forced + "=");
                    try {
                        Object obj = properties.getObject(forced);

                        if (obj != null) {
                            String valueToWrite = getPropertyValueToWrite(obj);
                            fw.write(valueToWrite);
                        }
                    } catch (NullPointerException e) {
                        // no value found - do nothing
                    }
                    fw.write("\n");

                }
            }
        }

        lnr.close();
        fw.close();
    } catch (Exception e) {
        m_errors.add("Could not save properties to " + target + " \n");
        m_errors.add(e.toString() + "\n");
    }
}

From source file:org.mewx.wenku8.fragment.NavigationDrawerFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // set button clicked listener, mainly working on change fragment in MainActivity.
    try {// w  w  w .  ja  v a2  s . c o m
        mainActivity.findViewById(R.id.main_menu_rklist).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainActivity.getCurrentFragment() == MainActivity.FRAGMENT_LIST.RKLIST)
                    return; // selected button, so just ignore.
                clearAllButtonColor();
                setHighLightButton(MainActivity.FRAGMENT_LIST.RKLIST);
                mainActivity.setCurrentFragment(MainActivity.FRAGMENT_LIST.RKLIST);
                mainActivity.changeFragment(new RKListFragment());
                closeDrawer();
            }
        });

        mainActivity.findViewById(R.id.main_menu_latest).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainActivity.getCurrentFragment() == MainActivity.FRAGMENT_LIST.LATEST)
                    return; // selected button, so just ignore.
                clearAllButtonColor();
                setHighLightButton(MainActivity.FRAGMENT_LIST.LATEST);
                mainActivity.setCurrentFragment(MainActivity.FRAGMENT_LIST.LATEST);
                mainActivity.changeFragment(new LatestFragment());
                closeDrawer();
            }
        });

        mainActivity.findViewById(R.id.main_menu_fav).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainActivity.getCurrentFragment() == MainActivity.FRAGMENT_LIST.FAV)
                    return; // selected button, so just ignore.
                clearAllButtonColor();
                setHighLightButton(MainActivity.FRAGMENT_LIST.FAV);
                mainActivity.setCurrentFragment(MainActivity.FRAGMENT_LIST.FAV);
                mainActivity.changeFragment(new FavFragment());
                closeDrawer();
            }
        });

        mainActivity.findViewById(R.id.main_menu_config).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainActivity.getCurrentFragment() == MainActivity.FRAGMENT_LIST.CONFIG)
                    return; // selected button, so just ignore.
                clearAllButtonColor();
                setHighLightButton(MainActivity.FRAGMENT_LIST.CONFIG);
                mainActivity.setCurrentFragment(MainActivity.FRAGMENT_LIST.CONFIG);
                mainActivity.changeFragment(new ConfigFragment());
                closeDrawer();
            }
        });

        mainActivity.findViewById(R.id.main_menu_open_source).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(getActivity()).theme(Theme.LIGHT).title(R.string.main_menu_statement)
                        .content(GlobalConfig.getOpensourceLicense()).forceStacking(true)
                        .positiveColorRes(R.color.dlgPositiveButtonColor)
                        .positiveText(R.string.dialog_positive_known).show();
            }
        });

        mainActivity.findViewById(R.id.main_menu_dark_mode_switcher)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openOrCloseDarkMode();
                    }
                });

    } catch (NullPointerException e) {
        Toast.makeText(mainActivity, "NullPointerException in onActivityCreated();", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }

    // User Account
    //        RelativeLayout rlBackground = (RelativeLayout)getActivity().findViewById(R.id.top_background);
    rivUserAvatar = (RoundedImageView) getActivity().findViewById(R.id.user_avatar);
    tvUserName = (TextView) getActivity().findViewById(R.id.user_name);

    View.OnClickListener ocl = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!LightUserSession.getLogStatus() && GlobalConfig.isNetworkAvailable(getActivity())) {
                if (!LightUserSession.isUserInfoSet()) {
                    Intent intent = new Intent(getActivity(), UserLoginActivity.class);
                    startActivity(intent);
                } else {
                    // show dialog to login, error to jump to login activity
                    if (LightUserSession.aiui.getStatus() == AsyncTask.Status.FINISHED) {
                        Toast.makeText(getActivity(), "Relogged.", Toast.LENGTH_SHORT).show();
                        LightUserSession.aiui = new LightUserSession.AsyncInitUserInfo();
                        LightUserSession.aiui.execute();
                    }
                }
            } else if (!GlobalConfig.isNetworkAvailable(getActivity())) {
                // no network, no log in
                Toast.makeText(getActivity(), getResources().getString(R.string.system_network_error),
                        Toast.LENGTH_SHORT).show();
            } else {
                // Logged, click to info page
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                startActivity(intent);
            }
        }
    };
    rivUserAvatar.setOnClickListener(ocl);
    tvUserName.setOnClickListener(ocl);

    // Initial: set color states here ...
    // get net work status, no net -> FAV
    if (!GlobalConfig.isNetworkAvailable(getActivity())) {
        clearAllButtonColor();
        setHighLightButton(MainActivity.FRAGMENT_LIST.FAV);
        mainActivity.setCurrentFragment(MainActivity.FRAGMENT_LIST.FAV);
        mainActivity.changeFragment(new FavFragment());
    } else {
        clearAllButtonColor();
        setHighLightButton(mainActivity.getCurrentFragment());
        mainActivity.changeFragment(new LatestFragment());
    }

    // set menu background
    bgImage = (ImageView) getActivity().findViewById(R.id.bg_img);
    if (GlobalConfig.getFromAllSetting(GlobalConfig.SettingItems.menu_bg_id) != null) {
        switch (GlobalConfig.getFromAllSetting(GlobalConfig.SettingItems.menu_bg_id)) {
        case "0":
            try {
                bmMenuBackground = BitmapFactory
                        .decodeFile(GlobalConfig.getFromAllSetting(GlobalConfig.SettingItems.menu_bg_path));
            } catch (OutOfMemoryError oome) {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;
                    bmMenuBackground = BitmapFactory.decodeFile(
                            GlobalConfig.getFromAllSetting(GlobalConfig.SettingItems.menu_bg_path), options);
                    if (bmMenuBackground == null)
                        throw new Exception("PictureLoadFailureException");
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "Exception: " + e.toString()
                            + "\n??SD?????",
                            Toast.LENGTH_SHORT).show();
                    bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_04));
                    return;
                }
            }
            bgImage.setImageBitmap(bmMenuBackground);
            break;
        case "1":
            bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_01));
            break;
        case "2":
            bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_02));
            break;
        case "3":
            bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_03));
            break;
        case "4":
            bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_04));
            break;
        case "5":
            bgImage.setImageDrawable(getResources().getDrawable(R.drawable.bg_avatar_05));
            break;
        }
    }
}

From source file:org.jab.docsearch.DocSearch.java

/**
 * Set the page./*from ww w  .  j a v a2s  . com*/
 *
 * @param pageToSet
 *            Page name
 * @return True, if page is successfully set.
 */
private boolean setPage(final String pageToSet) {
    logger.debug("setPage('" + pageToSet + "') entered");

    boolean returnBool = true;

    try {
        if (FileTypeUtils.isFileTypeHTML(pageToSet) || FileTypeUtils.isFileTypeText(pageToSet)) {
            editorPane.setContentType("text/html");
            editorPane.setPage(fileString + blankFile);
        }
    } catch (NullPointerException npe) {
        logger.fatal("setPage() failed", npe);
        setStatus(dsErrSetPa + " : " + npe.toString() + "\n" + pageToSet);
    } catch (IOException ioe) {
        logger.fatal("setPage() failed", ioe);
        setStatus(dsErrSetPa + " : " + ioe.toString() + "\n" + pageToSet);
    }

    // which page?
    if ("home".equals(pageToSet)) {
        setStatus(I18n.getString("loading") + " : *" + pageToSet + "*");
        editorPane.setContentType("text/html");
        if (hasStartPage) {
            try {
                if (env.isWebStart()) {
                    editorPane.setPage(startPageString);
                } else {
                    editorPane.setPage(fileString + startPageString);
                }
            } catch (IOException ioe) {
                logger.fatal("setPage() failed", ioe);
                editorPane.setText(lastSearch);
            }
        } else {
            editorPane.setText(lastSearch);
        }
        editorPane.select(0, 0);
    } else if ("help".equals(pageToSet)) {
        setStatus(I18n.getString("loading") + " : *" + pageToSet + "*");
        editorPane.setContentType("text/html");
        if (hasStartPage) {
            try {
                if (env.isWebStart()) {
                    editorPane.setPage(helpPageString);
                } else {
                    editorPane.setPage(fileString + helpPageString);
                }
            } catch (IOException ioe) {
                logger.fatal("setPage() failed", ioe);
                editorPane.setText(lastSearch);
            }
        } else {
            editorPane.setText(lastSearch);
        }
        editorPane.select(0, 0);
    } else if ("result".equals(pageToSet)) {
        setStatus(I18n.getString("loading") + " : *" + pageToSet + "*");
        editorPane.setContentType("text/html");
        editorPane.setText(lastSearch);
        editorPane.select(0, 0);
    } else {
        if (FileTypeUtils.isFileTypeHTML(pageToSet) || FileTypeUtils.isFileTypeText(pageToSet)) {
            if (FileTypeUtils.isFileTypeHTML(pageToSet)) {
                editorPane.setContentType("text/html");
            } else if (FileTypeUtils.isFileTypeText(pageToSet)) {
                editorPane.setContentType("text/plain");
            }

            try {
                // set the page
                if (pageToSet.startsWith("file:/")) {
                    String newPageToSet = pageToSet.substring(6, pageToSet.length());
                    editorPane.setPage(fileString + newPageToSet);
                } else if (pageToSet.startsWith("http:")) {
                    editorPane.setPage(pageToSet);
                } else if (pageToSet.startsWith("ftp")) {
                    editorPane.setPage(pageToSet);
                } else {
                    editorPane.setPage(fileString + pageToSet);
                }
                setStatus(I18n.getString("loaded") + " " + pageToSet);
            } catch (IOException ioe) {
                logger.fatal("setPage() failed", ioe);
                returnBool = false;
                showMessage(dsErrLdgPa, "\n" + pageToSet + ioe.toString());
            }
        } else {
            doExternal(pageToSet);
        }
    }

    // store page name
    // clean last search text
    if (returnBool) {
        curPage = pageToSet;
    }

    return returnBool;
}

From source file:org.jab.docsearch.DocSearch.java

/**
 * Method doSearch//from w  w w  .  ja va  2  s. c om
 *
 * @param searchText  Search text
 */
public void doSearch(String searchText) {
    // TODO format date with locale

    setStatus(I18n.getString("please_wait...") + " " + I18n.getString("searching") + " --> " + searchText);
    setSearching(true);
    setIsWorking(true);
    int srchMaxPos = indexes.size() * 3;
    if (srchMaxPos > 0) {
        pPanel.setMaxPos(srchMaxPos);
    }
    synchronized (this) {
        ArrayList[] sizeList = null;
        if (phrase.isSelected()) {
            if (searchText.indexOf("\"") == -1) {
                searchText = "\"" + searchText + "\"";
            }
        }
        // for each di - search and add the results
        int grandTotalHits = 0;
        int selectedFields = searchIn.getSelectedIndex();
        String sField = searchOpts[selectedFields];

        StringBuffer searchedIndexes = new StringBuffer();
        StringBuffer bodyBuf = new StringBuffer();

        StringBuffer hitBuf = new StringBuffer();
        hitBuf.append("<html><head><title>");
        hitBuf.append(I18n.getString("results_for_search"));
        hitBuf.append(' ');
        hitBuf.append(searchText);
        hitBuf.append("</title></head><body><h1 align=\"center\">");
        hitBuf.append(I18n.getString("results_for_search"));
        hitBuf.append(": ");
        hitBuf.append("<strong><font color=\"blue\">");
        hitBuf.append(searchText);
        hitBuf.append("</font></strong></h1>");
        if (env.isGUIMode()) {
            if (logger.isDebugEnabled()) {
                logger.debug("doSearch() search for '" + searchText + "'");
            }
        } else {
            System.out.println(I18n.getString("results_for_search") + ": " + searchText);
        }

        if (!indexes.isEmpty()) {
            try {
                int curSrchPos = 0;

                // add the items
                Iterator<DocSearcherIndex> iterator = indexes.iterator();
                while (iterator.hasNext()) {
                    curSrchPos++;
                    if (curSrchPos > 0) {
                        pPanel.setCurPos(curSrchPos);
                    }
                    DocSearcherIndex currentIndex = iterator.next();
                    boolean isCdRomIdx = currentIndex.isCdrom();
                    StringBuffer tempBuf = new StringBuffer();
                    if (currentIndex.getShouldBeSearched()) {
                        String findText = "";

                        // create searcher
                        Searcher searcher = new IndexSearcher(currentIndex.getIndexPath());
                        if ((searchText.indexOf("(") != -1) || (searchText.indexOf("[") != -1)) {
                            findText = searchText;
                        } else {
                            // add body and title, or single field to query
                            if (selectedFields == 0) {
                                findText = "+(" + Index.FIELD_BODY + ":(" + searchText + ") OR "
                                        + Index.FIELD_TITLE + ":(" + searchText + "))";
                            } else {
                                // TODO dont use sField directly, because it
                                // is translated in other languages
                                findText = "+" + sField + ":(" + searchText + ")";
                            }

                            // add author to query
                            if (useAuthor.isSelected()) {
                                findText += " +" + Index.FIELD_AUTHOR + ":(" + authorField.getText() + ")";
                            }

                            // add filetype to query
                            if (useType.isSelected()) {
                                findText += " +" + Index.FIELD_TYPE + ":("
                                        + fileTypesToFind[fileType.getSelectedIndex()] + ")";
                            }
                        }
                        logger.debug("doSearch() query string '" + findText + "'");
                        setStatus(dsSrchStr + ": " + findText + "...");

                        // create query
                        QueryParser queryParser = new QueryParser(Index.FIELD_BODY, new StandardAnalyzer());
                        Query query = queryParser.parse(findText);

                        // check for date filter and search in index
                        Hits hits;
                        if (useDate.isSelected()) {
                            String dateFrom = DateTimeUtils.getDateStringForIndex(
                                    DateTimeUtils.getDateFromString(fromField.getText()));
                            String dateTo = DateTimeUtils
                                    .getDateStringForIndex(DateTimeUtils.getDateFromString(toField.getText()));
                            RangeFilter rangeFilter = new RangeFilter(Index.FIELD_MODDATE, dateFrom, dateTo,
                                    true, true);
                            if (logger.isDebugEnabled()) {
                                logger.debug("doSearch() search with date range '" + rangeFilter + "'");
                            }

                            hits = searcher.search(query, rangeFilter);
                        } else {
                            if (logger.isDebugEnabled()) {
                                logger.debug("doSearch() search without date range");
                            }

                            hits = searcher.search(query);
                        }

                        // check for search with filesize
                        int numHits;
                        if (useSize.isSelected()) {
                            int minFilesize = 1;
                            int maxFilesize = 2;
                            try {
                                minFilesize = Integer.parseInt(sizeFromField.getText()) * 1024;
                                maxFilesize = Integer.parseInt(sizeToField.getText()) * 1024;
                            } catch (Exception e) {
                                setStatus(dsErrParseNums + " " + e.toString());
                            }
                            sizeList = getHitsForFilesizeRange(hits, minFilesize, maxFilesize);
                            numHits = sizeList[0].size();
                        } else {
                            numHits = hits.length(); // NOT A SIZE QUERY
                        }

                        searchedIndexes.append("<li> <font color=\"blue\">");
                        searchedIndexes.append(currentIndex.getName());
                        searchedIndexes.append("</font> (<b>");
                        searchedIndexes.append(numHits);
                        searchedIndexes.append("</b> ");
                        searchedIndexes.append(I18n.getString("documents"));
                        searchedIndexes.append(")</li>");
                        if (env.isGUIMode()) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("doSearch() Index: " + currentIndex.getName());
                            }
                        } else {
                            System.out.println(I18n.getString("index") + ": " + currentIndex.getName());
                        }
                        grandTotalHits += numHits;
                        tempBuf.append("<p align=\"center\"><b>");
                        tempBuf.append(numHits);
                        tempBuf.append("</b> ");
                        tempBuf.append(I18n.getString("documents_found_in_index"));
                        tempBuf.append("<b> ");
                        tempBuf.append(currentIndex.getName());
                        tempBuf.append("</b></p>");

                        curSrchPos++;
                        if (curSrchPos > 0) {
                            pPanel.setCurPos(curSrchPos);
                        }
                        for (int i = 0; i < numHits; i++) {
                            if (i > maxNumHitsShown) {
                                setStatus(dsMxNumHits + " (" + maxNumHitsShown + ") "
                                        + I18n.getString("exceeded") + " (" + numHits + ").");
                                break;
                            }

                            // get document and score from result or special
                            // result
                            Document currentDocument;
                            float currentScore;

                            // filesize result?
                            if (useSize.isSelected()) {
                                currentDocument = (Document) sizeList[0].get(i);
                                currentScore = ((Float) sizeList[1].get(i)).floatValue();
                            } else {
                                currentDocument = hits.doc(i);
                                currentScore = hits.score(i);
                            }

                            // title
                            String currentTitle = Utils
                                    .convertTextToHTML(currentDocument.get(Index.FIELD_TITLE));

                            // filesize
                            String currentFilesize = currentDocument.get(Index.FIELD_SIZE);

                            // path or url
                            String currentFile;
                            if (!currentIndex.getIsWeb()) {
                                if (!isCdRomIdx) {
                                    currentFile = currentDocument.get(Index.FIELD_PATH);
                                } else {
                                    currentFile = getCDROMPath(currentDocument.get(Index.FIELD_URL));
                                }
                            } else {
                                currentFile = currentDocument.get(Index.FIELD_URL);
                            }

                            // type
                            String currentTypeStr = currentDocument.get(Index.FIELD_TYPE);
                            FileType currentType = FileType.fromValue(currentTypeStr);

                            // author
                            String currentAuthor = currentDocument.get(Index.FIELD_AUTHOR);
                            if ("".equals(currentAuthor)) {
                                currentAuthor = I18n.getString("unknown");
                            }

                            // date
                            String currentDate = currentDocument.get(Index.FIELD_MODDATE);
                            if ("".equals(currentDate)) {
                                currentDate = I18n.getString("unknown");
                            } else {
                                currentDate = DateTimeUtils.getDateParsedFromIndex(currentDate);
                            }

                            String currentSummary = Utils
                                    .convertTextToHTML(currentDocument.get(Index.FIELD_SUMMARY));

                            // add it to our page - doc size title score
                            tempBuf.append("<p align=\"left\">");
                            if (!currentIndex.getIsWeb()) {
                                tempBuf.append("<a href=\"");
                                tempBuf.append(fileString);
                                tempBuf.append(currentFile);
                                tempBuf.append("\">");
                            } else {
                                tempBuf.append("<a href=\"");
                                tempBuf.append(currentFile);
                                tempBuf.append("\">");
                            }
                            switch (currentType) {
                            case HTML: // html
                                tempBuf.append(htmlTag);
                                break;
                            case MS_WORD: // ms word
                                tempBuf.append(wordTag);
                                break;
                            case MS_EXCEL: // ms excel
                                tempBuf.append(excelTag);
                                break;
                            case PDF: // pdf
                                tempBuf.append(pdfTag);
                                break;
                            case RTF: // rtf
                                tempBuf.append(rtfTag);
                                break;
                            case OO_WRITER: // openoffice writer
                                tempBuf.append(ooWriterTag);
                                break;
                            case OO_IMPRESS: // openoffice impress
                                tempBuf.append(ooImpressTag);
                                break;
                            case OO_CALC: // openoffice calc
                                tempBuf.append(ooCalcTag);
                                break;
                            case OO_DRAW: // openoffice draw
                                tempBuf.append(ooDrawTag);
                                break;
                            case OPENDOCUMENT_TEXT: // opendocument text
                                tempBuf.append(openDocumentTextTag);
                                break;
                            case TEXT:
                                tempBuf.append(textTag);
                                break;
                            default:
                                logger.error("doSearch() FileType." + currentType + " is not ok here!");
                            }
                            tempBuf.append("&nbsp;");
                            tempBuf.append(currentTitle);
                            tempBuf.append("</a><br>");
                            tempBuf.append(currentSummary);
                            tempBuf.append("<font color=\"green\"><br><em>");
                            tempBuf.append(currentDate);
                            tempBuf.append(", ");
                            tempBuf.append(Utils.getKStyle(currentFilesize));
                            tempBuf.append("bytes, ");
                            tempBuf.append(currentAuthor);
                            tempBuf.append(", <b>");
                            tempBuf.append(Utils.getPercentStringFromScore(currentScore));
                            tempBuf.append("</b></em></font><br><font color=\"gray\">");
                            tempBuf.append(currentFile);
                            tempBuf.append("</font>");
                            tempBuf.append("</p>");
                            if (env.isGUIMode()) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("doSearch() \n\n* " + currentTitle + "\n" + currentSummary
                                            + "\n" + currentDate + ", " + Utils.getKStyle(currentFilesize)
                                            + "bytes, " + currentAuthor + ", "
                                            + Utils.getPercentStringFromScore(currentScore) + "\n"
                                            + currentFile);
                                }
                            } else {
                                System.out.println("\n\n* " + currentTitle + "\n" + currentSummary + "\n"
                                        + currentDate + ", " + Utils.getKStyle(currentFilesize) + "bytes, "
                                        + currentAuthor + ", " + Utils.getPercentStringFromScore(currentScore)
                                        + "\n" + currentFile);
                            }
                        } // end for hits
                          // now add our results
                        curSrchPos++;
                        if (curSrchPos > 0) {
                            pPanel.setCurPos(curSrchPos);
                        }
                        // add the footer
                        bodyBuf.append(tempBuf);

                        // close index
                        searcher.close();
                    } // end if shouldbesearched
                    else {
                        tempBuf.append("<p align=\"left\">");
                        tempBuf.append(I18n.getString("index"));
                        tempBuf.append("  &nbsp; <b>");
                        tempBuf.append(currentIndex.getName());
                        tempBuf.append("</b>  &nbsp; ");
                        tempBuf.append(dsWasNotSearched);
                        tempBuf.append("</p>");
                        bodyBuf.append(tempBuf);
                    }
                } // end while hasmore indexes

                // finish up the page
                hitBuf.append("<p align=\"left\"><strong>");
                hitBuf.append(grandTotalHits);
                hitBuf.append("</strong> ");
                hitBuf.append(I18n.getString("documents_found_in_all_indexes"));
                hitBuf.append("</p>");
                hitBuf.append("<ul>");
                hitBuf.append(searchedIndexes);
                hitBuf.append("</ul>");
                hitBuf.append(bodyBuf);
                hitBuf.append("</body></html>");
                if (env.isGUIMode()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("doSearch() " + dsTotHits + ": " + grandTotalHits);
                    }
                } else {
                    System.out.println("\n" + dsTotHits + ": " + grandTotalHits);
                }

                // save last search
                lastSearch = hitBuf.toString();

                // show result
                if (env.isGUIMode()) {
                    editorPane.setText(lastSearch);
                    editorPane.select(0, 0);

                    // add search text in combobox if not exist
                    int searchFieldCount = searchField.getItemCount();
                    boolean inThere = false;
                    for (int i = 1; i < searchFieldCount; i++) {
                        String tmpSrchTxt = (String) searchField.getItemAt(i);
                        if (tmpSrchTxt != null) {
                            if (tmpSrchTxt.equals(searchText)) {
                                inThere = true;
                            }
                        }
                    }
                    // if search text new, than put it to searchfield and
                    // select them
                    if (!inThere) {
                        searchField.addItem(searchText);
                        searchField.setSelectedIndex(searchField.getItemCount() - 1);
                    }
                    vista = new JComponentVista(editorPane, new PageFormat());

                    // set current page to result
                    curPage = "results";
                } else {
                    // TODO check if here ouput for command line needed!
                }
            } catch (IOException ioe) {
                logger.fatal("doSearch() failed with IOException", ioe);
                showMessage(dsErrPrfSrch, dsCrptdIdx + " :\n" + ioe.toString());
            } catch (NullPointerException npe) {
                logger.fatal("doSearch() failed with NullPointerException", npe);
                showMessage(dsErrPrfSrch, dsCrptdIdx + " :\n" + npe.toString());
            } catch (Exception e) {
                logger.fatal("doSearch() failed with Exception", e);
                showMessage(dsErrPrfSrch, e.toString());
            }
        } else {
            showMessage(dsErrPrfSrch, dsMkIdx);
        }
    }

    setStatus(I18n.getString("search_complete"));
    setSearching(false);
    setIsWorking(false);
    pPanel.reset();
}

From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java

public List<String> setResourceGroups(SimplePageItem i, String[] groups) {

    ContentResourceEdit resource = null;
    List<String> ret = null;

    boolean pushed = false;
    try {//w ww  .  ja va2s .  c  o m
        pushed = pushAdvisor();
        resource = contentHostingService.editResource(i.getSakaiId());

        if (AccessMode.GROUPED.equals(resource.getInheritedAccess())) {
            Collection<String> oldGroups = resource.getInheritedGroups();
            if (oldGroups instanceof List)
                ret = (List<String>) oldGroups;
            else if (oldGroups != null)
                ret = new ArrayList<String>(oldGroups);
        }
        // else null

        if (groups == null || groups.length == 0) {
            if (AccessMode.GROUPED.equals(resource.getAccess()))
                resource.clearGroupAccess();
            // else must be public or site already, leave it
        } else {
            Site site = getCurrentSite();
            for (int n = 0; n < groups.length; n++) {
                Group group = site.getGroup(groups[n]);
                groups[n] = group.getReference();
            }
            resource.setGroupAccess(Arrays.asList(groups));
        }
        contentHostingService.commitResource(resource, NotificationService.NOTI_NONE);
        resource = null;

    } catch (java.lang.NullPointerException e) {
        // KNL-714 gives spurious null pointer
        setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror"));
    } catch (Exception e) {
        setErrMessage(e.toString());
        return null;
    } finally {
        // this will generate a traceback in the case of KNL-714, but there's no way
        // to trap it. Sorry. The log entry will say
        // org.sakaiproject.content.impl.BaseContentService - cancelResource(): closed ContentResourceEdit
        // the user will also get a warning
        if (resource != null) {
            contentHostingService.cancelResource(resource);
        }
        if (pushed)
            popAdvisor();
    }

    return ret;

}

From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java

public void addMultimediaFile(MultipartFile file) {
    try {/*  w w  w . j a  v a 2s  .  c  om*/

        String name = null;
        String sakaiId = null;
        String mimeType = null;

        if (file != null) {
            if (!uploadSizeOk(file))
                return;

            String collectionId = getCollectionId(false);
            //    user specified a file, create it
            name = file.getOriginalFilename();
            if (name == null || name.length() == 0)
                name = file.getName();
            int i = name.lastIndexOf("/");
            if (i >= 0)
                name = name.substring(i + 1);
            String base = name;
            String extension = "";
            i = name.lastIndexOf(".");
            if (i > 0) {
                base = name.substring(0, i);
                extension = name.substring(i + 1);
            }

            mimeType = file.getContentType();
            try {
                ContentResourceEdit res = null;
                if (itemId != -1 && replacefile) {
                    // upload new version -- get existing file
                    SimplePageItem item = findItem(itemId);
                    String resId = item.getSakaiId();
                    res = contentHostingService.editResource(resId);
                } else {
                    // otherwise create a new file
                    res = contentHostingService.addResource(collectionId,
                            fixFileName(collectionId, Validator.escapeResourceName(base),
                                    Validator.escapeResourceName(extension)),
                            "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
                }
                if (isCaption)
                    res.setContentType("text/vtt");
                else
                    res.setContentType(mimeType);
                res.setContent(file.getInputStream());
                try {
                    contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
                    //    there's a bug in the kernel that can cause
                    //    a null pointer if it can't determine the encoding
                    //    type. Since we want this code to work on old
                    //    systems, work around it.
                } catch (java.lang.NullPointerException e) {
                    setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror"));
                }
                sakaiId = res.getId();

                if (("application/zip".equals(mimeType) || "application/x-zip-compressed".equals(mimeType))
                        && isWebsite) {
                    // We need to set the sakaiId to the resource id of the index file
                    sakaiId = expandZippedResource(sakaiId);
                    if (sakaiId == null)
                        return;

                    // We set this special type for the html field in the db. This allows us to
                    // map an icon onto website links in applicationContext.xml
                    mimeType = "LBWEBSITE";
                }

            } catch (org.sakaiproject.exception.OverQuotaException ignore) {
                setErrMessage(messageLocator.getMessage("simplepage.overquota"));
                return;
            } catch (Exception e) {
                setErrMessage(
                        messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
                log.error("addMultimedia error 1 " + e);
                return;
            }
            ;
        } else if (mmUrl != null && !mmUrl.trim().equals("") && multimediaDisplayType != 1
                && multimediaDisplayType != 3) {
            //    user specified a URL, create the item
            String url = mmUrl.trim();
            // if user gives a plain hostname, make it a URL.
            // ui add https if page is displayed with https. I'm reluctant to use protocol-relative
            // urls, because I don't know whether all the players understand it.
            if (!url.startsWith("http:") && !url.startsWith("https:") && !url.startsWith("/")) {
                String atom = url;
                int i = atom.indexOf("/");
                if (i >= 0)
                    atom = atom.substring(0, i);
                // first atom is hostname
                if (atom.indexOf(".") >= 0) {
                    String server = ServerConfigurationService.getServerUrl();
                    if (server.startsWith("https:"))
                        url = "https://" + url;
                    else
                        url = "http://" + url;
                }
            }

            name = url;
            String basename = url;
            // SAK-11816 method for creating resource ID
            String extension = ".url";
            if (basename != null && basename.length() > 32) {
                // lose the http first                              
                if (basename.startsWith("http:")) {
                    basename = basename.substring(7);
                } else if (basename.startsWith("https:")) {
                    basename = basename.substring(8);
                }
                if (basename.length() > 32) {
                    // max of 18 chars from the URL itself                      
                    basename = basename.substring(0, 18);
                    // add a timestamp to differentiate it (+14 chars)          
                    Format f = new SimpleDateFormat("yyyyMMddHHmmss");
                    basename += f.format(new Date());
                    // total new length of 32 chars                             
                }
            }

            String collectionId;
            SimplePage page = getCurrentPage();

            collectionId = getCollectionId(true);

            try {
                //    urls aren't something people normally think of as resources. Let's hide them
                ContentResourceEdit res = contentHostingService
                        .addResource(collectionId,
                                fixFileName(collectionId, Validator.escapeResourceName(basename),
                                        Validator.escapeResourceName(extension)),
                                "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
                res.setContentType("text/url");
                res.setResourceType("org.sakaiproject.content.types.urlResource");
                res.setContent(url.getBytes());
                contentHostingService.commitResource(res, NotificationService.NOTI_NONE);
                sakaiId = res.getId();
            } catch (org.sakaiproject.exception.OverQuotaException ignore) {
                setErrMessage(messageLocator.getMessage("simplepage.overquota"));
                return;
            } catch (Exception e) {
                setErrMessage(
                        messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString()));
                log.error("addMultimedia error 2 " + e);
                return;
            }
            //    connect to url and get mime type
            // new dialog passes the mime type
            if (multimediaMimeType != null && !"".equals(multimediaMimeType))
                mimeType = multimediaMimeType;
            else
                mimeType = getTypeOfUrl(url);

        } else if (mmUrl != null && !mmUrl.trim().equals("")
                && (multimediaDisplayType == 1 || multimediaDisplayType == 3)) {
            // fall through. we have an embed code, don't need file
        } else
            //    nothing to do
            return;

        //    itemId tells us whether it's an existing item
        //    isMultimedia tells us whether resource or multimedia
        //    sameWindow is only passed for existing items of type HTML/XHTML
        //      for new items it should be set true for HTML/XTML, false otherwise
        //      for existing items it should be set to the passed value for HTML/XMTL, false otherwise
        //      it is ignored for isMultimedia, as those are always displayed inline in the current page

        SimplePageItem item = null;
        if (itemId == -1 && isMultimedia) {
            item = appendItem(sakaiId, name, SimplePageItem.MULTIMEDIA);
        } else if (itemId == -1 && isWebsite) {
            String websiteName = name.substring(0, name.indexOf("."));
            item = appendItem(sakaiId, websiteName, SimplePageItem.RESOURCE);
        } else if (itemId == -1) {
            item = appendItem(sakaiId, name, SimplePageItem.RESOURCE);
        } else if (isCaption) {
            item = findItem(itemId);
            if (item == null)
                return;
            item.setAttribute("captionfile", sakaiId);
            update(item);
            return;
        } else {
            item = findItem(itemId);
            if (item == null)
                return;

            // editing an existing item which might have customized properties
            // retrieve original resource and check for customizations
            ResourceHelper resHelp = new ResourceHelper(getContentResource(item.getSakaiId()));
            // if replacing file, keep existing name
            boolean hasCustomName = resHelp.isNameCustom(item.getName()) || replacefile;

            item.setSakaiId(sakaiId);
            if (!hasCustomName) {
                item.setName(name);
            }
        }

        // for new file, old captions don't make sense
        item.removeAttribute("captionfile");
        // remember who added it, for permission checks
        item.setAttribute("addedby", getCurrentUserId());

        item.setPrerequisite(this.prerequisite);

        if (mimeType != null) {
            item.setHtml(mimeType);
        } else {
            item.setHtml(null);
        }

        if (mmUrl != null && !mmUrl.trim().equals("") && isMultimedia) {
            if (multimediaDisplayType == 1)
                // the code is filtered by the UI, so the user can see the effect.
                // This protects against someone handcrafting a post.
                // The code is similar to that in submit, but currently doesn't
                // have folder-specific override (because there are no folders involved)
                item.setAttribute("multimediaEmbedCode", AjaxServer.filterHtml(mmUrl.trim()));
            else if (multimediaDisplayType == 3)
                item.setAttribute("multimediaUrl", mmUrl.trim());
            item.setAttribute("multimediaDisplayType", Integer.toString(multimediaDisplayType));
        }
        //    if this is an existing item and a resource, leave it alone
        //    otherwise initialize to false
        if (isMultimedia || itemId == -1)
            item.setSameWindow(false);

        clearImageSize(item);
        try {
            //      if (itemId == -1)
            //      saveItem(item);
            //        else
            update(item);
        } catch (Exception e) {
            System.out.println("save error " + e);
            //    saveItem and update produce the errors
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}