Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

In this page you can find the example usage for java.util HashMap isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.yahoo.ycsb.db.RadosClient.java

@Override
public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    byte[] buffer;

    try {/*from w w w . ja  v a 2  s  . co  m*/
        RadosObjectInfo info = ioctx.stat(key);
        buffer = new byte[(int) info.getSize()];

        ReadOp rop = ioctx.readOpCreate();
        ReadResult readResult = rop.queueRead(0, info.getSize());
        // TODO: more size than byte length possible;
        // rop.operate(key, Rados.OPERATION_NOFLAG); // for rados-java 0.3.0
        rop.operate(key, 0);
        // readResult.raiseExceptionOnError("Error ReadOP(%d)", readResult.getRVal()); // for rados-java 0.3.0
        if (readResult.getRVal() < 0) {
            throw new RadosException("Error ReadOP", readResult.getRVal());
        }
        if (info.getSize() != readResult.getBytesRead()) {
            return new Status("ERROR", "Error the object size read");
        }
        readResult.getBuffer().get(buffer);
    } catch (RadosException e) {
        return new Status("ERROR-" + e.getReturnValue(), e.getMessage());
    }

    JSONObject json = new JSONObject(new String(buffer, java.nio.charset.StandardCharsets.UTF_8));
    Set<String> fieldsToReturn = (fields == null ? json.keySet() : fields);

    for (String name : fieldsToReturn) {
        result.put(name, new StringByteIterator(json.getString(name)));
    }

    return result.isEmpty() ? Status.ERROR : Status.OK;
}

From source file:de.adorsys.forge.gwt.GWTPlugin.java

private void generateWidget(JavaResource resouce, String sufix, String javaTemplate, String uiTemplate,
        final PipeOut out) {
    try {/*from  ww  w. ja  v  a 2s  .  c  o  m*/
        JavaSource<?> javaSource = resouce.getJavaSource();
        if (javaSource instanceof JavaClass) {
            ResourceFacet resources = project.getFacet(ResourceFacet.class);
            JavaSourceFacet java = project.getFacet(JavaSourceFacet.class);
            GWTFacet gwtFacet = project.getFacet(GWTFacet.class);

            VelocityContext velocityContext = gwtFacet.createVelocityContext(null);

            HashMap<String, String> msgCollector = new HashMap<String, String>();
            velocityContext.put("msgCollector", msgCollector);
            velocityContext.put("javaSource", javaSource);

            StringWriter stringWriter;
            if (uiTemplate != null) {
                stringWriter = new StringWriter();
                velocityEngine.mergeTemplate(uiTemplate, "UTF-8", velocityContext, stringWriter);
                String fqViewName = java.getBasePackage().concat(".widgets.").concat(javaSource.getName())
                        .concat(sufix).concat("Widget");
                resources.createResource(stringWriter.toString().toCharArray(),
                        fqViewName.replace('.', '/') + ".ui.xml");
            }

            if (javaTemplate != null) {
                stringWriter = new StringWriter();
                velocityEngine.mergeTemplate(javaTemplate, "UTF-8", velocityContext, stringWriter);
                JavaType<?> serviceClass = JavaParser.parse(JavaType.class, stringWriter.toString());
                java.saveJavaSource(serviceClass);
            }

            if (!msgCollector.isEmpty()) {
                ShellMessages.info(out,
                        String.format("Collecting %s new messages from UI template", msgCollector.size()));
                gwtFacet.addMessages(msgCollector);
            }
        }
    } catch (FileNotFoundException e) {
        ShellMessages.error(out, "Bean source not found!" + e);
    }
}

From source file:Controladores.controladorAtividade.java

