Example usage for java.util ArrayList contains

List of usage examples for java.util ArrayList contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_link.java

@Override
public ArrayList<String> getAttributesColumnsHeaders() {
    ArrayList<String> attColumnsHeaders = new ArrayList<>();
    for (Link link : getVisibleElementsInTable())
        for (Map.Entry<String, String> entry : link.getAttributes().entrySet())
            if (attColumnsHeaders.contains(entry.getKey()) == false)
                attColumnsHeaders.add(entry.getKey());
    return attColumnsHeaders;
}

From source file:com.redhat.jenkins.nodesharingbackend.Api.java

/**
 * Report workload to be executed on orchestrator for particular executor master.
 *
 * The order of items from orchestrator is preserved though not guaranteed to be exactly the same as the builds ware
 * scheduled on individual executor Jenkinses.
 *///from www  .j a v a  2s.  c om
@RequirePOST
public void doReportWorkload(@Nonnull final StaplerRequest req, @Nonnull final StaplerResponse rsp)
        throws IOException {
    Jenkins.getActiveInstance().checkPermission(RestEndpoint.RESERVE);

    Pool pool = Pool.getInstance();
    final ConfigRepo.Snapshot config = pool.getConfig(); // Fail early when there is no config

    final ReportWorkloadRequest request = Entity.fromInputStream(req.getInputStream(),
            ReportWorkloadRequest.class);

    final List<ReportWorkloadRequest.Workload.WorkloadItem> reportedItems = request.getWorkload().getItems();
    final ArrayList<ReservationTask> reportedTasks = new ArrayList<>(reportedItems.size());
    final ExecutorJenkins executor;
    try {
        executor = config.getJenkinsByUrl(request.getExecutorUrl());
    } catch (NoSuchElementException ex) {
        rsp.setStatus(HttpServletResponse.SC_CONFLICT);
        rsp.getWriter().println(unknownExecutor(request.getExecutorUrl(), pool.getConfigRepoUrl()));
        return;
    }

    for (ReportWorkloadRequest.Workload.WorkloadItem item : reportedItems) {
        reportedTasks.add(new ReservationTask(executor, item.getLabel(), item.getName(), item.getId()));
    }

    Queue.withLock(new Runnable() {
        @Override
        public void run() {
            Queue queue = Jenkins.getActiveInstance().getQueue();
            for (Queue.Item item : queue.getItems()) {
                if (item.task instanceof ReservationTask
                        && ((ReservationTask) item.task).getOwner().equals(executor)) {
                    // Cancel items executor is no longer interested in and keep those it cares for
                    if (!reportedTasks.contains(item.task)) {
                        queue.cancel(item);
                    }
                    reportedTasks.remove(item.task);
                }
            }

            // These might have been reported just before the build started the execution on Executor so now the
            // ReservationTask might be executing or even completed on executor, though there is no way for orchestrator
            // to know. This situation will be handled by executor rejecting the `utilizeNode` call.
            for (ReservationTask newTask : reportedTasks) {
                queue.schedule2(newTask, 0);
            }
        }
    });

    String version = this.version;
    new ReportWorkloadResponse(pool.getConfigRepoUrl(), version).toOutputStream(rsp.getOutputStream());
}

From source file:com.sforce.cd.apexUnit.client.fileReader.ApexManifestFileReader.java

