Example usage for java.util Map toString

List of usage examples for java.util Map toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.apache.zeppelin.submarine.job.thread.JobRunThread.java

public void run() {
    boolean tryLock = lockRunning.tryLock();
    if (false == tryLock) {
        LOGGER.warn("Can not get JobRunThread lockRunning!");
        return;/*from  w  w  w. j av  a2  s .  c o m*/
    }

    SubmarineUI submarineUI = submarineJob.getSubmarineUI();
    try {
        InterpreterContext intpContext = submarineJob.getIntpContext();
        String noteId = intpContext.getNoteId();
        String userName = intpContext.getAuthenticationInfo().getUser();
        String jobName = SubmarineUtils.getJobName(userName, noteId);

        if (true == running.get()) {
            String message = String.format("Job %s already running.", jobName);
            submarineUI.outputLog("WARN", message);
            LOGGER.warn(message);
            return;
        }
        running.set(true);

        Properties properties = submarineJob.getProperties();
        HdfsClient hdfsClient = submarineJob.getHdfsClient();
        File pythonWorkDir = submarineJob.getPythonWorkDir();

        submarineJob.setCurrentJobState(EXECUTE_SUBMARINE);

        String algorithmPath = properties.getProperty(SubmarineConstants.SUBMARINE_ALGORITHM_HDFS_PATH, "");
        if (!algorithmPath.startsWith("hdfs://")) {
            String message = "Algorithm file upload HDFS path, " + "Must be `hdfs://` prefix. now setting "
                    + algorithmPath;
            submarineUI.outputLog("Configuration error", message);
            return;
        }

        List<ParagraphInfo> paragraphInfos = intpContext.getIntpEventClient().getParagraphList(userName,
                noteId);
        String outputMsg = hdfsClient.saveParagraphToFiles(noteId, paragraphInfos,
                pythonWorkDir == null ? "" : pythonWorkDir.getAbsolutePath(), properties);
        if (!StringUtils.isEmpty(outputMsg)) {
            submarineUI.outputLog("Save algorithm file", outputMsg);
        }

        HashMap jinjaParams = SubmarineUtils.propertiesToJinjaParams(properties, submarineJob, true);

        URL urlTemplate = Resources.getResource(SubmarineJob.SUBMARINE_JOBRUN_TF_JINJA);
        String template = Resources.toString(urlTemplate, Charsets.UTF_8);
        Jinjava jinjava = new Jinjava();
        String submarineCmd = jinjava.render(template, jinjaParams);
        // If the first line is a newline, delete the newline
        int firstLineIsNewline = submarineCmd.indexOf("\n");
        if (firstLineIsNewline == 0) {
            submarineCmd = submarineCmd.replaceFirst("\n", "");
        }

        StringBuffer sbLogs = new StringBuffer(submarineCmd);
        submarineUI.outputLog("Submarine submit command", sbLogs.toString());

        long timeout = Long
                .valueOf(properties.getProperty(SubmarineJob.TIMEOUT_PROPERTY, SubmarineJob.defaultTimeout));
        CommandLine cmdLine = CommandLine.parse(SubmarineJob.shell);
        cmdLine.addArgument(submarineCmd, false);
        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog watchDog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchDog);
        StringBuffer sbLogOutput = new StringBuffer();
        executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
            @Override
            protected void processLine(String line, int level) {
                line = line.trim();
                if (!StringUtils.isEmpty(line)) {
                    sbLogOutput.append(line + "\n");
                }
            }
        }));

        if (Boolean.valueOf(properties.getProperty(SubmarineJob.DIRECTORY_USER_HOME))) {
            executor.setWorkingDirectory(new File(System.getProperty("user.home")));
        }

        Map<String, String> env = new HashMap<>();
        String launchMode = (String) jinjaParams.get(SubmarineConstants.INTERPRETER_LAUNCH_MODE);
        if (StringUtils.equals(launchMode, "yarn")) {
            // Set environment variables in the submarine interpreter container run on yarn
            String javaHome, hadoopHome, hadoopConf;
            javaHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_JAVA_HOME);
            hadoopHome = (String) jinjaParams.get(SubmarineConstants.DOCKER_HADOOP_HDFS_HOME);
            hadoopConf = (String) jinjaParams.get(SubmarineConstants.SUBMARINE_HADOOP_CONF_DIR);
            env.put("JAVA_HOME", javaHome);
            env.put("HADOOP_HOME", hadoopHome);
            env.put("HADOOP_HDFS_HOME", hadoopHome);
            env.put("HADOOP_CONF_DIR", hadoopConf);
            env.put("YARN_CONF_DIR", hadoopConf);
            env.put("CLASSPATH", "`$HADOOP_HDFS_HOME/bin/hadoop classpath --glob`");
            env.put("ZEPPELIN_FORCE_STOP", "true");
        }

        LOGGER.info("Execute EVN: {}, Command: {} ", env.toString(), submarineCmd);
        AtomicBoolean cmdLineRunning = new AtomicBoolean(true);
        executor.execute(cmdLine, env, new DefaultExecuteResultHandler() {
            @Override
            public void onProcessComplete(int exitValue) {
                String message = String.format("jobName %s ProcessComplete exit value is : %d", jobName,
                        exitValue);
                LOGGER.info(message);
                submarineUI.outputLog("JOR RUN COMPLETE", message);
                cmdLineRunning.set(false);
                submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_FINISHED);
            }

            @Override
            public void onProcessFailed(ExecuteException e) {
                String message = String.format("jobName %s ProcessFailed exit value is : %d, exception is : %s",
                        jobName, e.getExitValue(), e.getMessage());
                LOGGER.error(message);
                submarineUI.outputLog("JOR RUN FAILED", message);
                cmdLineRunning.set(false);
                submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
            }
        });
        int loopCount = 100;
        while ((loopCount-- > 0) && cmdLineRunning.get() && running.get()) {
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.destroyProcess();
            Thread.sleep(1000);
        }
        if (watchDog.isWatching()) {
            watchDog.killedProcess();
        }

        // Check if it has been submitted to YARN
        Map<String, Object> jobState = submarineJob.getJobStateByYarn(jobName);
        loopCount = 50;
        while ((loopCount-- > 0) && !jobState.containsKey("state") && running.get()) {
            Thread.sleep(3000);
            jobState = submarineJob.getJobStateByYarn(jobName);
        }

        if (!jobState.containsKey("state")) {
            String message = String.format("JOB %s was not submitted to YARN!", jobName);
            LOGGER.error(message);
            submarineUI.outputLog("JOR RUN FAILED", message);
            submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        submarineJob.setCurrentJobState(EXECUTE_SUBMARINE_ERROR);
        submarineUI.outputLog("Exception", e.getMessage());
    } finally {
        running.set(false);
        lockRunning.unlock();
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.util.EntityAssociationUpdateHelper.java

public void update() throws RepositoryException {
    //Initiliaze ids and other variables which will be used through this update
    initialise();/* w w w . ja  v a  2s . c  om*/

    loadExistingValues();

    //Values to be added will replace existing values
    //Before that we must isolate all values that
    //must be removed from associations
    //and all values that should be added to associations
    Map<String, T> newValuesMapToBeAdded = new LinkedHashMap<String, T>();

    List<String> listOfNewIdsToBeAdded = new ArrayList<String>();

    if (CollectionUtils.isNotEmpty(valuesToBeAdded)) {

        for (T valueToAdd : valuesToBeAdded) {

            String idToBeAdded = valueToAdd.getId();

            if (StringUtils.isBlank(idToBeAdded))
                throw new CmsException("Cms Repository Entity does not have an id");

            newValuesMapToBeAdded.put(idToBeAdded, valueToAdd);

            listOfNewIdsToBeAdded.add(idToBeAdded);
        }
    }

    ValueFactory valueFactory = session.getValueFactory();

    //Replace values in JCR Node
    if (isReferrerPropertyNameMultivalue) {
        JcrNodeUtils.addMultiValueProperty(referrerNodeWhichContainsProperty, referrerPropertyName,
                SaveMode.UPDATE, listOfNewIdsToBeAdded, ValueType.String, valueFactory);
    } else {
        if (newValuesMapToBeAdded != null && newValuesMapToBeAdded.size() > 1) {
            throw new CmsException("Must update single value property " + referrerPropertyName.getJcrName()
                    + " in node " + referrerNodeWhichContainsProperty.getPath()
                    + " but found more than one values " + newValuesMapToBeAdded.toString());
        }

        JcrNodeUtils.addSimpleProperty(SaveMode.UPDATE, referrerNodeWhichContainsProperty, referrerPropertyName,
                CollectionUtils.isEmpty(listOfNewIdsToBeAdded) ? null : listOfNewIdsToBeAdded.get(0), //Expecting at most one value 
                valueFactory, ValueType.String);
    }

}

From source file:org.metis.push.PusherBean.java

/**
 * This method is called by the web socket container after a new
 * connection/session has been established with this server endpoint. This
 * method will attempt to subscribe the client based on any query params and
 * if no params were provide, will use the URL's extra path info.
 *///from w  w w  .  j av  a2 s. com
public void afterConnectionEstablished(WebSocketSession session) throws Exception {

    super.afterConnectionEstablished(session);

    LOG.debug(getBeanName() + ":afterConnectionEstablished - session id = " + session.getId());

    // place the session in the global session registry. it will be removed
    // from the registry when it is closed
    WdsSocketSession wds = new WdsSocketSession(session);
    getWdsSessions().put(session.getId(), wds);

    // based on the query string (if any), attempt to find a SqlStmnt for
    // this session
    Map<String, String> map = Utils.getQueryMap(session.getUri().getQuery());

    SqlStmnt sqlStmnt = (map == null || map.isEmpty()) ? SqlStmnt.getMatch(getSqlStmnts4Get(), null)
            : SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet());

    // if statement was not found and query params were provided, then
    // close connection because search for statement had to take place based
    // on query params provided. in other words, if client provides query
    // params then it is requesting a subscrption via those params.
    if (sqlStmnt == null && (map != null && !map.isEmpty())) {
        LOG.error(getBeanName() + ":afterConnectionEstablished - unable to find sql "
                + "statement with this incoming param set: " + map.toString());
        session.close(POLICY_VIOLATION);
        return;
    }

    // if statement was not found and params were not provided, then attempt
    // to find statement based on the url's "extra path" info
    if (sqlStmnt == null) {
        LOG.trace(getBeanName() + ":afterConnectionEstablished - unable to find sql "
                + "statement on first pass, will attempt to use extra path info");
        String[] xtraPathInfo = Utils.getExtraPathInfo(session.getUri().toString());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
            // put the xtra path info in the bucket and try again
            map = (map == null) ? new HashMap<String, String>() : map;
            map.clear();
            map.put(xtraPathInfo[0], xtraPathInfo[1]);
            // try again with the extra path info
            sqlStmnt = SqlStmnt.getMatch(getSqlStmnts4Get(), map.keySet());
            // if statement could not be found, then simply return - client
            // may later subscribe with valid params
            if (sqlStmnt == null) {
                LOG.debug(getBeanName() + ":findStmnt - unable to find sql "
                        + "statement with this xtra path info: " + map.toString());
                return;
            }
        } else {
            // there was no extra path info, so simply return
            return;
        }
    }

    mainLock.lock();
    try {
        // if we've gotten this far, a SqlStmnt was found based on query or
        // extra path info, now see if SqlStmnt already has a job with the
        // same param set (map). if no job was found, then create and start
        // one
        if (sqlStmnt.findSqlJob(map, wds) == null) {
            sqlStmnt.createSqlJob(map, wds);
        }
    } finally {
        mainLock.unlock();
    }
}