@RequestMapping(value = "salvar-atividade", produces = "text/html; charset=UTF-8")
@ResponseBody//from  w w  w .ja  va  2s  . c  o m
public String salvarAtividade(String atividadeJson, String operacao) {

    try {
        Atividade atividade = new Gson().fromJson(atividadeJson, Atividade.class);

        HashMap<String, String> erros = new HashMap<String, String>();

        if (atividade.getNome().trim().length() == 0) {
            erros.put("erroAtividadeNome", "Informe um nome para a atividade!");
        }

        if (atividade.getDescricao().trim().length() == 0) {
            erros.put("erroAtividadeDescricao", "Informe uma descrio para a atividade!");
        }

        if (atividade.getTpprioridade().getId() == 0) {
            erros.put("erroTpPrioridade", "Selecione uma prioridade para a atividade!");
        }

        if (atividade.getSitatividade().getId() == 0) {
            erros.put("erroSitAtividade", "Selecione uma situao para a atividade!");
        }

        if (atividade.getTptempoByTptempoestimadoid().getId() == 0) {
            erros.put("erroTempoEstimado", "Selecione o tempo estimado de concluso da atividade!");
        }

        if (atividade.getSitatividade().getId() == 3) {

            if (atividade.getTptempoByTptempoconclusaoid().getId() == 0) {
                erros.put("erroTempoConclusao", "Selecione o tempo de concluso!");
            }

            if (atividade.getDescconclusao().length() == 0) {
                erros.put("erroDescricaoConclusao", "Informe a descricao da conclusao!");
            }
        }

        if (erros.isEmpty()) {

            if (operacao.equalsIgnoreCase("I")) {
                atividade.setDtcriacao(new Date());
            } else {
                atividade.setDtalteracao(new Date());
            }

            AtividadeDAO.salvarAtividade(atividade);
        }

        Gson gson = new Gson();
        JsonObject myObj = new JsonObject();

        if (operacao.equalsIgnoreCase("U")) {
            myObj.addProperty("isFuncionario", Boolean.TRUE);
        }

        myObj.addProperty("sucesso", erros.isEmpty());
        JsonElement objetoErrosEmJson = gson.toJsonTree(erros);
        myObj.add("erros", objetoErrosEmJson);

        return myObj.toString();

    } catch (Exception erro) {
        erro.printStackTrace();
        return null;
    }
}

From source file:azkaban.webapp.servlet.ExecutorServlet.java

private Map<String, Object> getExecutableFlowUpdateInfo(ExecutableNode node, long lastUpdateTime) {
    HashMap<String, Object> nodeObj = new HashMap<String, Object>();
    if (node instanceof ExecutableFlowBase) {
        ExecutableFlowBase base = (ExecutableFlowBase) node;
        ArrayList<Map<String, Object>> nodeList = new ArrayList<Map<String, Object>>();

        for (ExecutableNode subNode : base.getExecutableNodes()) {
            Map<String, Object> subNodeObj = getExecutableFlowUpdateInfo(subNode, lastUpdateTime);
            if (!subNodeObj.isEmpty()) {
                nodeList.add(subNodeObj);
            }/*w  w w . ja v  a2 s .  com*/
        }

        if (!nodeList.isEmpty()) {
            nodeObj.put("flow", base.getFlowId());
            nodeObj.put("nodes", nodeList);
        }
    }

    if (node.getUpdateTime() > lastUpdateTime || !nodeObj.isEmpty()) {
        nodeObj.put("id", node.getId());
        nodeObj.put("status", node.getStatus());
        nodeObj.put("startTime", node.getStartTime());
        nodeObj.put("endTime", node.getEndTime());
        nodeObj.put("updateTime", node.getUpdateTime());

        nodeObj.put("attempt", node.getAttempt());
        if (node.getAttempt() > 0) {
            nodeObj.put("pastAttempts", node.getAttemptObjects());
        }
    }

    return nodeObj;
}

From source file:com.sos.jitl.jasperreports.JobSchedulerJasperReportJob.java

/**
 * @param sosConnection connection zur Document Factory Datenbank
 * @param queue Name der Print Queue//from w ww .  ja v a 2 s.  c o  m
 * @return Name des Druckers oder Leerstring falls der Drucker nicht gefunden wurde
 * @throws Exception falls Drucker, Queue oder Resource gesperrt ist
 */
