Example usage for org.springframework.util CollectionUtils isEmpty

List of usage examples for org.springframework.util CollectionUtils isEmpty

Introduction

In this page you can find the example usage for org.springframework.util CollectionUtils isEmpty.

Prototype

public static boolean isEmpty(@Nullable Map<?, ?> map) 

Source Link

Document

Return true if the supplied Map is null or empty.

Usage

From source file:com.iana.dver.dao.impl.DverDetailsDaoImpl.java

@Override
public List<byte[]> getDverFilesFromDverDetailIds(final List<Integer> dverDetailsIds)
        throws DataAccessException {
    List files = getHibernateTemplate().executeFind(new HibernateCallback<List<byte[]>>() {
        @Override//  ww  w  . j  a  v  a  2s  . c o  m
        public List<byte[]> doInHibernate(Session session) throws HibernateException, SQLException {
            logger.info("get DverFiles From DverDetailIds ....");
            Query query = session.createQuery(FIND_DVER_FILE_VO_FROM_DVER_DETAIL_ID);
            query.setParameterList("dverDetailIds", dverDetailsIds);
            return query.list();
        }
    });
    return (!CollectionUtils.isEmpty(files)) ? files : new ArrayList<byte[]>();
}

From source file:com.formkiq.core.service.FolderServiceImpl.java

@Override
public void createWorkflowOutput(final ArchiveDTO archive) throws IOException {

    Workflow workflow = archive.getWorkflow();

    List<WorkflowOutput> outputs = !CollectionUtils.isEmpty(workflow.getOutputs()) ? workflow.getOutputs()
            : new ArrayList<>();

    if (!CollectionUtils.isEmpty(workflow.getPrintsteps())) {
        WorkflowOutputPdf pdf = new WorkflowOutputPdf();
        pdf.setForms(workflow.getPrintsteps());
        outputs.add(pdf);// w  w w  . ja  va 2  s. co m
    }

    if (!CollectionUtils.isEmpty(outputs)) {

        for (WorkflowOutput wo : outputs) {

            if (FORM.equals(wo.getInputDocumentType())) {

                WorkflowOutputForm wof = (WorkflowOutputForm) wo;

                String uuid = extractLabelAndValue(wof.getForm()).getRight();
                this.formcalcService.calculate(archive, uuid);

            } else if (PDF.equals(wo.getInputDocumentType())) {

                byte[] pdf = this.printRenderer.createPDF(archive, (WorkflowOutputPdf) wo);
                archive.addPDF(workflow.getUUID() + ".pdf", pdf);

            } else {

                for (WorkflowOutputGenerator wog : this.context.getBeansOfType(WorkflowOutputGenerator.class)
                        .values()) {
                    if (wog.isSupported(wo)) {
                        wog.addOutputDocument(archive, wo);
                    }
                }
            }
        }
    }
}

From source file:com.phoenixnap.oss.ramlapisync.generation.rules.spring.SpringRestClientMethodBodyRule.java