From source file:com.stvn.nscreen.my.MyPurchaseListFragment.java

public void requestGetAssetInfoDetail(final JSONObject object) {
    ((MyMainActivity) getActivity()).showProgressDialog("", getString(R.string.wait_a_moment));
    String assetId = "";
    String terminalKey = "";
    try {// w w  w.j  a  va  2s .c o m
        assetId = object.getString("assetId");
        terminalKey = mPref.getWebhasTerminalKey();
        assetId = URLDecoder.decode(assetId, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String url = mPref.getWebhasServerUrl() + "/getAssetInfo.json?version=1&terminalKey=" + terminalKey
            + "&assetProfile=9&assetId=" + assetId;
    JYStringRequest request = new JYStringRequest(mPref, Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    ((MyMainActivity) getActivity()).hideProgressDialog();

                    try {
                        JSONObject jo = new JSONObject(response);
                        if (jo.getString("resultCode").equals("100")) { // success
                            JSONObject asset = jo.getJSONObject("asset");
                            String assetId = asset.getString("assetId");
                            String primaryAssetId = "";
                            String episodePeerExistence = "";
                            String contentGroupId = "";
                            String rating = asset.getString("rating");
                            if (rating.startsWith("19") && mPref.isAdultVerification() == false) {
                                String alertTitle = "??? ";
                                String alertMsg1 = getActivity().getString(R.string.error_not_adult1);
                                String alertMsg2 = getActivity().getString(R.string.error_not_adult2);
                                CMAlertUtil.Alert1(getActivity(), alertTitle, alertMsg1, alertMsg2, false, true,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Intent intent = new Intent(getActivity(),
                                                        CMSettingMainActivity.class);
                                                getActivity().startActivity(intent);
                                            }
                                        }, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        });
                            } else {
                                if (asset.isNull("assetId") == false) {
                                    assetId = asset.getString("assetId");
                                } else if (asset.isNull("primaryAssetId") == false) {
                                    assetId = asset.getString("primaryAssetId");
                                }

                                if (asset.isNull("primaryAssetId") == false) {
                                    primaryAssetId = asset.getString("primaryAssetId");
                                }

                                if (asset.isNull("episodePeerExistence") == false) {
                                    episodePeerExistence = asset.getString("episodePeerExistence");
                                }

                                if (asset.isNull("contentGroupId") == false) {
                                    contentGroupId = asset.getString("contentGroupId");
                                }

                                String productType = "";
                                if (asset.isNull("productType") == false) {
                                    productType = object.getString("productType");
                                    productType = productType.toLowerCase();
                                }

                                if (TextUtils.isEmpty(assetId) == false) {
                                    if (TextUtils.isEmpty(episodePeerExistence)) {
                                        Intent intent = new Intent(getActivity(), VodDetailActivity.class);
                                        intent.putExtra("assetId", assetId);
                                        startActivity(intent);
                                    } else {

                                        Intent intent = new Intent(getActivity(), VodDetailActivity.class);
                                        intent.putExtra("assetId", assetId);
                                        if ("1".equalsIgnoreCase(episodePeerExistence) == true) {
                                            intent.putExtra("episodePeerExistence", episodePeerExistence);
                                            intent.putExtra("contentGroupId", contentGroupId);
                                            intent.putExtra("primaryAssetId", primaryAssetId);
                                        }
                                        startActivity(intent);
                                    }
                                }

                            }
                        } else {
                            String alertTitle = getString(R.string.my_cnm_alert_title_expired);
                            String alertMessage1 = getString(R.string.my_cnm_alert_message1_expired);
                            CMAlertUtil.Alert(getActivity(), alertTitle, alertMessage1, "", true, false,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                        }
                                    }, true);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    ((MyMainActivity) getActivity()).hideProgressDialog();
                    if (mPref.isLogging()) {
                        VolleyLog.d("MyPurchaseListFragment", "onErrorResponse(): " + error.getMessage());
                    }
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("version", String.valueOf(1));
            params.put("areaCode", String.valueOf(0));
            if (mPref.isLogging()) {
                Log.d("MyPurchaseListFragment", "getParams()" + params.toString());
            }
            return params;
        }
    };
    mRequestQueue.add(request);

}

