Example usage for java.util ArrayList toString

List of usage examples for java.util ArrayList toString

Introduction

In this page you can find the example usage for java.util ArrayList toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.bcp.bcp.geofencing.GeofenceTransitionsIntentService.java

/**
 * Gets transition details and returns them as a formatted string.
 *
 * @param context               The app context.
 * @param geofenceTransition    The ID of the geofence transition.
 * @param triggeringGeofences   The geofence(s) triggered.
 * @return The transition details formatted as String.
 *///from www.ja v a2 s . c  om
private String getGeofenceTransitionDetails(Context context, int geofenceTransition,
        List<Geofence> triggeringGeofences) {

    String geofenceTransitionString = getTransitionString(geofenceTransition);

    // Get the Ids of each geofence that was triggered.
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
    Date curDate = new Date();
    SimpleDateFormat format = new SimpleDateFormat(Constants.TIME_FORMAT);
    gEntryDate = format.format(curDate);
    boolean isInserted;

    gaddress = triggeringGeofencesIdsList.toString();
    gstatus = geofenceTransitionString;
    String geoFenceDetailString = geofenceTransitionString + ": " + triggeringGeofencesIdsString;

    Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
    Account[] accounts = AccountManager.get(this).getAccounts();

    for (Account account : accounts) {
        if (gmailPattern.matcher(account.name).matches()) {
            gemail = account.name;
        }
    }

    //insert into new fence breach fusion table for each entry exit //no conditions

    //When switch is ON  and we are breaching a fence (entering) we will write that data to FT When switch is ON and we are breaching fence(exiting) we will write that data to FT as well.

    //status:exit
    if (geofenceTransitionString.equalsIgnoreCase("Exited")) {
        if (mPref.getBoolean("SWITCH", false)) {
            //Switch : ON
            //if switch is ON
            String timeValue = mPref.getString("Time_Interval", "60000");
            long configurableTime = Long.parseLong(timeValue);
            mEditor.putLong("CONFIG TIME", configurableTime);
            mEditor.commit();
            Intent intent = new Intent(this, MyLocationService.class);
            startService(intent);
            if (!mPref.getBoolean(geoFenceDetailString, false)) {
                credentials.insertIntoGeoFusionTables(
                        this.saveGeoFile(gaddress, gstatus, gEntryDate, gemail, "geofile"));
            }

        } else {
        }

    } else if (geofenceTransitionString.equalsIgnoreCase("Entered")) {//status :Entry

        if (mPref.getBoolean("SWITCH", false)) {

            if (!mPref.getBoolean(geoFenceDetailString, false)) {
                credentials.insertIntoGeoFusionTables(
                        this.saveGeoFile(gaddress, gstatus, gEntryDate, gemail, "geofile"));
            }

        } else {//Switch : OFF

        }
    }

    if (!mPref.getBoolean(geoFenceDetailString, false)) {
        isInserted = databaseHandler.addFenceTiming(
                new FenceTiming(triggeringGeofencesIdsList.toString(), geofenceTransitionString, gEntryDate));
        if (isInserted) {
            Log.e("GeofenceonsIS : ", "inserted to db");
        }
    }

    return geoFenceDetailString;
}

From source file:com.zjut.material_wecenter.Client.java

/**
 * publishQuestion ?//from   w ww.j a v a2 s.  c  o m
 * @param content 
 * @param detail 
 * @param topics ?
 * @return ?PublishQuestionResult
 */
public Result publishQuestion(String content, String detail, ArrayList<String> topics) {
    Map<String, String> params = new HashMap<>();
    params.put("question_content", content);
    params.put("question_detail", detail);
    // ??
    StringBuilder topic = new StringBuilder();
    if (!topics.isEmpty()) {
        topic.append(topics.get(0));
        for (int i = 1; i < topics.size(); i++)
            topic.append(',').append(topics.get(i));
    }
    params.put("topics", topics.toString());
    String json = doPost(Config.PUSHLISH_QUESTION, params);
    return getResult(json, PublishQuestion.class);
}