@Override
public JMethod apply(ApiActionMetadata endpointMetadata, CodeModelHelper.JExtMethod generatableType) {
    JBlock body = generatableType.get().body();
    JCodeModel owner = generatableType.owner();
    //build HttpHeaders
    JClass httpHeadersClass = owner.ref(HttpHeaders.class);
    JExpression headersInit = JExpr._new(httpHeadersClass);
    JVar httpHeaders = null;//  w  ww  .  j a  v  a  2 s .  c o  m
    if (endpointMetadata.getInjectHttpHeadersParameter()) {
        for (JVar var : generatableType.get().params()) {
            if (var.name().equals("httpHeaders")) {
                httpHeaders = var;
                break;
            }
        }
    } else {
        httpHeaders = body.decl(httpHeadersClass, "httpHeaders", headersInit);
    }

    //Declare Arraylist to contain the acceptable Media Types
    body.directStatement("//  Add Accepts Headers and Body Content-Type");
    JClass mediaTypeClass = owner.ref(MediaType.class);
    JClass refArrayListClass = owner.ref(ArrayList.class).narrow(mediaTypeClass);
    JVar acceptsListVar = body.decl(refArrayListClass, "acceptsList", JExpr._new(refArrayListClass));

    //If we have a request body, lets set the content type of our request
    if (endpointMetadata.getRequestBody() != null) {
        body.invoke(httpHeaders, "setContentType")
                .arg(mediaTypeClass.staticInvoke("valueOf").arg(endpointMetadata.getRequestBodyMime()));
    }

    //If we have response bodies defined, we need to add them to our accepts headers list
    //TODO possibly restrict
    String documentDefaultType = endpointMetadata.getParent().getDocument().getMediaType();
    //If a global mediatype is defined add it
    if (StringUtils.hasText(documentDefaultType)) {
        body.invoke(acceptsListVar, "add").arg(mediaTypeClass.staticInvoke("valueOf").arg(documentDefaultType));
    } else { //default to application/json just in case
        body.invoke(acceptsListVar, "add").arg(mediaTypeClass.staticInvoke("valueOf").arg("application/json"));
    }

    //Iterate over Response Bodies and add each distinct mime type to accepts headers
    if (endpointMetadata.getResponseBody() != null && !endpointMetadata.getResponseBody().isEmpty()) {
        for (String responseMime : endpointMetadata.getResponseBody().keySet()) {
            if (!responseMime.equals(documentDefaultType) && !responseMime.equals("application/json")) {
                body.invoke(acceptsListVar, "add")
                        .arg(mediaTypeClass.staticInvoke("valueOf").arg(responseMime));
            }
        }
    }

    //Set accepts list as our accepts headers for the call
    body.invoke(httpHeaders, "setAccept").arg(acceptsListVar);

    //Get the parameters from the model and put them in a map for easy lookup
    List<JVar> params = generatableType.get().params();
    Map<String, JVar> methodParamMap = new LinkedHashMap<>();
    for (JVar param : params) {
        methodParamMap.put(param.name(), param);
    }

    // Add headers
    for (ApiParameterMetadata parameter : endpointMetadata.getRequestHeaders()) {
        JVar param = methodParamMap.get(NamingHelper.getParameterName(parameter.getName()));
        String javaParamName = NamingHelper.getParameterName(parameter.getName());
        body._if(methodParamMap.get(javaParamName).ne(JExpr._null()))._then().block().invoke(httpHeaders, "add")
                .arg(parameter.getName()).arg(JExpr.invoke(param, "toString"));
    }

    //Build the Http Entity object
    JClass httpEntityClass = owner.ref(HttpEntity.class);
    JInvocation init = JExpr._new(httpEntityClass);

    if (endpointMetadata.getRequestBody() != null) {
        init.arg(methodParamMap.get(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL,
                endpointMetadata.getRequestBody().getName())));
    }
    init.arg(httpHeaders);

    //Build the URL variable
    JExpression urlRef = JExpr.ref(baseUrlFieldName);
    JType urlClass = owner._ref(String.class);
    JExpression targetUrl = urlRef.invoke("concat").arg(endpointMetadata.getResource().getUri());
    JVar url = body.decl(urlClass, "url", targetUrl);
    JVar uriBuilderVar = null;
    JVar uriComponentVar = null;

    //Initialise the UriComponentsBuilder
    JClass builderClass = owner.ref(UriComponentsBuilder.class);
    JExpression builderInit = builderClass.staticInvoke("fromHttpUrl").arg(url);

    //If we have any Query Parameters, we will use the URIBuilder to encode them in the URL
    if (!CollectionUtils.isEmpty(endpointMetadata.getRequestParameters())) {
        //iterate over the parameters and add calls to .queryParam
        for (ApiParameterMetadata parameter : endpointMetadata.getRequestParameters()) {
            builderInit = builderInit.invoke("queryParam").arg(parameter.getName())
                    .arg(methodParamMap.get(NamingHelper.getParameterName(parameter.getName())));
        }
    }
    //Add these to the code model
    uriBuilderVar = body.decl(builderClass, "builder", builderInit);

    JClass componentClass = owner.ref(UriComponents.class);
    JExpression component = uriBuilderVar.invoke("build");
    uriComponentVar = body.decl(componentClass, "uriComponents", component);

    //build request entity holder
    JVar httpEntityVar = body.decl(httpEntityClass, "httpEntity", init);

    //construct the HTTP Method enum
    JClass httpMethod = null;
    try {
        httpMethod = (JClass) owner._ref(HttpMethod.class);
    } catch (ClassCastException e) {

    }

    //get all uri params from metadata set and add them to the param map in code
    if (!CollectionUtils.isEmpty(endpointMetadata.getPathVariables())) {
        //Create Map with Uri Path Variables
        JClass uriParamMap = owner.ref(Map.class).narrow(String.class, Object.class);
        JExpression uriParamMapInit = JExpr._new(owner.ref(HashMap.class));
        JVar uriParamMapVar = body.decl(uriParamMap, "uriParamMap", uriParamMapInit);

        endpointMetadata.getPathVariables().forEach(
                p -> body.invoke(uriParamMapVar, "put").arg(p.getName()).arg(methodParamMap.get(p.getName())));
        JInvocation expandInvocation = uriComponentVar.invoke("expand").arg(uriParamMapVar);

        body.assign(uriComponentVar, expandInvocation);
    }

    //Determining response entity type
    JClass returnType = null;
    if (!endpointMetadata.getResponseBody().isEmpty()) {
        ApiBodyMetadata apiBodyMetadata = endpointMetadata.getResponseBody().values().iterator().next();
        JClass genericType = findFirstClassBySimpleName(apiBodyMetadata.getCodeModel(),
                apiBodyMetadata.getName());
        if (apiBodyMetadata.isArray()) {
            JClass arrayType = owner.ref(List.class);
            returnType = arrayType.narrow(genericType);
        } else {
            returnType = genericType;
        }
    } else {
        returnType = owner.ref(Object.class);
    }

    JExpression returnExpression = JExpr.dotclass(returnType);//assume not parameterized by default
    //check if return is parameterized
    if (!CollectionUtils.isEmpty(returnType.getTypeParameters())) {
        //if yes - build the parameterized type reference and change returnExpression
        //Due to issue 61, it is generated as
        //class _P extends org.springframework.core.ParameterizedTypeReference<java.util.List<java.lang.String>>
        //ParameterizedTypeReference<List<String>> typeRef = new _P();
        //Create Map with Uri Path Variables
        JClass paramTypeRefClass = owner.ref(ParameterizedTypeReference.class);
        paramTypeRefClass = paramTypeRefClass.narrow(returnType);

        body.directStatement("class _P extends " + paramTypeRefClass.fullName() + "{};");

        JExpression paramTypeRefInit = JExpr._new(owner.directClass("_P"));
        returnExpression = body.decl(paramTypeRefClass, "typeReference", paramTypeRefInit);
    }

    //build rest template exchange invocation
    JInvocation jInvocation = JExpr._this().ref(restTemplateFieldName).invoke("exchange");

    jInvocation.arg(uriComponentVar.invoke("encode").invoke("toUri"));
    jInvocation.arg(httpMethod.staticRef(endpointMetadata.getActionType().name()));
    jInvocation.arg(httpEntityVar);
    jInvocation.arg(returnExpression);

    body._return(jInvocation);

    return generatableType.get();
}