public static String getActiveFactoryPrinter(SOSConnection sosConnection, String queue) throws Exception {
    String rv = "";
    /** Tabelle der Warteschlangen */
    String tableQueues = "LF_QUEUES";
    /** Tabelle der Drucker */
    String tablePrinters = "LF_PRINTERS";
    /** Tabelle der Ressourcen */
    String tableResources = "LF_RESOURCES";

    HashMap printer = sosConnection.getSingle("SELECT d.\"SYSTEM_NAME\", q.\"STATUS\", "
            + "d.\"STATUS\" as \"PRINTER_STATUS\", r.\"STATUS\" as \"RESOURCE_STATUS\" FROM " + tableQueues
            + " q, " + "( " + tablePrinters + " d LEFT OUTER JOIN " + tableResources
            + " r ON d.\"SYSTEM_NAME\"=r.\"RESOURCE_KEY\")" + " WHERE q.\"NAME\"='" + queue
            + "' AND d.\"PRINTER\"=q.\"PRINTER\" AND"
            + " (r.\"RESOURCE\" IS NULL OR r.\"RESOURCE_TYPE\"='printer')");

    if (!printer.isEmpty()) {
        rv = printer.get("system_name").toString();
        String status = printer.get("status").toString();
        if (status.equals("0"))
            throw new Exception("Queue " + queue + " is suspended.");
        String printerStatus = printer.get("printer_status").toString();
        if (printerStatus.equals("0"))
            throw new Exception("Printer " + rv + " is suspended.");
        if (printer.get("resource_status") != null) {
            String resourceStatus = printer.get("resource_status").toString();
            if (resourceStatus.equals("0"))
                throw new Exception("Resource for printer " + rv + " is suspended.");
        }
    }

    return rv;
}

From source file:de.unibi.techfak.bibiserv.web.beans.session.AbstractCloudInputBean.java

public void validate_s3_url() {
    HashMap<Integer, String> validationMessage = awsbean.validate_s3_url_awsbean(s3url_to_object, selectedData);
    throwFacesMessage(validationMessage, getId() + "_msg_validation");

    resetValidated();//  ww w  .  ja v a2  s.c  o m
    showPublicObjects = false;

    loadListMsg = messages.property("de.unibi.techfak.bibiserv.bibimainapp.input.VALIDATINGEND") + ".<br/>";

    // this is bucket url
    if (!selectedData.getBucket().isEmpty() && selectedData.getFile().isEmpty()) {
        showPublicObjects = true;

        validationMessage = awsbean.loadS3ObjectListForced(selectedData.getBucket());
        if (validationMessage.isEmpty()) {
            loadListMsg += messages.property("de.unibi.techfak.bibiserv.bibimainapp.input.LISTOBJECTS") + ".";
        } else {
            loadListMsg = "";
            for (String str : validationMessage.values()) {
                loadListMsg += str + ".<br/>";
            }
        }
        itemlist_public_objects = awsbean.getS3ObjectList(selectedData.getBucket());
    }
}

From source file:fi.cosky.sdk.API.java

@SuppressWarnings("unchecked")
public <T extends BaseData> T navigate(Class<T> tClass, Link l, HashMap<String, String> queryParameters)
        throws IOException {
    Object result;//from   w  ww .jav a  2s  .c o m
    retry = true;
    long start = 0;
    long end;

    if (isTimed()) {
        start = System.currentTimeMillis();
    }

    if (tClass.equals(TokenData.class)) {
        result = sendRequest(l, tClass, null);
        return (T) result;
    }

    if (l.getRel().equals("authenticate")) {
        HashMap<String, String> headers = new HashMap<String, String>();
        String authorization = "Basic "
                + Base64.encodeBase64String((this.ClientKey + ":" + this.ClientSecret).getBytes());
        headers.put("authorization", authorization);
        result = sendRequestWithAddedHeaders(Verb.POST, this.baseUrl + l.getUri(), tClass, null, headers);
        return (T) result;
    }

    String uri = l.getUri();
    if (l.getMethod().equals("GET") && queryParameters != null && !queryParameters.isEmpty()) {
        StringBuilder sb = new StringBuilder(uri + "?");

        for (String key : queryParameters.keySet()) {
            sb.append(key + "=" + queryParameters.get(key) + "&");
        }
        sb.deleteCharAt(sb.length() - 1);
        uri = sb.toString();
    }

    if (l.getMethod().equals("GET") && !uri.contains(":")) {
        result = sendRequest(l, tClass, null);
    } else if (l.getMethod().equals("PUT")) {
        result = sendRequest(l, tClass, null);
    } else if (l.getMethod().equals("POST")) {
        result = sendRequest(l, tClass, null);
    } else if (l.getMethod().equals("DELETE")) {
        result = sendRequest(l, tClass, new Object());
    } else {
        result = sendRequest(l, tClass, null);
    }
    if (isTimed()) {
        end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("Method " + l.getMethod() + " on " + l.getUri() + " doing " + l.getRel() + " took "
                + time + " ms.");
    }
    return (T) result;
}

From source file:annis.service.internal.QueryServiceImpl.java