From source file:com.tobolkac.triviaapp.ScreenSlideActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);
    Bundle b = getIntent().getExtras();//  w w  w . j a  v  a2s  . c o  m
    Parse.initialize(this, "paHnFob0MGoBuy16Pzg5YPCH6TMOZfgZPXEOY1em",
            "1WOoBPDmOAu9CbHfvKIGmNIt2mY32mEvBYoLcPLV");
    ParseAnalytics.trackAppOpened(getIntent());
    //        questionNums = b.getIntArray("questionsNumArray");
    //        cat = b.getString("category");
    timerTextView = (TextView) findViewById(R.id.gameTimer);
    timerTextView.setText("2:00");
    cdt.start();

    //set up vibrator
    vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    //Challenging (Creating Game)
    if (b.getString("com.parse.Data") == null && b.getString("gameId") == null) {
        isChallenger = true;
        //          userList.setText("Challenging");
        challengedUser = getIntent().getStringExtra("opponentName");
        cat = b.getString("category");
        Log.d("category", "category: " + cat);
        questionNums = getIntent().getIntegerArrayListExtra("questionNumArray");

        //query to batch retrieve questions
        ParseQuery<ParseObject> queryQuestions = ParseQuery.getQuery("Questions");
        queryQuestions.whereEqualTo("category", cat);
        queryQuestions.whereContainedIn("categoryIndex", questionNums);
        /*queryQuestions.findInBackground(new FindCallback<ParseObject>() {
                
        @Override
        public void done(List<ParseObject> objects, ParseException e) {
          Log.d("questions retrieved", "number: " + objects.size());
          questions = objects;
        }
        });*/

        correctArray = new int[questionNums.size()];
        for (int i = 0; i < correctArray.length; i++) {
            correctArray[i] = 0;
        }
        try {
            questions = queryQuestions.find();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("questionNums after",
                "In ScrrenSlideActivity: " + questionNums.toString() + " " + questions.size());

    } else {
        //Being Challenged (From Homescreen)
        if (b.getString("gameId") != null) {
            gameId = b.getString("gameId");
        } else {
            try {
                JSONObject data = new JSONObject(b.getString("com.parse.Data"));
                gameId = data.getString("gameId");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        isChallenger = false;

        ParseQuery<ParseObject> query = ParseQuery.getQuery("Games");
        try {
            ParseObject gameObj = query.get(gameId);
            challenger = gameObj.getString("challenger");
            opponent = gameObj.getString("opponent");
            cat = gameObj.getString("category");
            //getting question array from game object
            JSONArray q = gameObj.getJSONArray("questionsArray");
            Log.d("Json array", "length: " + q.length());
            ArrayList<Integer> stuff = new ArrayList<Integer>();
            for (int s = 0; s < q.length(); s++) {
                stuff.add((Integer) q.get(s));
            }

            Log.d("opponent questions Array", stuff.toString());

            //query to grab questions by category and number
            ParseQuery<ParseObject> queryQuestions = ParseQuery.getQuery("Questions");
            queryQuestions.whereEqualTo("category", cat);
            queryQuestions.whereContainedIn("categoryIndex", stuff);

            correctArray = new int[stuff.size()];
            for (int i = 0; i < correctArray.length; i++) {
                correctArray[i] = 0;
            }
            try {
                questions = queryQuestions.find();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // Instantiate a ViewPager and a PagerAdapter.
    mPager = (ViewPager) findViewById(R.id.pager);
    FragmentManager manager = getSupportFragmentManager();
    mPagerAdapter = new ScreenSlidePagerAdapter(manager);
    mPager.setAdapter(mPagerAdapter);
    mPager.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            return true;
        }
    });
    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            // When changing pages, reset the action bar actions since they are dependent
            // on which page is currently active. An alternative approach is to have each
            // fragment expose actions itself (rather than the activity exposing actions),
            // but for simplicity, the activity provides the actions in this sample.

            questionProgress.setCorrectArray(correctArray);
            questionProgress.setNumCorrect(position + 1);

            invalidateOptionsMenu();
        }
    });

    timerTextView = (TextView) findViewById(R.id.gameTimer);
    startTime = System.currentTimeMillis();

    questionProgress = ((CorrectQuestionView) findViewById(R.id.questionProgress));
    questionProgress.setQuestionProgress(true);
    questionProgress.setNumCorrect(1);
    questionProgress.setCorrectArray(correctArray);

}

From source file:org.openhab.binding.somfytahoma.handler.SomfyTahomaBridgeHandler.java