private void insertIntoTestClassesArray(String strLine, ArrayList<String> testClassList) {
    String tempTestClassId = null;
    Map<String, String> namespaceAndName = new HashMap<String, String>();
    namespaceAndName.put("name", strLine);

    String soql = QueryConstructor.generateQueryToFetchApexClass(namespaceAndName.get("namespace"),
            namespaceAndName.get("name"));
    // query using WSC
    tempTestClassId = ApexClassFetcherUtils.fetchAndAddToMapApexClassIdBasedOnName(
            ConnectionHandler.getConnectionHandlerInstance().getConnection(), soql);
    LOG.debug("tempTestClassId: " + tempTestClassId);

    //triggers are included only for code coverage and not for tests to avoid exception by the platform
    if (tempTestClassId == null && includeTriggers) {
        // look if the given class name is a trigger if its not ApexClass
        String soqlForTrigger = QueryConstructor.generateQueryToFetchApexTrigger(
                namespaceAndName.get("namespace"), namespaceAndName.get("name"));
        // query using WSC
        tempTestClassId = ApexClassFetcherUtils.fetchAndAddToMapApexClassIdBasedOnName(
                ConnectionHandler.getConnectionHandlerInstance().getConnection(), soqlForTrigger);
        LOG.debug("tempTestClassId(TriggerId: " + tempTestClassId);
    }/*from w  ww .  j  a  v a 2  s  .  c o m*/
    if (tempTestClassId != null) {
        if (!testClassList.contains(tempTestClassId)) {
            testClassList.add(tempTestClassId);
            ApexClassFetcherUtils.apexClassMap.put(tempTestClassId, strLine);
        } else {
            LOG.warn("Duplicate entry found in manifest file for : " + strLine
                    + " . Skipping multiple execution/code coverage computation of this test class/source class");
            ApexClassFetcherUtils.duplicateApexClassMap.put(tempTestClassId, strLine);
        }

    } else {
        LOG.warn("The class " + strLine + " does not exist in the org.");
        if (!nonExistantApexClassEntries.contains(strLine)) {
            nonExistantApexClassEntries.add(strLine);
        }
    }
}

From source file:de.tuebingen.uni.sfs.germanet.api.GermaNet.java

/**
 * Returns a <code>List</code> of all <code>Synsets</code> with the
 * specified <code>WordCategory</code> in which <code>orthForm</code> occurs
 * as main orthographical form in one of its <code>LexUnits</code> -- in
 * case <code>considerAllOrthForms</code> is true. Else returns a
 * <code>List</code> of all <code>Synsets</code> in which
 * <code>orthForm</code> occurs as as main orthographical form, as
 * orthographical variant, as old orthographical form, or as old
 * orthographic variant in one of its <code>LexUnits</code> -- in case
 * <code>considerAllOrthForms</code> is false. It uses the
 * <code>ignoreCase</code> flag as set in the constructor.
 * @param orthForm the <code>orthForm</code> to be found
 * @param wordCategory the <code>WordCategory</code> of the
 * <code>Synsets</code> to be found (e.g. <code>WordCategory.adj</code>)
 * @param considerMainOrthFormOnly considering main orthographical form only
 * (<code>true</code>) or all variants (<code>false</code>)
 * @return a <code>List</code> of <code>Synsets</code> with the specified
 * <code>orthForm</code> and <code>wordCategory</code>.
 *///from w w w. j  a  va2 s  . co m
public List<Synset> getSynsets(String orthForm, WordCategory wordCategory, boolean considerMainOrthFormOnly) {
    /*
     * This method can probably be removed since it is very rare that
     * an orthForm is contained in more than one word class
     */
    ArrayList<Synset> rval = new ArrayList<Synset>();
    HashMap<String, ArrayList<LexUnit>> map;
    List<LexUnit> tmpList;

    if (ignoreCase) {
        orthForm = orthForm.toLowerCase();
    }

    if (considerMainOrthFormOnly) {
        map = wordCategoryMap.get(wordCategory);
    } else {
        map = wordCategoryMapAllOrthForms.get(wordCategory);
    }
    if (map != null) {
        tmpList = map.get(orthForm);
        if (tmpList != null) {
            for (LexUnit lu : tmpList) {
                if (!rval.contains(lu.getSynset())) {
                    rval.add(lu.getSynset());
                }
            }
        }
    }
    rval.trimToSize();
    return rval;
}

From source file:com.idega.company.business.impl.CompanyServiceImpl.java