/**
 * Get an Annis Binary object identified by its id.
 *
 * @param id//  w ww  .j  a v  a2s .  c o  m
 * @param rawOffset the part we want to start from, we start from 0
 * @param rawLength how many bytes we take
 * @return AnnisBinary
 */
@Override
public Response binary(String toplevelCorpusName, String corpusName, String rawOffset, String rawLength,
        String fileName) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:binary:" + toplevelCorpusName);

    String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
    if (acceptHeader == null || acceptHeader.trim().isEmpty()) {
        acceptHeader = "*/*";
    }

    List<AnnisBinaryMetaData> meta = annisDao.getBinaryMeta(toplevelCorpusName, corpusName);
    HashMap<String, AnnisBinaryMetaData> matchedMetaByType = new LinkedHashMap<>();

    for (AnnisBinaryMetaData m : meta) {
        if (fileName == null) {
            // just add all available media types
            if (!matchedMetaByType.containsKey(m.getMimeType())) {
                matchedMetaByType.put(m.getMimeType(), m);
            }
        } else {
            // check if this binary has the right title/file name
            if (fileName.equals(m.getFileName())) {
                matchedMetaByType.put(m.getMimeType(), m);
            }
        }
    }

    if (matchedMetaByType.isEmpty()) {
        return Response.status(Response.Status.NOT_FOUND).entity("Requested binary not found").build();
    }

    // find the best matching mime type
    String bestMediaTypeMatch = MIMEParse.bestMatch(matchedMetaByType.keySet(), acceptHeader);
    if (bestMediaTypeMatch.isEmpty()) {
        return Response.status(Response.Status.NOT_ACCEPTABLE)
                .entity("Client must accept one of the following media types: "
                        + StringUtils.join(matchedMetaByType.keySet(), ", "))
                .build();
    }
    MediaType mediaType = MediaType.valueOf(bestMediaTypeMatch);

    int offset = 0;
    int length = 0;

    if (rawLength == null || rawOffset == null) {
        // use matched binary meta data to get the complete file size
        AnnisBinaryMetaData matchedBinary = matchedMetaByType.get(mediaType.toString());
        if (matchedBinary != null) {
            length = matchedBinary.getLength();
        }
    } else {
        // use the provided information
        offset = Integer.parseInt(rawOffset);
        length = Integer.parseInt(rawLength);
    }

    log.debug("fetching  " + (length / 1024) + "kb (" + offset + "-" + (offset + length) + ") from binary "
            + toplevelCorpusName + "/" + corpusName + (fileName == null ? "" : fileName) + " "
            + mediaType.toString());

    final InputStream stream = annisDao.getBinary(toplevelCorpusName, corpusName, mediaType.toString(),
            fileName, offset, length);

    log.debug("fetch successfully");
    StreamingOutput result = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                ByteStreams.copy(stream, output);
                output.close();
            } finally {
                stream.close();
            }
        }
    };

    return Response.ok(result, mediaType).build();
}

From source file:org.kuali.student.enrollment.class2.courseoffering.service.facade.CourseOfferingServiceFacadeImpl.java