private void processStateChangedEvent(SomfyTahomaEvent event) {
    String deviceUrl = event.getDeviceUrl();
    ArrayList<SomfyTahomaState> states = event.getDeviceStates();
    logger.debug("States for device {} : {}", deviceUrl, states.toString());
    Thing thing = getThingByDeviceUrl(deviceUrl);

    if (thing != null) {
        logger.debug("Updating status of thing: {}", thing.getUID().getId());
        SomfyTahomaBaseThingHandler handler = (SomfyTahomaBaseThingHandler) thing.getHandler();

        if (handler != null) {
            // update thing status
            handler.updateThingStatus(states);
            handler.updateThingChannels(states);
        }//  ww  w  .jav a 2  s .  c om
    } else {
        logger.debug("Thing handler is null, probably not bound thing.");
    }
}

From source file:com.swcguild.springmvcwebapp.controller.FactorizerController.java

@RequestMapping(value = "/factorizer", method = RequestMethod.POST)
public String doPost(HttpServletRequest request, Model model) {

    try {// w ww. j  a va 2  s .  c  o  m

        myAnswer = request.getParameter("myAnswer");
        ArrayList<Integer> factors = new ArrayList<>();
        sumOfFactors = 0;
        factorsAre = "";
        isOrIsNotPerfect = "";
        isOrIsNotPrime = "";
        message = "";
        int inputNum = Integer.parseInt(myAnswer);

        for (int i = 1; i < inputNum; i++) {
            if (inputNum % i == 0) {
                factors.add(i);
                //System.out.println(i);
                sumOfFactors = sumOfFactors + i;
            }
        }

        if (sumOfFactors != inputNum) {
            isOrIsNotPerfect = "not";
        }

        if (sumOfFactors != 1) {
            isOrIsNotPrime = "not";
        }

        model.addAttribute("inputNum", inputNum);
        model.addAttribute("factors",
                factors.toString().replace("[", "").replace("]", "").trim() + ", " + myAnswer);
        model.addAttribute("isOrIsNotPerfect", isOrIsNotPerfect);
        model.addAttribute("isOrIsNotPrime", isOrIsNotPrime);

    } catch (NumberFormatException e) {

    }

    return "factorizerResponse";
}

From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java

