List of usage examples for java.util HashMap isEmpty
public boolean isEmpty()
From source file:com.bitants.wally.fragments.SearchFragment.java
@Override public void onResume() { super.onResume(); HashMap<String, Object> messages = WallyApplication.readMessages(TAG); if (!messages.isEmpty()) { String tagName = (String) messages.get(EXTRA_MESSAGE_TAG); if (tagName != null) { searchTag(tagName);/*from w w w . j a v a 2 s. c o m*/ } } }
From source file:org.gcaldaemon.core.Synchronizer.java
private final void loadEventRegistry() { if (!eventRegistry.isEmpty()) { return;// w w w . ja va2 s .c o m } RandomAccessFile file = null; try { if (eventRegistryFile.isFile()) { // Load history file file = new RandomAccessFile(eventRegistryFile, "r"); int len = (int) eventRegistryFile.length(); byte[] bytes = new byte[len]; file.readFully(bytes); file.close(); String content = StringUtils.decodeToString(bytes, StringUtils.US_ASCII); bytes = null; // Parse history file StringTokenizer st = new StringTokenizer(content, "\r\n"); HashMap uids = new HashMap(); String urlHash = new String(); String line; int i; while (st.hasMoreTokens()) { line = st.nextToken().trim(); if (line.startsWith("URL\t")) { if (!uids.isEmpty()) { eventRegistry.put(urlHash, uids); } i = line.indexOf('\t'); if (i != -1) { urlHash = line.substring(i + 1); uids = new HashMap(); } continue; } i = line.indexOf('\t'); if (i != -1) { uids.put(line.substring(0, i), new Long(line.substring(i + 1))); } } if (!uids.isEmpty()) { eventRegistry.put(urlHash, uids); } if (log.isDebugEnabled()) { log.debug("Event registry loaded successfully (" + len + " bytes)."); } return; } } catch (Exception ioError) { if (file != null) { try { file.close(); eventRegistryFile.delete(); } catch (Exception ignored) { } } log.warn("Unable to load event registry!", ioError); } }
From source file:org.kuali.kfs.module.purap.document.web.struts.PaymentRequestAction.java
/** * This method runs two checks based on the user input on PREQ initiate screen: Encumber next fiscal year check and Duplicate * payment request check. Encumber next fiscal year is checked first and will display a warning message to the user if it's the * case. Duplicate payment request check calls <code>PaymentRequestService</code> to perform the duplicate payment request * check. If one is found, a question is setup and control is forwarded to the question action method. Coming back from the * question prompt the button that was clicked is checked and if 'no' was selected they are forward back to the page still in * init mode.//from ww w . ja v a 2 s. c o m * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @param paymentRequestDocument The PaymentRequestDocument * @throws Exception * @return An ActionForward * @see org.kuali.kfs.module.purap.document.service.PaymentRequestService */ protected ActionForward performDuplicatePaymentRequestAndEncumberFiscalYearCheck(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, PaymentRequestDocument paymentRequestDocument) throws Exception { ActionForward forward = null; Object question = request.getParameter(KFSConstants.QUESTION_INST_ATTRIBUTE_NAME); if (question == null) { // perform encumber next fiscal year check and prompt warning message if needs if (isEncumberNextFiscalYear(paymentRequestDocument)) { String questionText = SpringContext.getBean(ConfigurationService.class) .getPropertyValueAsString(PurapKeyConstants.WARNING_ENCUMBER_NEXT_FY); return this.performQuestionWithoutInput(mapping, form, request, response, PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION, questionText, KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, ""); } else { // perform duplicate payment request check HashMap<String, String> duplicateMessages = SpringContext.getBean(PaymentRequestService.class) .paymentRequestDuplicateMessages(paymentRequestDocument); if (!duplicateMessages.isEmpty()) { return this.performQuestionWithoutInput(mapping, form, request, response, PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION, duplicateMessages.get(PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION), KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, ""); } } } else { Object buttonClicked = request.getParameter(KFSConstants.QUESTION_CLICKED_BUTTON); // If the user replies 'Yes' to the encumber-next-year-question, proceed with duplicate payment check if (PurapConstants.PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) { HashMap<String, String> duplicateMessages = SpringContext.getBean(PaymentRequestService.class) .paymentRequestDuplicateMessages(paymentRequestDocument); if (!duplicateMessages.isEmpty()) { return this.performQuestionWithoutInput(mapping, form, request, response, PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION, duplicateMessages.get(PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION), KFSConstants.CONFIRMATION_QUESTION, KFSConstants.ROUTE_METHOD, ""); } } // If the user replies 'No' to either of the questions, redirect to the PREQ initiate page. else if ((PurapConstants.PREQDocumentsStrings.ENCUMBER_NEXT_FISCAL_YEAR_QUESTION.equals(question) || PurapConstants.PREQDocumentsStrings.DUPLICATE_INVOICE_QUESTION.equals(question)) && ConfirmationQuestion.NO.equals(buttonClicked)) { paymentRequestDocument .updateAndSaveAppDocStatus(PurapConstants.PaymentRequestStatuses.APPDOC_INITIATE); forward = mapping.findForward(KFSConstants.MAPPING_BASIC); } } return forward; }
From source file:org.apache.axis2.transport.http.ListingAgent.java
public void processListService(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String url;/* w w w . j av a 2s .c o m*/ try { url = req.getRequestURL().toString(); } catch (Throwable t) { log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t); url = req.getRequestURI(); } String serviceName = extractServiceName(url); HashMap services = configContext.getAxisConfiguration().getServices(); String query = req.getQueryString(); int wsdl2 = query.indexOf("wsdl2"); int wsdl = query.indexOf("wsdl"); int xsd = query.indexOf("xsd"); int policy = query.indexOf("policy"); if ((services != null) && !services.isEmpty()) { Object serviceObj = services.get(serviceName); if (serviceObj != null) { boolean isHttp = "http".equals(req.getScheme()); if (wsdl2 >= 0) { res.setContentType("text/xml"); String ip = extractHostAndPort(url, isHttp); String wsdlName = req.getParameter("wsdl2"); if (wsdlName != null && wsdlName.length() > 0) { InputStream in = ((AxisService) serviceObj).getClassLoader() .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName); if (in != null) { OutputStream out = res.getOutputStream(); out.write(IOUtils.getStreamAsByteArray(in)); out.flush(); out.close(); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { OutputStream out = res.getOutputStream(); ((AxisService) serviceObj).printWSDL2(out, ip); out.flush(); out.close(); } return; } else if (wsdl >= 0) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); String ip = extractHostAndPort(url, isHttp); String wsdlName = req.getParameter("wsdl"); if (wsdlName != null && wsdlName.length() > 0) { AxisService axisServce = (AxisService) serviceObj; axisServce.printUserWSDL(out, wsdlName); out.flush(); out.close(); } else { ((AxisService) serviceObj).printWSDL(out, ip); out.flush(); out.close(); } return; } else if (xsd >= 0) { res.setContentType("text/xml"); int ret = ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd")); if (ret == 0) { //multiple schemas are present and the user specified //no name - in this case we cannot possibly pump a schema //so redirect to the service root res.sendRedirect(""); } else if (ret == -1) { res.sendError(HttpServletResponse.SC_NOT_FOUND); } return; } else if (policy >= 0) { ExternalPolicySerializer serializer = new ExternalPolicySerializer(); serializer .setAssertionsToFilter(configContext.getAxisConfiguration().getLocalPolicyAssertions()); // check whether Id is set String idParam = req.getParameter("id"); if (idParam != null) { // Id is set Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj); if (targetPolicy != null) { XMLStreamWriter writer; try { OutputStream out = res.getOutputStream(); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); res.setContentType("application/wspolicy+xml"); targetPolicy.serialize(writer); writer.flush(); } catch (XMLStreamException e) { throw new ServletException("Error occured when serializing the Policy", e); } catch (FactoryConfigurationError e) { throw new ServletException("Error occured when serializing the Policy", e); } } else { OutputStream out = res.getOutputStream(); res.setContentType("text/html"); String outStr = "<b>No policy found for id=" + idParam + "</b>"; out.write(outStr.getBytes()); } } else { PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude(); Policy effecPolicy = policyInclude.getEffectivePolicy(); if (effecPolicy != null) { XMLStreamWriter writer; try { OutputStream out = res.getOutputStream(); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); res.setContentType("application/wspolicy+xml"); effecPolicy.serialize(writer); writer.flush(); } catch (XMLStreamException e) { throw new ServletException("Error occured when serializing the Policy", e); } catch (FactoryConfigurationError e) { throw new ServletException("Error occured when serializing the Policy", e); } } else { OutputStream out = res.getOutputStream(); res.setContentType("text/html"); String outStr = "<b>No effective policy for " + serviceName + " servcie</b>"; out.write(outStr.getBytes()); } } return; } else { try { req.getSession().setAttribute(Constants.SINGLE_SERVICE, serviceObj); } catch (Throwable t) { log.info("Old Servlet API :" + t); } } } else { try { req.getSession().setAttribute(Constants.SINGLE_SERVICE, null); } catch (Throwable t) { log.info("Old Servlet API :" + t); } res.sendError(HttpServletResponse.SC_NOT_FOUND, url); } } renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res); }
From source file:com.zimbra.cs.account.ldap.upgrade.BUG_27075.java
private void doBug83551(Config config) throws ServiceException { // perform this step if the following condition is met (IV = installed version) // ((IV < 7.2.4) OR ((IV >= 8.0.0) AND (IV < 8.0.5)) boolean stepRequired = mSince.compare("7.2.5") < 0 || (mSince.compare("8.0.0") >= 0 && mSince.compare("8.0.5") < 0); if (!stepRequired) { return;/*w ww. java 2 s . c o m*/ } // check if the attribute already exists. It's possible that server may have been upgraded from // 7.2.2->7.2.5, 7.2.5->8.0.0 and then 8.0.0->8.0.5. The 7.2.2->7.2.5 would have already added the attribute. HashMap<String, Object> attrs = new HashMap<String, Object>(); String attr = Provisioning.A_zimbraWebGzipEnabled; String curVal = config.getAttr(attr, null); if (curVal == null) { attrs.put(attr, ("" + config.isWebGzipEnabled()).toUpperCase()); } attr = Provisioning.A_zimbraHttpCompressionEnabled; curVal = config.getAttr(attr, null); if (curVal == null) { attrs.put(attr, ("" + config.isHttpCompressionEnabled()).toUpperCase()); } if (!attrs.isEmpty()) { try { printer.println("Setting " + attrs.keySet() + " on globalConfig"); prov.modifyAttrs(config, attrs); } catch (ServiceException e) { printer.println("Caught ServiceException while setting " + attrs.keySet() + " on globalConfig"); printer.printStackTrace(e); } } }
From source file:com.zimbra.cs.account.ldap.upgrade.BUG_27075.java
private void doBug79208(Config config) throws ServiceException { // perform this step if the following condition is met (IV = installed version) // ((IV < 7.2.3) OR ((IV >= 8.0.0) AND (IV < 8.0.3)) boolean stepRequired = mSince.compare("7.2.3") < 0 || (mSince.compare("8.0.0") >= 0 && mSince.compare("8.0.3") < 0); if (!stepRequired) { return;//from www . ja v a 2 s .c om } // check if the attribute already exists. It's possible that server may have been upgraded from // 7.2.2->7.2.3, 7.2.3->8.0.0 and then 8.0.0->8.0.3. The 7.2.2->7.2.3 would have already added the attribute. HashMap<String, Object> attrs = new HashMap<String, Object>(); String attr = Provisioning.A_zimbraHttpThreadPoolMaxIdleTimeMillis; String curVal = config.getAttr(attr, null); if (curVal == null) { attrs.put(attr, config.getHttpThreadPoolMaxIdleTimeMillis()); } attr = Provisioning.A_zimbraHttpConnectorMaxIdleTimeMillis; curVal = config.getAttr(attr, null); if (curVal == null) { attrs.put(attr, config.getHttpConnectorMaxIdleTimeMillis()); } if (!attrs.isEmpty()) { try { printer.println("Setting " + attrs.keySet() + " on globalConfig"); prov.modifyAttrs(config, attrs); } catch (ServiceException e) { printer.println("Caught ServiceException while setting " + attrs.keySet() + " on globalConfig"); printer.printStackTrace(e); } } }
From source file:org.wso2.carbon.ui.BreadCrumbGenerator.java
/** * Generates breadcrumb html content./*from ww w. j a v a2 s .com*/ * Please do not add line breaks to places where HTML content is written. * It makes debugging difficult. * @param request * @param currentPageHeader * @return String */ public HashMap<String, String> getBreadCrumbContent(HttpServletRequest request, BreadCrumbItem currentBreadcrumbItem, String jspFilePath, boolean topPage, boolean removeLastItem) { String breadcrumbCookieString = ""; //int lastIndexofSlash = jspFilePath.lastIndexOf(System.getProperty("file.separator")); //int lastIndexofSlash = jspFilePath.lastIndexOf('/'); StringBuffer content = new StringBuffer(); StringBuffer cookieContent = new StringBuffer(); HashMap<String, String> breadcrumbContents = new HashMap<String, String>(); HashMap<String, BreadCrumbItem> breadcrumbs = (HashMap<String, BreadCrumbItem>) request.getSession() .getAttribute("breadcrumbs"); String menuId = request.getParameter("item"); String region = request.getParameter("region"); String ordinalStr = request.getParameter("ordinal"); if (topPage) { //some wizards redirect to index page of the component after doing some operations. //Hence a map of region & menuId for component/index page is maintained & retrieved //by passing index page (eg: ../service-mgt/index.jsp) //This logic should run only for pages marked as toppage=true if (menuId == null && region == null) { HashMap<String, String> indexPageBreadcrumbParamMap = (HashMap<String, String>) request.getSession() .getAttribute("index-page-breadcrumb-param-map"); //eg: indexPageBreadcrumbParamMap contains ../service-mgt/index.jsp : region1,services_list_menu pattern if (indexPageBreadcrumbParamMap != null && !(indexPageBreadcrumbParamMap.isEmpty())) { String params = indexPageBreadcrumbParamMap.get(jspFilePath); if (params != null) { region = params.substring(0, params.indexOf(',')); menuId = params.substring(params.indexOf(',') + 1); } } } } if (menuId != null && region != null) { String key = region.trim() + "-" + menuId.trim(); HashMap<String, String> breadcrumbMap = (HashMap<String, String>) request.getSession() .getAttribute(region + "menu-id-breadcrumb-map"); String breadCrumb = ""; if (breadcrumbMap != null && !(breadcrumbMap.isEmpty())) { breadCrumb = breadcrumbMap.get(key); } if (breadCrumb != null) { content.append("<table cellspacing=\"0\"><tr>"); Locale locale = CarbonUIUtil.getLocaleFromSession(request); String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale); content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">" + homeText + "</a></td>"); cookieContent.append(breadCrumb); cookieContent.append("#"); generateBreadcrumbForMenuPath(content, breadcrumbs, breadCrumb, true); } } else { HashMap<String, List<BreadCrumbItem>> links = (HashMap<String, List<BreadCrumbItem>>) request .getSession().getAttribute("page-breadcrumbs"); //call came within a page. Retrieve the breadcrumb cookie Cookie[] cookies = request.getCookies(); for (int a = 0; a < cookies.length; a++) { Cookie cookie = cookies[a]; if ("current-breadcrumb".equals(cookie.getName())) { breadcrumbCookieString = cookie.getValue(); //bringing back the , breadcrumbCookieString = breadcrumbCookieString.replace("%2C", ","); //bringing back the # breadcrumbCookieString = breadcrumbCookieString.replace("%23", "#"); if (log.isDebugEnabled()) { log.debug("cookie :" + cookie.getName() + " : " + breadcrumbCookieString); } } } if (links != null) { if (log.isDebugEnabled()) { log.debug("size of page-breadcrumbs is : " + links.size()); } content.append("<table cellspacing=\"0\"><tr>"); Locale locale = CarbonUIUtil.getLocaleFromSession(request); String homeText = CarbonUIUtil.geti18nString("component.home", "org.wso2.carbon.i18n.Resources", locale); content.append("<td class=\"breadcrumb-link\"><a href=\"" + CarbonUIUtil.getHomePage() + "\">" + homeText + "</a></td>"); String menuBreadcrumbs = ""; if (breadcrumbCookieString.indexOf('#') > -1) { menuBreadcrumbs = breadcrumbCookieString.substring(0, breadcrumbCookieString.indexOf('#')); } cookieContent.append(menuBreadcrumbs); cookieContent.append("#"); generateBreadcrumbForMenuPath(content, breadcrumbs, menuBreadcrumbs, false); int clickedBreadcrumbLocation = 0; if (ordinalStr != null) { //only clicking on already made page breadcrumb link will send this via request parameter try { clickedBreadcrumbLocation = Integer.parseInt(ordinalStr); } catch (NumberFormatException e) { // Do nothing log.warn("Found String for breadcrumb ordinal"); } } String pageBreadcrumbs = ""; if (breadcrumbCookieString.indexOf('#') > -1) { pageBreadcrumbs = breadcrumbCookieString.substring(breadcrumbCookieString.indexOf('#') + 1); } StringTokenizer st2 = new StringTokenizer(pageBreadcrumbs, "*"); String[] tokens = new String[st2.countTokens()]; int count = 0; String previousToken = ""; while (st2.hasMoreTokens()) { String currentToken = st2.nextToken(); //To avoid page refresh create breadcrumbs if (!currentToken.equals(previousToken)) { previousToken = currentToken; tokens[count] = currentToken; count++; } } //jspSubContext should be the same across all the breadcrumbs //(cookie is updated everytime a page is loaded) List<BreadCrumbItem> breadcrumbItems = null; // if(tokens != null && tokens.length > 0){ //String token = tokens[0]; //String jspSubContext = token.substring(0, token.indexOf('+')); //breadcrumbItems = links.get("../"+jspSubContext); // } LinkedList<String> tokenJSPFileOrder = new LinkedList<String>(); LinkedList<String> jspFileSubContextOrder = new LinkedList<String>(); HashMap<String, String> jspFileSubContextMap = new HashMap<String, String>(); for (int a = 0; a < tokens.length; a++) { String token = tokens[a]; if (token != null) { String jspFileName = token.substring(token.indexOf('+') + 1); String jspSubContext = token.substring(0, token.indexOf('+')); jspFileSubContextMap.put(jspFileName, jspSubContext); tokenJSPFileOrder.add(jspFileName); jspFileSubContextOrder.add(jspSubContext + "^" + jspFileName); } } if (clickedBreadcrumbLocation > 0) { int tokenCount = tokenJSPFileOrder.size(); while (tokenCount > clickedBreadcrumbLocation) { String lastItem = tokenJSPFileOrder.getLast(); if (log.isDebugEnabled()) { log.debug("Removing breacrumbItem : " + lastItem); } tokenJSPFileOrder.removeLast(); jspFileSubContextOrder.removeLast(); tokenCount = tokenJSPFileOrder.size(); } } boolean lastBreadcrumbItemAvailable = false; if (clickedBreadcrumbLocation == 0) { String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink()) + "+" + currentBreadcrumbItem.getId(); if (!previousToken.equals(tmp)) { //To prevent page refresh lastBreadcrumbItemAvailable = true; } } if (tokenJSPFileOrder != null) { //found breadcrumb items for given sub context for (int i = 0; i < jspFileSubContextOrder.size(); i++) { String token = tokenJSPFileOrder.get(i); //String jspFileName = token.substring(token.indexOf('+')+1); //String jspSubContext = jspFileSubContextMap.get(jspFileName); String fileContextToken = jspFileSubContextOrder.get(i); String jspFileName = fileContextToken.substring(fileContextToken.indexOf('^') + 1); String jspSubContext = fileContextToken.substring(0, fileContextToken.indexOf('^')); if (jspSubContext != null) { breadcrumbItems = links.get("../" + jspSubContext); } if (breadcrumbItems != null) { int bcSize = breadcrumbItems.size(); for (int a = 0; a < bcSize; a++) { BreadCrumbItem tmp = breadcrumbItems.get(a); if (tmp.getId().equals(jspFileName)) { if (tmp.getLink().startsWith("#")) { content.append("<td class=\"breadcrumb-link\"> > " + tmp.getConvertedText() + "</td>"); } else { //if((a+1) == bcSize){ //if((a+1) == bcSize && clickedBreadcrumbLocation > 0){ if ((((a + 1) == bcSize) && !(lastBreadcrumbItemAvailable)) || removeLastItem) { content.append("<td class=\"breadcrumb-link\"> > " + tmp.getConvertedText() + "</td>"); } else { content.append("<td class=\"breadcrumb-link\"> > <a href=\"" + appendOrdinal(tmp.getLink(), i + 1) + "\">" + tmp.getConvertedText() + "</a></td>"); } } cookieContent.append(getSubContextFromUri(tmp.getLink()) + "+" + token + "*"); } } } } } //add last breadcrumb item if (lastBreadcrumbItemAvailable && !(removeLastItem)) { String tmp = getSubContextFromUri(currentBreadcrumbItem.getLink()) + "+" + currentBreadcrumbItem.getId(); cookieContent.append(tmp); cookieContent.append("*"); content.append("<td class=\"breadcrumb-link\"> > " + currentBreadcrumbItem.getConvertedText() + "</td>"); } content.append("</tr></table>"); } } breadcrumbContents.put("html-content", content.toString()); String finalCookieContent = cookieContent.toString(); if (removeLastItem && breadcrumbCookieString != null && breadcrumbCookieString.trim().length() > 0) { finalCookieContent = breadcrumbCookieString; } breadcrumbContents.put("cookie-content", finalCookieContent); return breadcrumbContents; }
From source file:Controladores.controladorProjeto.java
@RequestMapping(value = "salvar-projeto-restrito", produces = "text/html; charset=UTF-8") @ResponseBody/* w w w . j a va 2 s . com*/ public String salvarProjeto(Projeto projeto, BindingResult result, HttpSession sessao, HttpServletRequest request, String operacao) { try { HashMap<String, String> erros = new HashMap<String, String>(); ArrayList<Tag> funcProjeto = funcionariosProjeto(sessao); if (projeto.getNome().trim().length() == 0) { erros.put("erroNomeProjeto", "Informe o nome do projeto"); } if (projeto.getDescricao().trim().length() == 0) { erros.put("erroDescricaoProjeto", "Informe a descrio do projeto"); } if (funcProjeto.isEmpty()) { erros.put("erroFuncionariosProjeto", "Selecione ao menos um funcionrio para o projeto"); } int projetoId = 0; if (erros.isEmpty()) { if (operacao.equalsIgnoreCase("I")) { projeto.setDtcriacao(new Date()); } else { projeto.setDtalteracao(new Date()); } Funcionario f = (Funcionario) sessao.getAttribute("funcionario"); projeto.setUsercriador(f); projetoId = ProjetoDAO.salvarProjeto(projeto, funcProjeto, operacao); } Gson gson = new Gson(); JsonObject myObj = new JsonObject(); if (operacao.equalsIgnoreCase("I")) { myObj.addProperty("projetoId", projetoId); } myObj.addProperty("sucesso", erros.isEmpty()); JsonElement objetoErrosEmJson = gson.toJsonTree(erros); myObj.add("erros", objetoErrosEmJson); return myObj.toString(); } catch (Exception erro) { return null; } }
From source file:org.opensilk.music.library.mediastore.util.FilesUtil.java
@NonNull public static List<File> filterAudioFiles(Context context, List<File> files) { if (files.size() == 0) { return Collections.emptyList(); }// w w w. j a v a 2s . co m //Map for cursor final HashMap<String, File> pathMap = new HashMap<>(); //The returned list final List<File> audioFiles = new ArrayList<>(); //Build the selection final int size = files.size(); final StringBuilder selection = new StringBuilder(); selection.append(MediaStore.Files.FileColumns.DATA + " IN ("); for (int i = 0; i < size; i++) { final File f = files.get(i); final String path = f.getAbsolutePath(); pathMap.put(path, f); //Add file to map while where iterating //TODO it would probably be better to use selectionArgs selection.append("'").append(StringUtils.replace(path, "'", "''")).append("'"); if (i < size - 1) { selection.append(","); } } selection.append(")"); Cursor c = null; try { c = context.getContentResolver().query(MediaStore.Files.getContentUri("external"), Projections.MEDIA_TYPE_PROJECTION, selection.toString(), null, null); if (c != null && c.moveToFirst()) { do { final int mediaType = c.getInt(0); final String path = c.getString(1); final File f = pathMap.remove(path); if (f != null && mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_AUDIO) { audioFiles.add(f); } //else throw away } while (c.moveToNext()); } //either the query failed or the cursor didn't contain all the files we asked for. if (!pathMap.isEmpty()) { Timber.w("%d files weren't found in mediastore. Best guessing mime type", pathMap.size()); for (File f : pathMap.values()) { final String mime = guessMimeType(f); if (StringUtils.contains(mime, "audio") || "application/ogg".equals(mime)) { audioFiles.add(f); } } } } catch (Exception e) { if (FilesUtil.DUMPSTACKS) Timber.e(e, "filterAudioFiles"); } finally { closeQuietly(c); } return audioFiles; }
From source file:com.google.gwt.emultest.java.util.HashMapTest.java
public void testHashMapMap() { HashMap<Integer, Integer> srcMap = new HashMap<Integer, Integer>(); assertNotNull(srcMap);//from w ww. j a va 2 s.c o m checkEmptyHashMapAssumptions(srcMap); srcMap.put(INTEGER_1, INTEGER_11); srcMap.put(INTEGER_2, INTEGER_22); srcMap.put(INTEGER_3, INTEGER_33); HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(srcMap); assertFalse(hashMap.isEmpty()); assertTrue(hashMap.size() == SIZE_THREE); Collection<Integer> valColl = hashMap.values(); assertTrue(valColl.contains(INTEGER_11)); assertTrue(valColl.contains(INTEGER_22)); assertTrue(valColl.contains(INTEGER_33)); Collection<Integer> keyColl = hashMap.keySet(); assertTrue(keyColl.contains(INTEGER_1)); assertTrue(keyColl.contains(INTEGER_2)); assertTrue(keyColl.contains(INTEGER_3)); }