From source file:dev.meng.wikidata.revision.RevisionHistory.java

private void queryPageInfo(String lang, String pageId, PageInfo page) {
    Map<String, Object> params = new HashMap<>();
    params.put("format", "json");
    params.put("action", "query");
    params.put("pageids", pageId);
    params.put("prop", "info");
    try {//from   ww w  . j ava 2  s  . co  m
        String urlString = String.format(Configure.REVISION.API_ENDPOINT, lang) + "?"
                + StringUtils.mapToURLParameters(params, Configure.REVISION.DEFAULT_ENCODING);
        URL url = new URL(urlString);

        JSONObject response = HttpUtils.queryForJSONResponse(url, Configure.REVISION.DEFAULT_ENCODING);
        try {
            JSONObject pageInfo = response.getJSONObject("query").getJSONObject("pages").getJSONObject(pageId);
            page.setTitle(pageInfo.getString("title"));
            page.setSize(pageInfo.getLong("length"));
            page.setLastRevisionId(Long.toString(pageInfo.getLong("lastrevid")));

        } catch (JSONException ex) {
            Logger.log(this.getClass(), LogLevel.WARNING,
                    "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage());
        }

    } catch (UnsupportedEncodingException ex) {
        Logger.log(this.getClass(), LogLevel.WARNING,
                "Error in encoding: " + params.toString() + ", " + ex.getMessage());
    } catch (MalformedURLException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    } catch (IOException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    } catch (StringConvertionException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    }
}

From source file:it.chefacile.app.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = this;
    chefacileDb = new DatabaseHelper(this);
    // FilterButton = (ImageButton) findViewById(R.id.buttonfilter);
    TutorialButton = (ImageButton) findViewById(R.id.button);
    //  AddButton = (ImageButton) findViewById(R.id.button2);
    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    //Show = (ImageButton) findViewById(R.id.buttonShow);
    //Show2 = (ImageButton) findViewById(R.id.buttonShow2);
    materialAnimatedSwitch = (MaterialAnimatedSwitch) findViewById(R.id.pin);
    //buttoncuisine = (ImageButton) findViewById(R.id.btn_cuisine);
    //buttondiet = (ImageButton) findViewById(R.id.btn_diet);
    //buttonintol = (ImageButton) findViewById(R.id.btn_intoll);
    //Mostra = (Button) findViewById(R.id.btn_mostra);

    final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(1000); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(5); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE);

    ImageView icon = new ImageView(this); // Create an icon
    icon.setImageDrawable(getResources().getDrawable(R.drawable.logo));

    final com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton actionButton = new com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.Builder(
            this).setPosition(
                    com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.POSITION_RIGHT_CENTER)
                    .setContentView(icon).build();

    SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
    // repeat many times:
    ImageView dietIcon = new ImageView(this);
    dietIcon.setImageDrawable(getResources().getDrawable(R.drawable.diet));
    SubActionButton button1 = itemBuilder.setContentView(dietIcon).build();
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSingleChoiceDialogDiet(v);
        }/*ww w .jav a2 s  .  c  o  m*/
    });

    ImageView intolIcon = new ImageView(this);
    intolIcon.setImageDrawable(getResources().getDrawable(R.drawable.intoll));
    SubActionButton button2 = itemBuilder.setContentView(intolIcon).build();
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogIntol(v);
        }
    });

    ImageView cuisineIcon = new ImageView(this);
    cuisineIcon.setImageDrawable(getResources().getDrawable(R.drawable.cook12));
    SubActionButton button3 = itemBuilder.setContentView(cuisineIcon).build();
    button3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogCuisine(v);
        }
    });

    ImageView favouriteIcon = new ImageView(this);
    favouriteIcon.setImageDrawable(getResources().getDrawable(R.drawable.favorite));
    SubActionButton button4 = itemBuilder.setContentView(favouriteIcon).build();
    button4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSimpleListDialogFav(v);
        }
    });

    ImageView wandIcon = new ImageView(this);
    wandIcon.setImageDrawable(getResources().getDrawable(R.drawable.wand));
    SubActionButton button5 = itemBuilder.setContentView(wandIcon).build();
    button5.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sugg = getSuggestion();
            suggOccurrences = getCount();
            showSimpleListDialogSuggestions(v);
        }
    });

    final FloatingActionButton actionABC = (FloatingActionButton) findViewById(R.id.action_abc);

    actionABC.bringToFront();
    actionABC.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ingredients.length() < 2) {
                Snackbar.make(responseView, "Insert at least one ingredient", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            } else {
                new RetrieveFeedTask().execute();
            }
        }

        // Snackbar.make(view, "Non disponibile, mangia l'aria", Snackbar.LENGTH_LONG)
        //         .setAction("Action", null).show();

    });

    FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this).setStartAngle(90).setEndAngle(270)
            .addSubActionView(button1).addSubActionView(button2).addSubActionView(button3)
            .addSubActionView(button4).addSubActionView(button5).attachTo(actionButton).build();

    startDatabase(chefacileDb);

    for (int j = 0; j < cuisineItems.length; j++) {
        cuisineItems[j] = cuisineItems[j].substring(0, 1).toUpperCase() + cuisineItems[j].substring(1);
    }
    Arrays.sort(cuisineItems);

    for (int i = 0; i < 24; i++) {
        cuisineBool[i] = false;
    }

    Arrays.sort(intolItems);

    for (int i = 0; i < 11; i++) {
        intolBool[i] = false;
    }

    mListView = (MaterialListView) findViewById(R.id.material_listview);

    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

    TutorialButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, IntroScreenActivity.class));
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        }
    });

    iv = (ImageView) findViewById(R.id.imageView);
    iv.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clicks++;
            Log.d("CLICKS", String.valueOf(clicks));
            if (clicks == 15) {
                Log.d("IMAGE SHOWN", "mai vero");
                setBackground(iv);
            }
        }
    });

    materialAnimatedSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isChecked) {
            if (isChecked == true) {
                ranking = 2;
                Toast.makeText(getApplicationContext(), "Minimize missing ingredients", Toast.LENGTH_SHORT)
                        .show();
            } else {
                ranking = 1;
                Toast.makeText(getApplicationContext(), "Maximize used ingredients", Toast.LENGTH_SHORT).show();
            }
            Log.d("Ranking", String.valueOf(ranking));
        }
    });

    final CharSequence[] items = { "Maximize used ingredients", "Minimize missing ingredients" };

    editText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    if (!(editText.getText().toString().trim().equals(""))) {

                        String input;
                        String s1 = editText.getText().toString().substring(0, 1).toUpperCase();
                        String s2 = editText.getText().toString().substring(1);
                        input = s1 + s2;

                        Log.d("INPUT: ", input);
                        searchedIngredients.add(input);
                        Log.d("SEARCHED INGR LIST", searchedIngredients.toString());

                        if (!chefacileDb.findIngredientPREF(input)) {
                            if (chefacileDb.findIngredient(input)) {
                                chefacileDb.updateCount(input);
                                mapIngredients = chefacileDb.getDataInMapIngredient();
                                Map<String, Integer> map2;
                                map2 = sortByValue(mapIngredients);
                                Log.d("MAPPACOUNT: ", map2.toString());

                            } else {
                                if (chefacileDb.occursExceeded()) {
                                    //chefacileDb.deleteMinimum(input);
                                    // chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());

                                } else {
                                    chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());
                                }
                            }
                        }
                    }

                    if (editText.getText().toString().trim().equals("")) {
                        ingredients += editText.getText().toString().trim() + "";
                        editText.getText().clear();

                    } else {
                        ingredients += editText.getText().toString().replaceAll(" ", "+").trim().toLowerCase()
                                + ",";
                        singleIngredient = editText.getText().toString().trim().toLowerCase();
                        currentIngredient = singleIngredient;
                        new RetrieveIngredientTask().execute();

                        //adapter.add(singleIngredient.substring(0,1).toUpperCase() + singleIngredient.substring(1));
                    }

                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                    in.hideSoftInputFromWindow(editText.getApplicationWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                    actionABC.startAnimation(animation);

                    return true;
                default:
                    break;
                }
            }
            return false;
        }
    });

    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

}