/***************************************************************************
 * Process the HTTP Post request/*  www .ja v a  2 s.  c  o  m*/
 ***************************************************************************/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    boolean checkedContent = false;
    boolean legend = false;
    String strErrorMessage = "";
    String serverUrl = request.getParameter("url");
    log.info("POST param serverUrl: " + serverUrl);
    if (serverUrl.startsWith("legend")) {
        serverUrl = serverUrl.replace("legend", "");
        serverUrl = serverUrl.replace("?", "&");
        serverUrl = serverUrl.replaceFirst("&", "?");
        legend = true;
    }
    serverUrl = checkTypeRequest(serverUrl);
    // log.info("serverUrl ckecked: " + serverUrl);
    if (!serverUrl.equals("ERROR")) {
        if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) {
            PostMethod httppost = null;
            try {
                if (log.isDebugEnabled()) {
                    Enumeration<?> e = request.getHeaderNames();
                    while (e.hasMoreElements()) {
                        String name = (String) e.nextElement();
                        String value = request.getHeader(name);
                        log.debug("request header:" + name + ":" + value);
                    }
                }
                HttpClient client = new HttpClient();
                httppost = new PostMethod(serverUrl);
                // PATH
                httppost.setDoAuthentication(false);
                httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(3, false));
                // FIN_PATH
                // PATH_MAPEAEDITA_SECURITY - AP
                // PATCH_TICKET_MJM-20112405-POST
                String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210
                if (authorizationValue == null) {
                    // The 'Authorization' header must be in this form ->
                    // Authorization: Basic <encodedLogin>
                    // 'encodedLogin' is a string in the form 'user:pass'
                    // that has been encoded by way of the Base64 algorithm.
                    // More info on this can be found at
                    // http://en.wikipedia.org/wiki/Basic_access_authentication
                    String user = (String) request.getSession().getAttribute("user");
                    String pass = (String) request.getSession().getAttribute("pass");
                    if (user != null && pass != null) {
                        String userAndPass = user + ":" + pass;
                        String encodedLogin = new String(
                                org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes()));
                        httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                    } else { // MJM - 20110520
                        String ticketParameter = request.getParameter("ticket");
                        if (ticketParameter != null) {
                            ticketParameter = ticketParameter.trim();
                            if (!ticketParameter.isEmpty()) {
                                Ticket ticket = TicketFactory.createInstance();
                                try {
                                    Map<String, String> props = ticket.getProperties(ticketParameter);
                                    user = props.get("user");
                                    pass = props.get("pass");
                                    String userAndPass = user + ":" + pass;
                                    String encodedLogin = new String(org.apache.commons.codec.binary.Base64
                                            .encodeBase64(userAndPass.getBytes()));
                                    httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin);
                                } catch (Exception e) {
                                    log.info("-------------------------------------------");
                                    log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS");
                                    log.info("METHOD: doPost");
                                    log.info("TICKET VALUE: " + ticketParameter);
                                    log.info("-------------------------------------------");
                                }
                            }
                        }
                    }
                } else {
                    httppost.addRequestHeader(AUTHORIZATION, authorizationValue);
                }
                // FIN_PATH_TICKET_MJM-20112405-POST
                // FIN_PATH_MAPEAEDITA_SECURITY - AP
                String body = inputStreamAsString(request.getInputStream());
                StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null);
                if (0 == httppost.getParameters().length) {
                    log.debug("No Name/Value pairs found ... pushing as received"); // PATCH
                    httppost.setRequestEntity(bodyEntity); // PATCH
                }
                if (log.isDebugEnabled()) {
                    log.debug("Body = " + body);
                    NameValuePair[] nameValuePairs = httppost.getParameters();
                    log.debug("NameValuePairs found: " + nameValuePairs.length);
                    for (int i = 0; i < nameValuePairs.length; ++i) {
                        log.debug("parameters:" + nameValuePairs[i].toString());
                    }
                }
                if (!legend)
                    client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
                if (soap) {
                    httppost.addRequestHeader("SOAPAction", serverUrl);
                }
                client.executeMethod(httppost);
                // PATH_FOLLOW_REDIRECT_POST
                int j = 0;
                String redirectLocation;
                Header locationHeader = httppost.getResponseHeader("location");
                while (locationHeader != null && j < numMaxRedirects) {
                    redirectLocation = locationHeader.getValue();
                    // AGG 20111304 Aadimos el cuerpo de la peticin POST a
                    // la nueva peticin redirigida
                    // String bodyPost = httppost.getResponseBodyAsString();
                    StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null);
                    httppost.releaseConnection();
                    httppost = new PostMethod(redirectLocation);
                    // AGG 20110912 Aadidas cabeceras peticin SOAP
                    if (redirectLocation.toLowerCase().contains("wsdl")) {
                        redirectLocation = serverUrl.replace("?wsdl", "");
                        httppost.addRequestHeader("SOAPAction", redirectLocation);
                        httppost.addRequestHeader("Content-type", "text/xml");
                    }
                    httppost.setRequestEntity(bodyEntityPost);
                    client.executeMethod(httppost);
                    locationHeader = httppost.getResponseHeader("location");
                    j++;
                }
                log.info("Number of followed redirections: " + j);
                if (locationHeader != null && j == numMaxRedirects) {
                    log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed.");
                }
                // FIN_PATH_FOLLOW_REDIRECT_POST
                if (log.isDebugEnabled()) {
                    Header[] responseHeaders = httppost.getResponseHeaders();
                    for (int i = 0; i < responseHeaders.length; ++i) {
                        String headerName = responseHeaders[i].getName();
                        String headerValue = responseHeaders[i].getValue();
                        log.debug("responseHeaders:" + headerName + "=" + headerValue);
                    }
                }
                // dump response to out
                if (httppost.getStatusCode() == HttpStatus.SC_OK) {
                    // PATH_SECURITY_PROXY - AG
                    Header[] respHeaders = httppost.getResponseHeaders();
                    int compSize = httppost.getResponseBody().length;
                    ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders));
                    String headersString = headerList.toString();
                    checkedContent = checkContent(headersString, compSize, serverUrl);
                    // FIN_PATH_SECURITY_PROXY - AG
                    if (checkedContent == true) {
                        /*
                         * checks if it has requested an getfeatureinfo to modify the response content
                         * type.
                         */
                        String requesteredUrl = request.getParameter("url");
                        if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/plain");
                        } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("application/gml+xml");
                        } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) {
                            response.setContentType("text/html");
                        } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch")
                                || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) {
                            response.setContentType("application/json");
                        } else {
                            response.setContentType("text/xml");
                        }
                        if (legend) {
                            String responseBody = httppost.getResponseBodyAsString();
                            if (responseBody.contains("ServiceExceptionReport")
                                    && serverUrl.contains("LegendGraphic")) {
                                response.sendRedirect("Componente/img/blank.gif");
                            } else {
                                response.setContentLength(responseBody.length());
                                PrintWriter out = response.getWriter();
                                out.print(responseBody);
                                response.flushBuffer();
                            }
                        } else {
                            // Patch_AGG 20112505 Prevents IE cache
                            if (request.getProtocol().compareTo("HTTP/1.0") == 0) {
                                response.setHeader("Pragma", "no-cache");
                            } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) {
                                response.setHeader("Cache-Control", "no-cache");
                            }
                            response.setDateHeader("Expires", -1);
                            // END patch
                            // Copy request to response
                            InputStream st = httppost.getResponseBodyAsStream();
                            final ServletOutputStream sos = response.getOutputStream();
                            IOUtils.copy(st, sos);
                        }
                    } else {
                        strErrorMessage += errorType;
                        log.error(strErrorMessage);
                    }
                } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                    response.addHeader(WWW_AUTHENTICATE,
                            httppost.getResponseHeader(WWW_AUTHENTICATE).getValue());
                } else {
                    strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString())
                            .concat(" ").concat(httppost.getResponseBodyAsString());
                    log.error("Unexpected failure: " + httppost.getStatusLine().toString());
                }
                httppost.releaseConnection();
                // AGG 20110927 Avoid Throwable (change it with exceptions)
            } catch (Exception e) {
                log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e);
            } finally {
                if (httppost != null) {
                    httppost.releaseConnection();
                }
            }
        } else {
            strErrorMessage += "Only HTTP(S) protocol supported";
            log.error("Only HTTP(S) protocol supported");
            // throw new
            // ServletException("only HTTP(S) protocol supported");
        }
    }
    // There are errors.
    if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) {
        if (strErrorMessage.equals("") == true) {
            strErrorMessage = "Error en el parametro url de entrada";
        }
        // String errorXML = strErrorMessage;
        String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage
                + "</descripcion></error>";
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            out.print(errorXML);
            response.flushBuffer();
        } catch (Exception e) {
            log.error(e);
        }
    }
    log.info("-------- End POST method --------");
}