From source file:com.excilys.ebi.bank.util.Asserts.java

public static void notEmpty(Map<?, ?> map, String messagePattern, Object arg1, Object arg2) {
    if (CollectionUtils.isEmpty(map)) {
        throw new IllegalArgumentException(MessageFormatter.format(messagePattern, arg1, arg2).getMessage());
    }//from w  w w  .ja v  a2  s .  co  m
}

From source file:com.embedler.moon.graphql.boot.sample.test.GenericTodoSchemaParserTest.java

@Test
public void restUploadFileUrlEncodedTest() throws IOException {

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("query",
            "mutation AddTodoMutationMutation{addTodoMutation(input: {clientMutationId:\"m-123\", addTodoInput:{text: \"text\"}}){ clientMutationId, todoEdge {cursor, node {text, complete}} }}");
    map.add("variables", "{}");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

    ResponseEntity<GraphQLServerResult> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + "/graphql", HttpMethod.POST, requestEntity, GraphQLServerResult.class);

    GraphQLServerResult result = responseEntity.getBody();
    Assert.assertTrue(CollectionUtils.isEmpty(result.getErrors()));
    Assert.assertFalse(CollectionUtils.isEmpty(result.getData()));
    LOGGER.info(objectMapper.writeValueAsString(result.getData()));
}

From source file:org.agatom.springatom.cmp.wizards.data.result.WizardResult.java

public boolean hasErrors() {
    return !CollectionUtils.isEmpty(this.errors) || !CollectionUtils.isEmpty(this.bindingErrors)
            || !CollectionUtils.isEmpty(this.validationMessages);
}

From source file:com.greenline.guahao.web.module.home.controllers.promotion.hosptopic.HospitalTopicController.java

/**
 * ?hospId?hospId.json??//from  w w  w. ja  va2s  . c o m
 * 
 * @param model
 * @param hospId
 */
private boolean analyseJsonProps(ModelMap model, String hospId) {
    // ?hospuuid?json
    String jsonProp = BizCommonUtils
            .readTxtFile(propDO.getImgUploadBasePath() + JSON_FILE_PATH_PRE + hospId + JSON_FILE_PATH_SUFFIX);
    if (StringUtils.isBlank(jsonProp)) {
        // ??
        return false;
    }

    try {
        Map<Object, Object> map = JsonUtils.getMap4Json(jsonProp);
        if (CollectionUtils.isEmpty(map)) {
            // ??
            return false;
        }

        model.put("theme", map.get(JSON_MAP_KEY_THEME));
        model.put("showAppDL", map.get(JSON_MAP_KEY_APPDL));
        model.put("showWeichat", map.get(JSON_MAP_KEY_WEICHAT));
        JSONObject jsonObj = (JSONObject) map.get(JSON_MAP_KEY_PLACARD);
        if (!jsonObj.isEmpty() && !jsonObj.isNullObject()) {
            String placardStr = jsonObj.toString();
            model.put("placardMap", JsonUtils.getMap4Json(placardStr));
        }
    } catch (Exception e) {
        log.error("json analyse error!", e);
        return false;
    }

    return true;
}