From source file:com.cloud.network.security.SecurityGroupManagerImpl.java

protected String generateRulesetSignature(Map<PortAndProto, Set<String>> ingress,
        Map<PortAndProto, Set<String>> egress) {
    String ruleset = ingress.toString();
    ruleset.concat(egress.toString());//  w w  w.  ja v a  2s .c o m
    return DigestUtils.md5Hex(ruleset);
}

From source file:com.openshift.internal.restclient.capability.resources.DockerRegistryImageStreamImportCapability.java

/**
 * @return the token required to pull docker metadata
 *///from   w ww  .  ja  v  a 2 s .  co  m
private String retrieveAuthToken(HttpClient client, String details) throws Exception {
    if (StringUtils.isNotBlank(details)) {
        Map<String, String> auth = parseAuthDetails(details);
        if (auth.containsKey(REALM)) {
            Request request = createAuthRequest(client, auth);
            ContentResponse response = request.send();
            LOG.debug("Auth response: " + response.toString());
            if (response.getStatus() == STATUS_OK
                    && response.getHeaders().contains(PROPERTY_CONTENT_TYPE, MEDIATYPE_APPLICATION_JSON)) {
                ModelNode tokenNode = ModelNode.fromJSONString(response.getContentAsString());
                if (tokenNode.hasDefined(TOKEN)) {
                    return tokenNode.get(TOKEN).asString();
                } else {
                    LOG.debug("No auth token was found on auth response: " + tokenNode.toJSONString(false));
                }
            } else {
                LOG.info(
                        "Unable to retrieve authentication token as response was not OK and/or unexpected content type");
            }
        } else {
            LOG.info(
                    "Unable to retrieve authentication token - 'realm' was not found in the authenticate header: "
                            + auth.toString());
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.regionserver.TestSplitTransactionOnCluster.java

/**
 * If a table has regions that have no store files in a region, they should split successfully
 * into two regions with no store files.
 *///from   www .  j a v  a2 s  .  c o  m
@Test
public void testSplitRegionWithNoStoreFiles() throws Exception {
    final TableName tableName = TableName.valueOf("testSplitRegionWithNoStoreFiles");
    // Create table then get the single region for our new table.
    createTableAndWait(tableName.getName(), HConstants.CATALOG_FAMILY);
    List<HRegion> regions = cluster.getRegions(tableName);
    HRegionInfo hri = getAndCheckSingleTableRegion(regions);
    ensureTableRegionNotOnSameServerAsMeta(admin, hri);
    int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName());
    HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
    // Turn off balancer so it doesn't cut in and mess up our placements.
    this.admin.setBalancerRunning(false, true);
    // Turn off the meta scanner so it don't remove parent on us.
    cluster.getMaster().setCatalogJanitorEnabled(false);
    try {
        // Precondition: we created a table with no data, no store files.
        printOutRegions(regionServer, "Initial regions: ");
        Configuration conf = cluster.getConfiguration();
        HBaseFsck.debugLsr(conf, new Path("/"));
        Path rootDir = FSUtils.getRootDir(conf);
        FileSystem fs = TESTING_UTIL.getDFSCluster().getFileSystem();
        Map<String, Path> storefiles = FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName);
        assertEquals("Expected nothing but found " + storefiles.toString(), storefiles.size(), 0);

        // find a splittable region.  Refresh the regions list
        regions = cluster.getRegions(tableName);
        final HRegion region = findSplittableRegion(regions);
        assertTrue("not able to find a splittable region", region != null);

        // Now split.
        SplitTransaction st = new MockedSplitTransaction(region, Bytes.toBytes("row2"));
        try {
            st.prepare();
            st.execute(regionServer, regionServer);
        } catch (IOException e) {
            fail("Split execution should have succeeded with no exceptions thrown");
        }

        // Postcondition: split the table with no store files into two regions, but still have not
        // store files
        List<HRegion> daughters = cluster.getRegions(tableName);
        assertTrue(daughters.size() == 2);

        // check dirs
        HBaseFsck.debugLsr(conf, new Path("/"));
        Map<String, Path> storefilesAfter = FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName);
        assertEquals("Expected nothing but found " + storefilesAfter.toString(), storefilesAfter.size(), 0);

        hri = region.getRegionInfo(); // split parent
        AssignmentManager am = cluster.getMaster().getAssignmentManager();
        RegionStates regionStates = am.getRegionStates();
        long start = EnvironmentEdgeManager.currentTimeMillis();
        while (!regionStates.isRegionInState(hri, State.SPLIT)) {
            assertFalse("Timed out in waiting split parent to be in state SPLIT",
                    EnvironmentEdgeManager.currentTimeMillis() - start > 60000);
            Thread.sleep(500);
        }

        // We should not be able to assign it again
        am.assign(hri, true, true);
        assertFalse("Split region can't be assigned", regionStates.isRegionInTransition(hri));
        assertTrue(regionStates.isRegionInState(hri, State.SPLIT));

        // We should not be able to unassign it either
        am.unassign(hri, true, null);
        assertFalse("Split region can't be unassigned", regionStates.isRegionInTransition(hri));
        assertTrue(regionStates.isRegionInState(hri, State.SPLIT));
    } finally {
        admin.setBalancerRunning(true, false);
        cluster.getMaster().setCatalogJanitorEnabled(true);
    }
}