From source file:UserInterface.Supplier.SalesOverviewJPanel.java

private void findTopProduct() {
    int max = 0;/*from  ww  w.  j a v  a2s  .com*/
    int current = 0;
    String currentPName = "null";
    ArrayList<String> currentPList = new ArrayList<>();
    currentPList.add("null");
    DefaultTableModel dtm = (DefaultTableModel) performanceJTable.getModel();
    for (int i = 0; i < dtm.getRowCount(); i++) {
        current = (int) dtm.getValueAt(i, 1);
        if (max < current) {
            max = current;
            currentPName = (String) dtm.getValueAt(i, 0);
            currentPList.clear();
            currentPList.add(currentPName);
        } else if (max == current) {
            currentPName = (String) dtm.getValueAt(i, 0);
            currentPList.add(currentPName);
        }
    }
    topSellingJLabel.setText(currentPList.toString());

}

From source file:com.hackensack.umc.activity.ProfileActivity.java

private ArrayList<CardResponse> parseCarddata(String cardResponse) {
    Gson gson = new Gson();
    try {//from  ww w. j  a v a  2 s  .  c om
        Type listType = new TypeToken<List<CardResponse>>() {
        }.getType();
        List<CardResponse> cardResponses = (List<CardResponse>) gson.fromJson(cardResponse, listType);
        ArrayList<CardResponse> cardResponseList = (ArrayList) cardResponses;
        Log.v(TAG, cardResponseList.toString());
        CardResponse cardRes = cardResponseList.get(0);
        Log.v(TAG, "CardResponse Data:as obj:" + cardRes.toString());
        return cardResponseList;
    } catch (Exception e) {

        return null;

    }

}

From source file:org.adaway.service.ApplyService.java

/**
 * Apply hosts file/* w w  w .  j a v a 2  s  .c o  m*/
 *
 * @return return code
 */