From source file:org.surfnet.oaaas.conext.SAMLAuthenticator.java

@Override
public void authenticate(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        String authStateValue, String returnUri) throws IOException, ServletException {
    LOG.debug("Hitting SAML Authenticator filter");
    if (isSAMLResponse(request)) {
        Response samlResponse = extractSamlResponse(request);
        SAMLAuthenticatedPrincipal principal = (SAMLAuthenticatedPrincipal) openSAMLContext.assertionConsumer()
                .consume(samlResponse);/*from   www. j  a  v a 2s . com*/
        if (enrichPricipal) {
            //need to save the Principal and the AuthState somewhere
            request.getSession().setAttribute(PRINCIPAL_FROM_SAML, principal);
            request.getSession().setAttribute(RELAY_STATE_FROM_SAML, getSAMLRelayState(request));
            response.sendRedirect(apiClient.getAuthorizationUrl());
        } else {
            proceedWithChain(request, response, chain, principal, getSAMLRelayState(request));
        }
    } else if (isOAuthCallback(request)) {
        SAMLAuthenticatedPrincipal principal = (SAMLAuthenticatedPrincipal) request.getSession()
                .getAttribute(PRINCIPAL_FROM_SAML);
        String authState = (String) request.getSession().getAttribute(RELAY_STATE_FROM_SAML);
        if (principal == null) { //huh
            throw new ServiceProviderAuthenticationException("No principal anymore in the session");
        }
        String userId = principal.getName();
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceProviderAuthenticationException("No userId in SAML assertion!");
        }
        apiClient.oauthCallback(request, userId);
        List<Group20> groups = apiClient.getGroups20(userId, userId);
        if (!CollectionUtils.isEmpty(groups)) {
            for (Group20 group : groups) {
                principal.addGroup(group.getId());
                if (StringUtils.isNotBlank(this.adminGroup) && adminGroup.equalsIgnoreCase(group.getId())) {
                    principal.setAdminPrincipal(true);
                }
            }
        }
        proceedWithChain(request, response, chain, principal, authState);
    } else {
        sendAuthnRequest(response, authStateValue, getReturnUri(request));
    }
}

From source file:com.raycloud.cobarclient.mybatis.spring.MySqlSessionTemplate.java

/**
 * {@inheritDoc}/*from  w  ww.  j  av a  2 s  .c o  m*/
 */
public int insert(String statement, Object parameter) {
    if (parameter instanceof Collection) {
        Collection collection = (Collection) parameter;
        if (CollectionUtils.isEmpty(collection)) {
            return 0;
        } else {
            if (collection.size() <= 100) {
                return batchSync(statement, collection);
            } else {
                return batchAsync(statement, collection);
            }
        }
    }
    return this.sqlSessionProxy.insert(statement, parameter);
}

From source file:pe.gob.mef.gescon.service.impl.PreguntaServiceImpl.java

@Override
public List<Consulta> getConcimientosVinculados(HashMap filters) {
    List<Consulta> lista = new ArrayList<Consulta>();
    try {//from  w  ww .  j  a  v a 2 s  . c  om
        PreguntaDao preguntaDao = (PreguntaDao) ServiceFinder.findBean("PreguntaDao");
        List<HashMap> consulta = preguntaDao.getConcimientosVinculados(filters);
        if (!CollectionUtils.isEmpty(consulta)) {
            for (HashMap map : consulta) {
                Consulta c = new Consulta();
                c.setId((BigDecimal) map.get("ID"));
                c.setIdconocimiento((BigDecimal) map.get("IDCONOCIMIENTO"));
                c.setCodigo((String) map.get("NUMERO"));
                c.setNombre((String) map.get("NOMBRE"));
                c.setSumilla((String) map.get("SUMILLA"));
                c.setFechaPublicacion((Date) map.get("FECHA"));
                c.setIdCategoria((BigDecimal) map.get("IDCATEGORIA"));
                c.setCategoria((String) map.get("CATEGORIA"));
                c.setIdTipoConocimiento((BigDecimal) map.get("IDTIPOCONOCIMIENTO"));
                c.setTipoConocimiento((String) map.get("TIPOCONOCIMIENTO"));
                c.setIdEstado((BigDecimal) map.get("IDESTADO"));
                c.setEstado((String) map.get("ESTADO"));
                lista.add(c);
            }
        }
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return lista;
}