public CourseWaitListInfo createColocatedWaitList(CourseWaitListInfo courseWaitListInfo, String waitlistType,
        boolean hasWaitlist, boolean limitWaitlistSize, boolean isColocatedAO, boolean isMaxEnrollmentShared,
        HashMap<String, String> aoIdfoIdMap, ContextInfo context) {

    setAutoProcConfReq(courseWaitListInfo, waitlistType, hasWaitlist, limitWaitlistSize);

    try {/* w  ww  . j av  a  2  s  . c o  m*/
        // whether co-locating or already existing colos
        if (!aoIdfoIdMap.isEmpty() && isColocatedAO) {
            CourseWaitListInfo courseWaitListInfoShared = new CourseWaitListInfo();
            if (!isMaxEnrollmentShared) { // want to keep old params for the new WLs for the rest of AOs
                courseWaitListInfoShared = getCourseWaitListService()
                        .getCourseWaitList(courseWaitListInfo.getId(), context);
            }

            for (Map.Entry<String, String> entry : aoIdfoIdMap.entrySet()) {
                String aoId = entry.getKey();
                String foId = entry.getValue();
                if (isMaxEnrollmentShared) { // create shared WL
                    // Put WL logic in. Shared WL ONLY when max enrollement is shared. Adding new aoID and foID(s)
                    if (!courseWaitListInfo.getActivityOfferingIds().contains(aoId)) {
                        courseWaitListInfo.getActivityOfferingIds().add(aoId);
                        // Delete WL for other AO
                        List<CourseWaitListInfo> courseWaitLists = getCourseWaitListService()
                                .getCourseWaitListsByActivityOffering(aoId, context);
                        for (CourseWaitListInfo courseWaitlist : courseWaitLists) {
                            if (!StringUtils.equals(courseWaitlist.getId(), courseWaitListInfo.getId())) {
                                getCourseWaitListService().deleteCourseWaitList(courseWaitlist.getId(),
                                        context);
                            }
                        }
                    }
                    if (!courseWaitListInfo.getFormatOfferingIds().contains(foId)) {
                        courseWaitListInfo.getFormatOfferingIds().add(foId);
                    }
                } else { // each AO keeps (or have to split shared) own WL
                    if (courseWaitListInfo.getActivityOfferingIds().contains(aoId)) {
                        courseWaitListInfo.getActivityOfferingIds().remove(aoId);
                        // creating new (non-shared) WL per AO
                        CourseWaitListInfo courseWaitListInfoNew = new CourseWaitListInfo(
                                courseWaitListInfoShared);
                        courseWaitListInfoNew.setId(null);
                        courseWaitListInfoNew.setActivityOfferingIds(new ArrayList<String>());
                        courseWaitListInfoNew.setFormatOfferingIds(new ArrayList<String>());
                        courseWaitListInfoNew.getActivityOfferingIds().add(aoId);
                        courseWaitListInfoNew.getFormatOfferingIds().add(foId);
                        getCourseWaitListService().createCourseWaitList(
                                CourseWaitListServiceConstants.COURSE_WAIT_LIST_WAIT_TYPE_KEY,
                                courseWaitListInfoNew, context);
                    }
                    if (courseWaitListInfo.getFormatOfferingIds().contains(foId)) {
                        courseWaitListInfo.getFormatOfferingIds().remove(foId);
                    }
                }
            }
        }

        courseWaitListInfo = getCourseWaitListService().updateCourseWaitList(courseWaitListInfo.getId(),
                courseWaitListInfo, context);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return courseWaitListInfo;
}

From source file:mobi.jenkinsci.ci.JenkinsCIPlugin.java

@Override
public List<ItemNode> getReleaseNotes(final Account account, final PluginConfig pluginConf,
        final String version, final String url, final HttpServletRequest request) throws Exception {
    final ArrayList<ItemNode> changes = new ArrayList<ItemNode>();
    final JenkinsClient client = JenkinsClient.getInstance(account, pluginConf);
    final String jenkinsUrl = pluginConf.getUrl();
    final String jobPathPart = getJobPathPart(url, jenkinsUrl);
    final Job job = client.getJob(jobPathPart);
    final String jobBuildPart = getJobBuildPart(client, url, jenkinsUrl);
    final int jobBuildNumber = job.getBuild(jobBuildPart).number;

    final HashMap<URL, ItemNode> ticketsMap = new HashMap<URL, ItemNode>();
    final List<ItemNode> changesList = new ArrayList<ItemNode>();

    final ArtifactFingerprint remoteBuildFingerprint = client.getArtifactFromMD5(getApkMd5(request));

    if (job.builds.size() <= 0 || remoteBuildFingerprint.original.number >= job.builds.get(0).number) {
        throw new Exception("Nothing to upgrade: you already have the latest build");
    }/*from ww  w  .  j av a 2  s  . c om*/
    for (final Build build : job.builds) {
        if (build.number > remoteBuildFingerprint.original.number && build.number <= jobBuildNumber) {
            for (final ChangeSetItem jobChange : client.getJobChanges(jobPathPart, build.number).items) {

                if (jobChange.issue != null) {
                    final URL ticketUrl = jobChange.issue.linkUrl;
                    if (ticketsMap.get(ticketUrl) == null) {
                        ticketsMap.put(ticketUrl, account.getPluginNodeForUrl(pluginConf, ticketUrl));
                    }
                } else {
                    changesList.add(jobChange.toAbstractNode(jenkinsUrl));
                }
            }
        }
    }

    if (!ticketsMap.isEmpty()) {
        changes.add(new HeaderNode("New features / Fixed bugs"));
        changes.addAll(ticketsMap.values());
    }

    if (!changesList.isEmpty()) {
        changes.add(new HeaderNode("Code changes"));
        changes.addAll(changesList);
    }
    return changes;
}