int apply() {
    showApplyNotification(mService, mService.getString(R.string.apply_dialog),
            mService.getString(R.string.apply_dialog), mService.getString(R.string.apply_dialog_hostnames));

    int returnCode = StatusCodes.SUCCESS; // default return code
    BufferedOutputStream bos = null;

    try {
        /* PARSE: parse hosts files to sets of hostnames and comments */

        FileInputStream fis = mService.openFileInput(Constants.DOWNLOADED_HOSTS_FILENAME);

        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        // Use whitelist and/or redirection rules from hosts sources only if enabled in preferences
        HostsParser parser = new HostsParser(reader, PreferenceHelper.getWhitelistRules(mService),
                PreferenceHelper.getRedirectionRules(mService));

        fis.close();

        updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
                mService.getString(R.string.apply_dialog_lists));

        /* READ DATABSE CONTENT */

        // add whitelist from db
        parser.addWhitelist(ProviderHelper.getEnabledWhitelistHashSet(mService));
        // add blacklist from db
        parser.addBlacklist(ProviderHelper.getEnabledBlacklistHashSet(mService));
        // add redirection list from db
        parser.addRedirectionList(ProviderHelper.getEnabledRedirectionListHashMap(mService));

        // get hosts sources list from db
        ArrayList<String> enabledHostsSources = ProviderHelper.getEnabledHostsSourcesArrayList(mService);
        Log.d(Constants.TAG, "Enabled hosts sources list: " + enabledHostsSources.toString());

        // compile lists (removing whitelist entries, etc.)
        parser.compileList();

        /* BUILD: build one hosts file out of sets and preferences */
        updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
                mService.getString(R.string.apply_dialog_hosts));

        FileOutputStream fos = mService.openFileOutput(Constants.HOSTS_FILENAME, Context.MODE_PRIVATE);

        bos = new BufferedOutputStream(fos);

        // build current timestamp for header
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();

        // add adaway header
        String header = Constants.HEADER1 + Constants.LINE_SEPERATOR + "# " + formatter.format(now)
                + Constants.LINE_SEPERATOR + Constants.HEADER2 + Constants.LINE_SEPERATOR
                + Constants.HEADER_SOURCES;
        bos.write(header.getBytes());

        // write sources into header
        String source = null;
        for (String host : enabledHostsSources) {
            source = Constants.LINE_SEPERATOR + "# " + host;
            bos.write(source.getBytes());
        }

        bos.write(Constants.LINE_SEPERATOR.getBytes());

        String redirectionIP = PreferenceHelper.getRedirectionIP(mService);

        // add "127.0.0.1 localhost" entry
        String localhost = Constants.LINE_SEPERATOR + Constants.LOCALHOST_IPv4 + " "
                + Constants.LOCALHOST_HOSTNAME + Constants.LINE_SEPERATOR + Constants.LOCALHOST_IPv6 + " "
                + Constants.LOCALHOST_HOSTNAME;
        bos.write(localhost.getBytes());

        bos.write(Constants.LINE_SEPERATOR.getBytes());

        // write hostnames
        String line;
        String linev6;
        if (PreferenceHelper.getEnableIpv6(mService)) {
            for (String hostname : parser.getBlacklist()) {
                line = Constants.LINE_SEPERATOR + redirectionIP + " " + hostname;
                linev6 = Constants.LINE_SEPERATOR + "::1" + " " + hostname;
                bos.write(line.getBytes());
                bos.write(linev6.getBytes());
            }
        } else {
            for (String hostname : parser.getBlacklist()) {
                line = Constants.LINE_SEPERATOR + redirectionIP + " " + hostname;
                bos.write(line.getBytes());
            }
        }

        /* REDIRECTION LIST: write redirection items */
        String redirectionItemHostname;
        String redirectionItemIP;
        for (HashMap.Entry<String, String> item : parser.getRedirectionList().entrySet()) {
            redirectionItemHostname = item.getKey();
            redirectionItemIP = item.getValue();

            line = Constants.LINE_SEPERATOR + redirectionItemIP + " " + redirectionItemHostname;
            bos.write(line.getBytes());
        }

        // hosts file has to end with new line, when not done last entry won't be
        // recognized
        bos.write(Constants.LINE_SEPERATOR.getBytes());

    } catch (FileNotFoundException e) {
        Log.e(Constants.TAG, "file to read or file to write could not be found", e);

        returnCode = StatusCodes.PRIVATE_FILE_FAIL;
    } catch (IOException e) {
        Log.e(Constants.TAG, "files can not be written or read", e);

        returnCode = StatusCodes.PRIVATE_FILE_FAIL;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, "Error closing output streams", e);
        }
    }

    // delete downloaded hosts file from private storage
    mService.deleteFile(Constants.DOWNLOADED_HOSTS_FILENAME);

    /* APPLY: apply hosts file using RootTools in copyHostsFile() */
    updateApplyNotification(mService, mService.getString(R.string.apply_dialog),
            mService.getString(R.string.apply_dialog_apply));

    Shell rootShell = null;
    try {
        rootShell = Shell.startRootShell();
    } catch (Exception e) {
        Log.e(Constants.TAG, "Problem opening a root shell!", e);
    }

    // copy build hosts file with RootTools, based on target from preferences
    try {
        if (PreferenceHelper.getApplyMethod(mService).equals("writeToSystem")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToDataData")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_DATA_DATA_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToData")) {

            ApplyUtils.copyHostsFile(mService, Constants.ANDROID_DATA_HOSTS, rootShell);
        } else if (PreferenceHelper.getApplyMethod(mService).equals("customTarget")) {

            ApplyUtils.copyHostsFile(mService, PreferenceHelper.getCustomTarget(mService), rootShell);
        }
    } catch (NotEnoughSpaceException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.NOT_ENOUGH_SPACE;
    } catch (RemountException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.REMOUNT_FAIL;
    } catch (CommandException e) {
        Log.e(Constants.TAG, "Exception: ", e);

        returnCode = StatusCodes.COPY_FAIL;
    }

    // delete generated hosts file from private storage
    mService.deleteFile(Constants.HOSTS_FILENAME);

    /*
     * Set last_modified_local dates in database to last_modified_online, got in download task
     */
    ProviderHelper.updateAllEnabledHostsSourcesLastModifiedLocalFromOnline(mService);

    /* check if hosts file is applied with chosen method */
    // check only if everything before was successful
    if (returnCode == StatusCodes.SUCCESS) {
        if (PreferenceHelper.getApplyMethod(mService).equals("writeToSystem")) {

            /* /system/etc/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_SYSTEM_ETC_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToDataData")) {

            /* /data/data/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_DATA_DATA_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(Constants.ANDROID_DATA_DATA_HOSTS, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("writeToData")) {

            /* /data/data/hosts */

            if (!ApplyUtils.isHostsFileCorrect(mService, Constants.ANDROID_DATA_HOSTS)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(Constants.ANDROID_DATA_HOSTS, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        } else if (PreferenceHelper.getApplyMethod(mService).equals("customTarget")) {

            /* custom target */

            String customTarget = PreferenceHelper.getCustomTarget(mService);

            if (!ApplyUtils.isHostsFileCorrect(mService, customTarget)) {
                returnCode = StatusCodes.APPLY_FAIL;
            } else {
                if (!ApplyUtils.isSymlinkCorrect(customTarget, rootShell)) {
                    returnCode = StatusCodes.SYMLINK_MISSING;
                }
            }
        }
    }

    try {
        rootShell.close();
    } catch (Exception e) {
        Log.e(Constants.TAG, "Problem closing the root shell!", e);
    }

    /* check if APN proxy is set */
    if (returnCode == StatusCodes.SUCCESS) {
        if (ApplyUtils.isApnProxySet(mService)) {
            Log.d(Constants.TAG, "APN proxy is set!");
            returnCode = StatusCodes.APN_PROXY;
        }
    }

    return returnCode;
}

From source file:org.helm.rest.AjaxTool.java

Response OnCmd(String cmd, Map<String, String> items, HttpServletRequest request) throws Exception {
    JSONObject ret = new JSONObject();
    switch (cmd) {
    case "helm.toolkit.monomer.json": {
        ArrayList<JSONObject> ret2 = getToolkitMonomers();
        ret.put("list", ret2);
    }// w w w.j  a v  a2 s  . c  o  m
        break;
    case "helm.toolkit.monomer.downloadjson": {
        ArrayList<JSONObject> ret2 = getToolkitMonomers();
        String s = "org.helm.webeditor.Monomers.loadDB(" + ret2.toString() + ");";
        return Response.status(Response.Status.OK).entity(s).build();
    }

    case "helm.monomer.del":
        LoadRules();
        ret = monomers.DelRecord(items.get("id"));
        if (ret != null) {
            try {
                monomers.Save();
            } catch (Exception e) {
                throw e;
            }
        }
        break;
    case "helm.monomer.load":
        LoadMonomers();
        ret = monomers.LoadRow(items.get("id"));
        break;
    case "helm.monomer.save": {
        LoadMonomers();
        String[] keys = monomers.getKeys();
        String[] row = new String[keys.length];
        for (int i = 0; i < keys.length; ++i) {
            row[i] = items.get(keys[i]);
        }

        ret = monomers.SaveRecord(row);
        if (ret != null) {
            try {
                monomers.Save();
            } catch (Exception e) {
                throw e;
            }
        }
    }
        break;
    case "helm.monomer.suggest":
        break;
    case "helm.monomer.list": {
        LoadMonomers();
        int page = ToInt(items.get("page"));
        int countperpage = ToInt(items.get("countperpage"));
        String polymertype = items.get("polymertype");
        String monomertype = items.get("monomertype");
        String symbol = items.get("symbol");
        ret = monomers.List(page, countperpage, "polymertype", polymertype, "monomertype", monomertype,
                "symbol", symbol);
    }
        break;
    case "helm.monomer.all": {
        LoadMonomers();
        ret.put("monomers", monomers.AsJSON());
    }
        break;
    case "helm.monomer.json": {
        LoadMonomers();
        ArrayList<JSONObject> ret2 = monomers.AsJSON();
        ret.put("list", ret2);
    }
        break;
    case "helm.monomer.downloadjson": {
        LoadMonomers();
        ArrayList<JSONObject> ret2 = monomers.AsJSON();
        String s = "org.helm.webeditor.Monomers.loadDB(" + ret2.toString() + ");";
        return Response.status(Response.Status.OK).entity(s).build();
    }
    case "helm.monomer.filelocation": {
        ret = new JSONObject();
        ret.put("momomers",
                DEFAULT_HELM_DIR + System.getProperty("file.separator") + DEFAULT_MONOMERS_FILE_NAME);
    }
        break;

    case "helm.rule.del":
        LoadRules();
        ret = rules.DelRecord(items.get("id"));
        if (ret != null) {
            try {
                rules.Save();
            } catch (Exception e) {
                throw e;
            }
        }
        break;
    case "helm.rule.load":
        LoadRules();
        ret = rules.LoadRow(items.get("id"));
        break;
    case "helm.rule.save": {
        LoadRules();
        String[] keys = rules.getKeys();
        String[] row = new String[keys.length];
        for (int i = 0; i < keys.length; ++i) {
            row[i] = items.get(keys[i]);
        }

        ret = rules.SaveRecord(row);
        if (ret != null) {
            try {
                rules.Save();
            } catch (Exception e) {
                throw e;
            }
        }
    }
        break;
    case "helm.rule.list": {
        LoadRules();
        int page = ToInt(items.get("page"));
        int countperpage = ToInt(items.get("countperpage"));
        String category = items.get("category");
        ret = rules.List(page, countperpage, "category", category, null, null, null, null);
    }
        break;
    case "helm.rule.all": {
        LoadRules();
        ret.put("rules", rules.AsJSON());
    }
        break;
    case "helm.rule.downloadjson":
    case "helm.rules.downloadjson": {
        LoadRules();
        ArrayList<JSONObject> ret2 = rules.AsJSON();
        String s = "org.helm.webeditor.RuleSet.loadDB(" + ret2.toString() + ");";
        return Response.status(Response.Status.OK).entity(s).build();
    }

    case "openjsd": {
        ret = new JSONObject();
        Part part = request.getPart("file");
        String filename = getFileName(part);
        String contents = getValue(part);
        ret.put("filename", filename);
        ret.put("base64", Database.EncodeBase64(contents));
        String s = "<html><head></head><body><textarea>" + wrapAjaxResult(ret) + "</textarea></body></html>";
        return Response.status(Response.Status.OK).entity(s).type("text/html").build();
    }
    case "savefile": {
        String filename = items.get("filename");
        String contents = items.get("contents");
        return Response.ok(contents, "application/unknown")
                .header("content-disposition", "attachment;filename=" + filename).build();
    }
    case "helm.properties":
        ret = CalculateProperties(items.get("helm"));
        break;

    case "cleanup":
        ret = Cleanup(items.get("input"), items.get("inputformat"));
        break;

    default:
        return Response.status(Response.Status.OK).entity(wrapAjaxError("Unknown cmd: " + cmd)).build();
    }

    return Response.status(Response.Status.OK).entity(wrapAjaxResult(ret)).build();
}