protected ArrayList<User> getUsersByRoles(Collection<String> roles) {
    if (ListUtil.isEmpty(roles)) {
        getLogger().warning("Roles are not provided");
        return null;
    }/* www  .  ja v  a2  s  .  c  o  m*/

    ArrayList<User> users = new ArrayList<User>();
    GroupBusiness groupBusiness = getGroupBusiness();
    if (groupBusiness == null) {
        return null;
    }

    UserBusiness userBusiness = getUserBusiness();
    if (userBusiness == null) {
        return null;
    }

    AccessController accessController = CoreUtil.getIWContext().getAccessController();
    for (String roleKey : roles) {
        Collection<Group> groupsByRole = accessController.getAllGroupsForRoleKey(roleKey,
                CoreUtil.getIWContext());
        if (ListUtil.isEmpty(groupsByRole)) {
            continue;
        }

        for (Group group : groupsByRole) {
            if (StringUtil.isEmpty(group.getName())) {
                try {
                    User user = userBusiness.getUser(Integer.valueOf(group.getId()));
                    if (accessController.hasRole(user, roleKey) && !users.contains(user)) {
                        users.add(user);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                }
            }

            Collection<User> usersInGroup = null;
            try {
                usersInGroup = groupBusiness.getUsers(group);
            } catch (FinderException e) {
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (!ListUtil.isEmpty(usersInGroup)) {
                for (User user : usersInGroup) {
                    if (!users.contains(user)) {
                        users.add(user);
                    }
                }
            }
        }
    }

    if (ListUtil.isEmpty(users)) {
        getLogger().warning("There are no users by role(s): " + roles);
    }
    return users;
}

From source file:edu.cornell.mannlib.vitro.webapp.dao.jena.IndividualSDB.java

private List<VClass> getMyVClasses(boolean assertedOnly) {
    List<VClass> vClassList = new ArrayList<VClass>();
    Model tempModel = null;// www  .  ja v a 2  s.co  m
    if (ind.getModel().contains((Resource) null, RDF.type, (RDFNode) null)) {
        tempModel = ind.getModel();
    } else {
        String getTypesQuery = buildMyVClassesQuery(assertedOnly);

        RDFService service = webappDaoFactory.getRDFService();
        try {
            tempModel = RDFServiceUtils.parseModel(
                    service.sparqlConstructQuery(getTypesQuery, RDFService.ModelSerializationFormat.N3),
                    RDFService.ModelSerializationFormat.N3);
        } catch (RDFServiceException e) {
            throw new RuntimeException(e);
        }
    }
    StmtIterator stmtItr = tempModel.listStatements((Resource) null, RDF.type, (RDFNode) null);
    LinkedList<String> list = new LinkedList<String>();
    while (stmtItr.hasNext()) {
        Statement stmt = stmtItr.nextStatement();
        if (stmt.getObject().isResource() && !stmt.getObject().isAnon()) {
            list.add(((Resource) stmt.getObject()).getURI());
        }
    }
    Iterator<String> itr = null;
    VClassDao checkSubClass = this.webappDaoFactory.getVClassDao();
    boolean directTypes = false;
    String currentType = null;
    ArrayList<String> done = new ArrayList<String>();

    /* Loop for comparing starts here */
    if (assertedOnly) {
        while (!directTypes) {
            itr = list.listIterator();

            do {
                if (itr.hasNext()) {
                    currentType = itr.next();
                } else {
                    directTypes = true; // get next element for comparison
                    break;
                }
            } while (done.contains(currentType));

            if (directTypes)
                break;
            // check to see if it's all over otherwise start comparing
            else
                itr = list.listIterator();

            while (itr.hasNext()) {
                String nextType = itr.next();
                if (checkSubClass.isSubClassOf(currentType, nextType)
                        && !currentType.equalsIgnoreCase(nextType)) {
                    itr.remove();
                }
            }

            done.add(currentType); // add the uri to done list. 
        }
    }

    /* Loop for comparing ends here */
    Iterator<String> typeIt = list.iterator();

    for (Iterator it = typeIt; it.hasNext();) {
        Resource type = ResourceFactory.createResource(it.next().toString());
        String typeURI = (!type.isAnon()) ? type.getURI()
                : VitroVocabulary.PSEUDO_BNODE_NS + type.getId().toString();
        if (type.getNameSpace() == null
                || (!webappDaoFactory.getNonuserNamespaces().contains(type.getNameSpace()))) {
            VClass vc = webappDaoFactory.getVClassDao().getVClassByURI(type.getURI());
            if (vc != null) {
                vClassList.add(vc);
            }
        }
    }

    try {
        Collections.sort(vClassList);
    } catch (Exception e) {
        log.error("Unable to sort VClass list", e);
    }

    return vClassList;
}

From source file:lfsom.visualization.clustering.LFSKMeans.java

/**
 * like {@link #initClustersLinearly(DistanceMetric)}, but after computing
 * the exact linear point, rather finds & uses the closest instance from the
 * data set as centroid./*  w  w  w  .  j a  v a 2 s .  c o  m*/
 */
private void initClustersLinearlyOnInstances() {
    ArrayList<double[]> usedInstances = new ArrayList<double[]>(); // to
    // store
    // which
    // points
    // are
    // already
    // taken
    for (int clusterIndex = 0; clusterIndex < k; clusterIndex++) {
        double[] centroid = new double[numberOfAttributes];
        for (int attributeIndex = 0; attributeIndex < numberOfAttributes; attributeIndex++) {
            centroid[attributeIndex] = (maxValues[attributeIndex] - minValues[attributeIndex])
                    / (clusters.length + 1) * (clusterIndex + 1) + minValues[attributeIndex];
            // now find the closest real instance to this point
            double minDistance = Double.MAX_VALUE;
            double[] minData = null;
            try {
                for (int i = 0; i < data.length; i++) {
                    if (LFSL2Metric.distance(centroid, data[i]) < minDistance
                            && !usedInstances.contains(data[i]) || i == data.length - 1) {
                        minData = data[i];
                        minDistance = LFSL2Metric.distance(centroid, data[i]);
                    }
                }
                usedInstances.add(minData);
                centroid = minData.clone();
            } catch (LFSException e) {
                e.printStackTrace();
            }
        }
        clusters[clusterIndex] = new LFSCluster(centroid);
    }
}

From source file:de.suse.swamp.modules.actions.WorkflowActions.java

/**
 * Is called when a task ok comes in.//from  w w  w. j a  v a  2 s. com
 */
public void doTaskok(RunData data, Context context) throws Exception {
    Logger.LOG("doTaskok() from webapp.");
    SWAMPUser user = ((SWAMPTurbineUser) data.getUser()).getSWAMPUser();
    WorkflowAPI wfapi = new WorkflowAPI();
    TaskAPI taskapi = new TaskAPI();
    ResultList history = new ResultList();

    if (data.getParameters().containsKey("taskid")) {
        // get the task we're working on
        int taskId = data.getParameters().getInt("taskid");
        WorkflowTask task = taskapi.doGetTask(taskId, user.getUserName());
        String taskType = null;
        ArrayList validationErrors = new ArrayList();

        // Check for availability of that Task:
        if (task != null && task.getState() == WorkflowTask.ACTIVE) {
            // get the action type of the task
            taskType = task.getActionType();

            // fill in the result for different
            if (taskType.equals("manualtask")) {
                ManualtaskResult result = (ManualtaskResult) task.getResult();
                result.setDone(true);

            } else if (taskType.equals("decision")) {
                int answer = -1;
                // get the answer given
                if (data.getParameters().containsKey("answer")) {
                    answer = data.getParameters().getInt("answer");
                    Logger.DEBUG("Answer #" + answer);
                    // if no answer selected, log error
                } else {
                    Logger.ERROR("in doTaskok: no answer on question given.");
                }
                // put selection into result
                DecisionResult result = (DecisionResult) task.getResult();
                result.setSelection(answer);
            } else if (taskType.equals("dataedit")) {
                DataeditResult result = (DataeditResult) task.getResult();
                context.put("result", result);

                DataeditActionTemplate action = (DataeditActionTemplate) task.getActionTemplate();
                HashMap actionFields = action.getAllFields(task.getWorkflowId());
                Workflow wf = wfapi.getWorkflow(task.getWorkflowId(), user.getUserName());

                // put all values in the result object
                for (Iterator iter = actionFields.keySet().iterator(); iter.hasNext();) {
                    ArrayList setField = (ArrayList) actionFields.get(iter.next());
                    for (Iterator it = setField.iterator(); it.hasNext();) {
                        Field f = (Field) it.next();
                        String fieldpath = f.getPath();
                        String field = "field_" + fieldpath;
                        if (data.getParameters().containsKey(field)) {
                            // binary data need extra storage
                            if (f.getDatatype().equals("fileref")) {
                                FileItem value = data.getParameters().getFileItem(field);
                                Logger.DEBUG("Value for key (file)" + field + ": " + value);
                                // need to store the file now
                                Databit dbit = wf.getDatabit(fieldpath);
                                if (DatapackActions.storeFile(dbit, true, value, user.getUserName())) {
                                    String fileName = value.getName();
                                    // fix for browsers setting complete path as name: 
                                    if (fileName.indexOf("\\") >= 0)
                                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                                    if (fileName.indexOf("/") >= 0)
                                        fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                                    result.setValue(fieldpath, fileName);
                                }
                            } else if (f.getDatatype().equalsIgnoreCase("multienum")) {
                                SWAMPHashSet values = new SWAMPHashSet(data.getParameters().getStrings(field));
                                result.setValue(fieldpath, values.toString(", "));
                            } else if (f.getDatatype().equalsIgnoreCase("patchdocumd")) {
                                String value = data.getParameters().get(field);
                                Logger.DEBUG("Value for key " + field + ": " + value);
                                result.setValue(fieldpath, value);
                            } else {
                                String value = StringEscapeUtils.unescapeHtml(data.getParameters().get(field));
                                Logger.DEBUG("Value for key " + field + ": " + value);
                                result.setValue(fieldpath, value);
                            }
                        } else if (data.getParameters().containsKey("boolean_" + fieldpath)) {
                            result.setValue(fieldpath, "false");
                        } else if (!f.isMandatory()) {
                            // don't complain about missing, non-mandatory fields
                        } else {
                            Logger.ERROR("Mandatory field " + fieldpath + " not set.");
                        }
                    }
                }
            }
            // validate task result
            validationErrors = task.validate();

            // if everything is ok, try to finish the task
            if (validationErrors.size() == 0) {
                try {
                    taskapi.finishTask(task, user.getUserName(), history);
                } catch (Exception e) {
                    e.printStackTrace();
                    validationErrors.add(e.getMessage());
                }
            }

            if (validationErrors.size() == 0) {
                Logger.LOG("Webapp: Done with working on task with id " + task.getId());

                WorkflowTask wftask = task;
                Workflow wf = wfapi.getWorkflow(wftask.getWorkflowId(), user.getUserName());

                context.put("statusheader", "Success");
                context.put("statusmessage", "Task \"" + task.getReplacedDescription() + "\" done in workflow "
                        + wf.getName() + ".");

                context.put("statusclass", "success");
                context.put("icon", "ok");
                context.put("history", history);
                context.put("workflow", wf);

                // add general Workflow Help
                SWAMPScreen.addHelplink(wf.getTemplate(), context, user.getUserName());
                ArrayList helps = new ArrayList();
                if (context.get("helps") != null) {
                    helps = (ArrayList) context.get("helps");
                }

                // add helplinks if there are new Tasks:
                if (wf.getActiveTasks().size() > 0) {
                    List activeTasks = wf.getActiveTasks();
                    for (Iterator it = activeTasks.iterator(); it.hasNext();) {
                        WorkflowTask helptask = (WorkflowTask) it.next();
                        String helpConext = helptask.getActionTemplate().getHelpContext();
                        if (helpConext != null && !helpConext.equals("")) {
                            ContextHelp help = new DocumentationAPI().getContextHelp(helpConext,
                                    user.getUserName());
                            if (help != null && !helps.contains(help)) {
                                helps.add(help);
                            }
                        }
                    }
                    context.put("helps", helps);
                }

                if (user.getPerm("taskpage", "results").equals("workflow")) {
                    Logger.DEBUG("Doing redirect to workflow page after task for " + user.getUserName());
                    setTemplate(data, "DisplayWorkflow.vm");
                } else if (user.getPerm("taskpage", "results").equals("previous")) {
                    CircularFifoBuffer pageBuffer = (CircularFifoBuffer) data.getUser().getTemp("pageBuffer",
                            new CircularFifoBuffer(2));
                    SWAMPHashMap params = (SWAMPHashMap) pageBuffer.get();
                    if (params != null && params.containsKey("template")) {
                        Logger.DEBUG("Redirect to previous page (" + params.get("template") + ") for "
                                + user.getUserName());
                        data.getParameters().clear();
                        for (Iterator it = params.keySet().iterator(); it.hasNext();) {
                            String key = (String) it.next();
                            data.getParameters().add(key, (String) params.get(key));
                        }
                        setTemplate(data, (String) params.get("template"));
                    } else {
                        Logger.WARN("Desired redirect not possible, no pageBuffer");
                    }
                }

                // if there were errors during validation, log the error
            } else {
                // go back to the Task-Page
                context.put("taskerror", "true");
                setTemplate(data, "DisplayTask.vm");

                Iterator errIter = validationErrors.iterator();
                String message = "", error;
                while (errIter.hasNext()) {
                    error = (String) errIter.next();
                    message = message + "<br />" + error;
                    Logger.ERROR(error);
                }
                message = message + "<p />Please correct the above mistake!";
                context.put("statusclass", "error");
                context.put("statusheader", "Error validating task");
                context.put("statusmessage", message);
                context.put("icon", "error");

                // fix page buffer
                CircularFifoBuffer pageBuffer = (CircularFifoBuffer) data.getUser().getTemp("pageBuffer",
                        new CircularFifoBuffer(2));
                pageBuffer.add(pageBuffer.get());
            } // end validation

        } else {
            // illegal task requested, redirect
            setTemplate(data, "DisplayTask.vm");
        }

    } else {
        Logger.ERROR("in doTaskok: no task id.");
    } //end taskid
}

From source file:net.morematerials.manager.UpdateManager.java

private void convertBlock(YamlConfiguration oldYaml, YamlConfiguration newYaml, String materialName,
        ArrayList<String> containedFiles) throws Exception {
    // This one is renamed because in the future items can fork items.
    if (oldYaml.contains("BlockID")) {
        newYaml.set("BaseId", oldYaml.getInt("BlockID"));
    }/*from  w w w.  j  a  v a 2 s  .c  o m*/

    // Rotation was never officially, but we will support 1.7.1 changes.
    if (oldYaml.contains("Rotate")) {
        newYaml.set("Rotation", oldYaml.getBoolean("Rotate"));
    }

    // Texture was a magic-function before. Replacing it now by correct one.
    newYaml.set("Texture", materialName + ".png");

    // Also there were no coords before, so we need to automatically calculate them for now.
    ArrayList<String> coords = new ArrayList<String>();
    BufferedImage bufferedImage = ImageIO.read(new File(this.tempDir, materialName + ".png"));
    Integer textureCount = bufferedImage.getWidth() / bufferedImage.getHeight();
    for (Integer i = 0; i < textureCount; i++) {
        coords.add("" + (i * bufferedImage.getHeight()) + " 0 " + bufferedImage.getHeight() + " "
                + bufferedImage.getHeight());
    }
    newYaml.set("Coords", coords);

    // Shape was also a magic function before, replacing that now.
    if (containedFiles.contains(materialName + ".shape")) {
        newYaml.set("Shape", materialName + ".shape");
    }

    // We can simply copy hardness...
    if (oldYaml.contains("Hardness")) {
        newYaml.set("Hardness", oldYaml.getDouble("Hardness"));
    }

    // Also the friction...
    if (oldYaml.contains("Friction")) {
        newYaml.set("Friction", oldYaml.getDouble("Friction"));
    }

    // Also the drop stuff...
    if (oldYaml.contains("ItemDrop")) {
        newYaml.set("ItemDrop", oldYaml.getString("ItemDrop"));
    }
    if (oldYaml.contains("ItemDropAmount")) {
        newYaml.set("ItemDropAmount", oldYaml.getInt("ItemDropAmount"));
    }

    // And at last the lightlevel!
    if (oldYaml.contains("LightLevel")) {
        newYaml.set("LightLevel", oldYaml.getDouble("LightLevel"));
    }

    // Cannot convert handlers! (They are coded, so we really can't!)
    if (oldYaml.contains("WalkAction.Handler") || oldYaml.contains("Rclick.Handler")
            || oldYaml.contains("Lclick.Handler") || oldYaml.contains("RedstonePowered.Handler")) {
        this.plugin.getUtilsManager()
                .log(" - " + materialName + " uses handlers, they cannot be converted automatically.");
    }
}

From source file:com.irccloud.android.activity.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                cloud, 0xff0b2e60));//from w w  w  .  java  2  s . co  m
        cloud.recycle();
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    setContentView(R.layout.activity_login);

    loading = findViewById(R.id.loading);

    connecting = findViewById(R.id.connecting);
    connectingMsg = (TextView) findViewById(R.id.connectingMsg);
    progressBar = (ProgressBar) findViewById(R.id.connectingProgress);

    loginHint = (LinearLayout) findViewById(R.id.loginHint);
    signupHint = (LinearLayout) findViewById(R.id.signupHint);
    hostHint = (TextView) findViewById(R.id.hostHint);

    login = findViewById(R.id.login);
    name = (EditText) findViewById(R.id.name);
    if (savedInstanceState != null && savedInstanceState.containsKey("name"))
        name.setText(savedInstanceState.getString("name"));
    email = (AutoCompleteTextView) findViewById(R.id.email);
    if (BuildConfig.ENTERPRISE)
        email.setHint(R.string.email_enterprise);
    ArrayList<String> accounts = new ArrayList<String>();
    AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
    for (Account a : am.getAccounts()) {
        if (a.name.contains("@") && !accounts.contains(a.name))
            accounts.add(a.name);
    }
    if (accounts.size() > 0)
        email.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                accounts.toArray(new String[accounts.size()])));

    if (savedInstanceState != null && savedInstanceState.containsKey("email"))
        email.setText(savedInstanceState.getString("email"));

    password = (EditText) findViewById(R.id.password);
    password.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                new LoginTask().execute((Void) null);
                return true;
            }
            return false;
        }
    });
    if (savedInstanceState != null && savedInstanceState.containsKey("password"))
        password.setText(savedInstanceState.getString("password"));

    host = (EditText) findViewById(R.id.host);
    if (BuildConfig.ENTERPRISE)
        host.setText(NetworkConnection.IRCCLOUD_HOST);
    else
        host.setVisibility(View.GONE);
    host.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                new LoginTask().execute((Void) null);
                return true;
            }
            return false;
        }
    });
    if (savedInstanceState != null && savedInstanceState.containsKey("host"))
        host.setText(savedInstanceState.getString("host"));
    else
        host.setText(getSharedPreferences("prefs", 0).getString("host", BuildConfig.HOST));

    if (host.getText().toString().equals("api.irccloud.com")
            || host.getText().toString().equals("www.irccloud.com"))
        host.setText("");

    loginBtn = (Button) findViewById(R.id.loginBtn);
    loginBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new LoginTask().execute((Void) null);
        }
    });
    loginBtn.setFocusable(true);
    loginBtn.requestFocus();

    sendAccessLinkBtn = (Button) findViewById(R.id.sendAccessLink);
    sendAccessLinkBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            new ResetPasswordTask().execute((Void) null);
        }
    });

    nextBtn = (Button) findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (host.getText().length() > 0) {
                NetworkConnection.IRCCLOUD_HOST = host.getText().toString();
                trimHost();

                new EnterpriseConfigTask().execute((Void) null);
            }
        }
    });

    TOS = (TextView) findViewById(R.id.TOS);
    TOS.setMovementMethod(new LinkMovementMethod());

    forgotPassword = (TextView) findViewById(R.id.forgotPassword);
    forgotPassword.setOnClickListener(forgotPasswordClickListener);

    enterpriseLearnMore = (TextView) findViewById(R.id.enterpriseLearnMore);
    enterpriseLearnMore.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isPackageInstalled("com.irccloud.android", LoginActivity.this)) {
                startActivity(getPackageManager().getLaunchIntentForPackage("com.irccloud.android"));
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("market://details?id=com.irccloud.android")));
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=com.irccloud.android")));
                }
            }
        }

        private boolean isPackageInstalled(String packagename, Context context) {
            PackageManager pm = context.getPackageManager();
            try {
                pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
                return true;
            } catch (NameNotFoundException e) {
                return false;
            }
        }
    });
    enterpriseHint = (LinearLayout) findViewById(R.id.enterpriseHint);

    EnterYourEmail = (TextView) findViewById(R.id.enterYourEmail);

    signupHint.setOnClickListener(signupHintClickListener);
    loginHint.setOnClickListener(loginHintClickListener);

    signupBtn = (Button) findViewById(R.id.signupBtn);
    signupBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            new LoginTask().execute((Void) null);
        }
    });

    TextView version = (TextView) findViewById(R.id.version);
    try {
        version.setText("Version " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
    } catch (NameNotFoundException e) {
        version.setVisibility(View.GONE);
    }

    Typeface LatoRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
    Typeface LatoLightItalic = Typeface.createFromAsset(getAssets(), "Lato-LightItalic.ttf");

    for (int i = 0; i < signupHint.getChildCount(); i++) {
        View v = signupHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    for (int i = 0; i < loginHint.getChildCount(); i++) {
        View v = loginHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    LinearLayout IRCCloud = (LinearLayout) findViewById(R.id.IRCCloud);
    for (int i = 0; i < IRCCloud.getChildCount(); i++) {
        View v = IRCCloud.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    notAProblem = (LinearLayout) findViewById(R.id.notAProblem);
    for (int i = 0; i < notAProblem.getChildCount(); i++) {
        View v = notAProblem.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface((i == 0) ? LatoRegular : LatoLightItalic);
        }
    }

    loginSignupHint = (LinearLayout) findViewById(R.id.loginSignupHint);
    for (int i = 0; i < loginSignupHint.getChildCount(); i++) {
        View v = loginSignupHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
            ((TextView) v).setOnClickListener((i == 0) ? loginHintClickListener : signupHintClickListener);
        }
    }

    name.setTypeface(LatoRegular);
    email.setTypeface(LatoRegular);
    password.setTypeface(LatoRegular);
    host.setTypeface(LatoRegular);
    loginBtn.setTypeface(LatoRegular);
    signupBtn.setTypeface(LatoRegular);
    TOS.setTypeface(LatoRegular);
    EnterYourEmail.setTypeface(LatoRegular);
    hostHint.setTypeface(LatoLightItalic);

    if (BuildConfig.ENTERPRISE) {
        name.setVisibility(View.GONE);
        email.setVisibility(View.GONE);
        password.setVisibility(View.GONE);
        loginBtn.setVisibility(View.GONE);
        signupBtn.setVisibility(View.GONE);
        TOS.setVisibility(View.GONE);
        signupHint.setVisibility(View.GONE);
        loginHint.setVisibility(View.GONE);
        forgotPassword.setVisibility(View.GONE);
        loginSignupHint.setVisibility(View.GONE);
        EnterYourEmail.setVisibility(View.GONE);
        sendAccessLinkBtn.setVisibility(View.GONE);
        notAProblem.setVisibility(View.GONE);
        enterpriseLearnMore.setVisibility(View.VISIBLE);
        enterpriseHint.setVisibility(View.VISIBLE);
        host.setVisibility(View.VISIBLE);
        nextBtn.setVisibility(View.VISIBLE);
        hostHint.setVisibility(View.VISIBLE);
        host.requestFocus();
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("signup")
            && savedInstanceState.getBoolean("signup")) {
        signupHintClickListener.onClick(null);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("login")
            && savedInstanceState.getBoolean("login")) {
        loginHintClickListener.onClick(null);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("forgotPassword")
            && savedInstanceState.getBoolean("forgotPassword")) {
        forgotPasswordClickListener.onClick(null);
    }

    mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean("resolving_error", false);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Auth.CREDENTIALS_API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}