List of usage examples for java.util ArrayList isEmpty
public boolean isEmpty()
From source file:com.twitter.ambrose.hive.HiveDAGTransformer.java
/** * Converts job properties to a DAGNode representation * /*from ww w . j a v a 2 s.c o m*/ * @param task * @return * hive 1.1.4 no MapredWork.getAllOperators function, so add it here */ public List<Operator<?>> getAllOperators(MapredWork myWork) { ArrayList<Operator<?>> opList = new ArrayList<Operator<?>>(); ArrayList<Operator<?>> returnList = new ArrayList<Operator<?>>(); if (myWork.getReducer() != null) { opList.add(myWork.getReducer()); } Map<String, ArrayList<String>> pa = myWork.getPathToAliases(); if (pa != null) { for (List<String> ls : pa.values()) { for (String a : ls) { Operator<?> op = myWork.getAliasToWork().get(a); if (op != null) { opList.add(op); } } } } //recursively add all children while (!opList.isEmpty()) { Operator<?> op = opList.remove(0); if (op.getChildOperators() != null) { opList.addAll(op.getChildOperators()); } returnList.add(op); } return returnList; }
From source file:probe.com.view.core.chart4j.VennDiagramPanel.java
/** * Handles mouse clicks in the chart panel. * * @param event the chart mouse event/*from w w w . j a v a 2 s . c om*/ */ private void mouseClickedInChart(ChartMouseEvent event) { ArrayList<ChartEntity> entities = getEntitiesForPoint(event.getTrigger().getPoint().x, event.getTrigger().getPoint().y); if (entities.isEmpty()) { return; } boolean dataPointFound = false; String dataPointTooltip = ""; for (ChartEntity tempEntity : entities) { if (tempEntity instanceof XYAnnotationEntity) { if (((XYAnnotationEntity) tempEntity).getToolTipText() != null) { dataPointFound = true; dataPointTooltip = ((XYAnnotationEntity) tempEntity).getToolTipText(); } } } if (dataPointFound) { String dataset = tooltipToDatasetMap.get(dataPointTooltip); JOptionPane.showMessageDialog(this, dataPointTooltip + ":\n" + vennDiagramResults.get(dataset), "Selected Values", JOptionPane.INFORMATION_MESSAGE); } }
From source file:gov.lanl.adore.djatoka.plugin.ExtractPDF.java
/** * Get PDF information with pdfinfo://w w w . j av a 2 s . c o m * - "Pages: X": number of pages; * - "Page X size: www.ww hhh.hh": size of each page, in pts. * @returns a map: * - [Pages][n] * - [Page 1][111.11 222.22] * - [Page i][www.ww hhh.hh] * - [Page n][999.99 1000.00] */ private static Map<String, String> getPDFProperties(ImageRecord input) throws DjatokaException { logger.debug("Getting PDF info"); try { setPDFCommandsPath(); } catch (IllegalStateException e) { logger.error("Failed to set PDF commands path: ", e); throw e; } HashMap<String, String> pdfProperties = new HashMap<String, String>(); String sourcePath = null; if (input.getImageFile() != null) { logger.debug("PDFInfo image file: " + input.getImageFile()); sourcePath = input.getImageFile(); } else if (input.getObject() != null && (input.getObject() instanceof InputStream)) { FileInputStream fis = null; fis = (FileInputStream) input.getObject(); File in; // Copy to tmp file try { String cacheDir = OpenURLJP2KService.getCacheDir(); if (cacheDir != null) { in = File.createTempFile("tmp", ".pdf", new File(cacheDir)); } else { in = File.createTempFile("tmp", ".pdf"); } in.deleteOnExit(); FileOutputStream fos = new FileOutputStream(in); IOUtils.copyStream(fis, fos); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } sourcePath = in.getAbsolutePath(); } else { throw new DjatokaException("File not defined and Input Object Type " + input //.getObject().getClass().getName() + " is not supported"); } String pdfinfoCmd[] = PDFINFO_COMMAND.clone(); pdfinfoCmd[PDFINFO_COMMAND_POSITION_BIN] = pdfinfoPath; pdfinfoCmd[PDFINFO_COMMAND_POSITION_FIRSTPAGE] = "1"; pdfinfoCmd[PDFINFO_COMMAND_POSITION_LASTPAGE] = "-1"; // Last page even we not knowing its number. pdfinfoCmd[PDFINFO_COMMAND_POSITION_FILE] = sourcePath; Process pdfProc = null; try { ArrayList<MatchResult> pageSizes = new ArrayList<MatchResult>(); MatchResult pages = null; pdfProc = Runtime.getRuntime().exec(pdfinfoCmd); BufferedReader lr = new BufferedReader(new InputStreamReader(pdfProc.getInputStream())); String line; for (line = lr.readLine(); line != null; line = lr.readLine()) { Matcher mm1 = PAGES_PATT.matcher(line); if (mm1.matches()) pages = mm1.toMatchResult(); Matcher mm2 = MEDIABOX_PATT.matcher(line); if (mm2.matches()) pageSizes.add(mm2.toMatchResult()); } int istatus = pdfProc.waitFor(); if (istatus != 0) logger.error("pdfinfo proc failed, exit status=" + istatus + ", file=" + sourcePath); if (pages == null) { logger.error("Did not find 'Pages' line in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); pdfProperties.put("Pages", "0"); } else { //int n = Integer.parseInteger(pages.group(1)); pdfProperties.put("Pages", pages.group(1)); } if (pageSizes.isEmpty()) { logger.error("Did not find \"Page X size\" lines in output of pdfinfo command: " + Arrays.deepToString(pdfinfoCmd)); throw new IllegalArgumentException("Failed to get pages size of PDF with pdfinfo."); } else { for (MatchResult mr : pageSizes) { String page = mr.group(1); float x0 = Float.parseFloat(mr.group(2)); float y0 = Float.parseFloat(mr.group(3)); float x1 = Float.parseFloat(mr.group(4)); float y1 = Float.parseFloat(mr.group(5)); float w = Math.abs(x1 - x0); float h = Math.abs(y1 - y0); // Have to scale page sizes by max dpi (MAX_DPI / DEFAULT_DENSITY). Otherwise, BookReader.js will request the wrong zoom level (svc.level). float ws = w * MAX_DPI / DEFAULT_DENSITY; float hs = h * MAX_DPI / DEFAULT_DENSITY; String width = "" + ws; //mr.group(2); String height = "" + hs; //mr.group(3); pdfProperties.put("Page " + page, width + " " + height); } } } catch (Exception e) { logger.error("Failed getting PDF information: ", e); throw new DjatokaException("Failed getting PDF information: ", e); } finally { // Our exec() should just consume one of the streams, but we want to stay safe. // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream()); org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream()); } return pdfProperties; }
From source file:com.thoughtworks.go.plugin.access.pluggabletask.JsonBasedTaskExtensionHandler_V1.java
@Override public TaskView toTaskView(String responseBody) { ArrayList<String> exceptions = new ArrayList<>(); try {// ww w .j av a2 s. c o m final Map map = (Map) new GsonBuilder().create().fromJson(responseBody, Object.class); if (map.isEmpty()) { exceptions.add("The Json for Task View cannot be empty"); } else { if (!(map.containsKey("displayValue") && map.get("displayValue") instanceof String)) { exceptions.add("The Json for Task View must contain a not-null 'displayValue' of type String"); } if (!(map.containsKey("template") && map.get("template") instanceof String)) { exceptions.add("The Json for Task View must contain a not-null 'template' of type String"); } } if (!exceptions.isEmpty()) { throw new RuntimeException(StringUtils.join(exceptions, ", ")); } return new TaskView() { @Override public String displayValue() { return (String) map.get("displayValue"); } @Override public String template() { return (String) map.get("template"); } }; } catch (Exception e) { LOGGER.error( "Error occurred while converting the Json to Task View. Error: {}. The Json received was '{}'.", e.getMessage(), responseBody); throw new RuntimeException(String .format("Error occurred while converting the Json to Task View. Error: %s.", e.getMessage())); } }
From source file:com.erudika.para.security.SecurityConfig.java
/** * Configures the protected private resources * * @param http HTTP sec object/*from w w w. j a va 2s. c om*/ * @throws Exception ex */ @Override protected void configure(HttpSecurity http) throws Exception { String[] defRoles = { "USER", "MOD", "ADMIN" }; Map<String, String> confMap = Config.getConfigMap(); ConfigObject c = Config.getConfig().getObject("security.protected"); ConfigValue apiSec = Config.getConfig().getValue("security.api_security"); boolean enableRestFilter = apiSec != null && Boolean.TRUE.equals(apiSec.unwrapped()); for (String key : c.keySet()) { ConfigValue cv = c.get(key); ArrayList<String> patterns = new ArrayList<String>(); ArrayList<String> roles = new ArrayList<String>(); // if API security is disabled don't add any API related patterns // to the list of protected resources if (!"api".equals(key) || enableRestFilter) { for (ConfigValue configValue : (ConfigList) cv) { if (configValue instanceof List) { for (ConfigValue role : (ConfigList) configValue) { roles.add(((String) role.unwrapped()).toUpperCase()); } } else { patterns.add((String) configValue.unwrapped()); } } String[] rolz = (roles.isEmpty()) ? defRoles : roles.toArray(new String[0]); http.authorizeRequests().antMatchers(patterns.toArray(new String[0])).hasAnyRole(rolz); } } if (Config.getConfigParamUnwrapped("security.csrf_protection", true)) { CachedCsrfTokenRepository str = new CachedCsrfTokenRepository(); Para.injectInto(str); http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() { private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$"); private final RegexRequestMatcher authEndpoints = new RegexRequestMatcher("^/\\w+_auth$", null); public boolean matches(HttpServletRequest request) { boolean matches = !RestRequestMatcher.INSTANCE.matches(request) && !IgnoredRequestMatcher.INSTANCE.matches(request) && !authEndpoints.matches(request) && !allowedMethods.matcher(request.getMethod()).matches(); return matches; } }).csrfTokenRepository(str); } else { http.csrf().disable(); } http.sessionManagement().enableSessionUrlRewriting(false); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); http.sessionManagement().sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()); http.exceptionHandling() .authenticationEntryPoint(new SimpleAuthenticationEntryPoint(confMap.get("security.signin"))); http.exceptionHandling() .accessDeniedHandler(new SimpleAccessDeniedHandler(confMap.get("security.access_denied"))); http.requestCache().requestCache(new SimpleRequestCache()); http.logout().logoutUrl(confMap.get("security.signout")) .logoutSuccessUrl(confMap.get("security.signout_success")); SimpleAuthenticationSuccessHandler successHandler = new SimpleAuthenticationSuccessHandler(); successHandler.setDefaultTargetUrl(confMap.get("security.signin_success")); successHandler.setTargetUrlParameter(confMap.get("security.returnto")); successHandler.setUseReferer(true); SimpleAuthenticationFailureHandler failureHandler = new SimpleAuthenticationFailureHandler(); failureHandler.setDefaultFailureUrl(confMap.get("security.signin_failure")); SimpleRememberMeServices tbrms = new SimpleRememberMeServices(Config.APP_SECRET_KEY, new SimpleUserService()); tbrms.setAlwaysRemember(true); tbrms.setTokenValiditySeconds(Config.SESSION_TIMEOUT_SEC.intValue()); tbrms.setCookieName(Config.AUTH_COOKIE); tbrms.setParameter(Config.AUTH_COOKIE.concat("-remember-me")); http.rememberMe().rememberMeServices(tbrms); PasswordAuthFilter passwordFilter = new PasswordAuthFilter("/" + PasswordAuthFilter.PASSWORD_ACTION); passwordFilter.setAuthenticationManager(authenticationManager()); passwordFilter.setAuthenticationSuccessHandler(successHandler); passwordFilter.setAuthenticationFailureHandler(failureHandler); passwordFilter.setRememberMeServices(tbrms); OpenIDAuthFilter openidFilter = new OpenIDAuthFilter("/" + OpenIDAuthFilter.OPENID_ACTION); openidFilter.setAuthenticationManager(authenticationManager()); openidFilter.setConsumer(new OpenID4JavaConsumer(new SimpleAxFetchListFactory())); openidFilter.setReturnToUrlParameters(Collections.singleton(confMap.get("security.returnto"))); openidFilter.setAuthenticationSuccessHandler(successHandler); openidFilter.setAuthenticationFailureHandler(failureHandler); openidFilter.setRememberMeServices(tbrms); FacebookAuthFilter facebookFilter = new FacebookAuthFilter("/" + FacebookAuthFilter.FACEBOOK_ACTION); facebookFilter.setAuthenticationManager(authenticationManager()); facebookFilter.setAuthenticationSuccessHandler(successHandler); facebookFilter.setAuthenticationFailureHandler(failureHandler); facebookFilter.setRememberMeServices(tbrms); GoogleAuthFilter googleFilter = new GoogleAuthFilter("/" + GoogleAuthFilter.GOOGLE_ACTION); googleFilter.setAuthenticationManager(authenticationManager()); googleFilter.setAuthenticationSuccessHandler(successHandler); googleFilter.setAuthenticationFailureHandler(failureHandler); googleFilter.setRememberMeServices(tbrms); LinkedInAuthFilter linkedinFilter = new LinkedInAuthFilter("/" + LinkedInAuthFilter.LINKEDIN_ACTION); linkedinFilter.setAuthenticationManager(authenticationManager()); linkedinFilter.setAuthenticationSuccessHandler(successHandler); linkedinFilter.setAuthenticationFailureHandler(failureHandler); linkedinFilter.setRememberMeServices(tbrms); TwitterAuthFilter twitterFilter = new TwitterAuthFilter("/" + TwitterAuthFilter.TWITTER_ACTION); twitterFilter.setAuthenticationManager(authenticationManager()); twitterFilter.setAuthenticationSuccessHandler(successHandler); twitterFilter.setAuthenticationFailureHandler(failureHandler); twitterFilter.setRememberMeServices(tbrms); GitHubAuthFilter githubFilter = new GitHubAuthFilter("/" + GitHubAuthFilter.GITHUB_ACTION); githubFilter.setAuthenticationManager(authenticationManager()); githubFilter.setAuthenticationSuccessHandler(successHandler); githubFilter.setAuthenticationFailureHandler(failureHandler); githubFilter.setRememberMeServices(tbrms); http.addFilterAfter(passwordFilter, BasicAuthenticationFilter.class); http.addFilterAfter(openidFilter, BasicAuthenticationFilter.class); http.addFilterAfter(facebookFilter, BasicAuthenticationFilter.class); http.addFilterAfter(googleFilter, BasicAuthenticationFilter.class); http.addFilterAfter(linkedinFilter, BasicAuthenticationFilter.class); http.addFilterAfter(twitterFilter, BasicAuthenticationFilter.class); http.addFilterAfter(githubFilter, BasicAuthenticationFilter.class); if (enableRestFilter) { RestAuthFilter restFilter = new RestAuthFilter(new Signer()); http.addFilterAfter(restFilter, RememberMeAuthenticationFilter.class); } }
From source file:info.savestate.saveybot.JSONFileManipulator.java
public String chain(String username, boolean verbose, int sentenceSize) { username = username.trim();/* www .j av a 2 s. co m*/ JSONArray json = getJSON(); ArrayList<String> words = new ArrayList<>(); for (int i = 0; i < json.length(); i++) { JSONObject savestate = json.getJSONObject(i); if (savestate.getString("name").toLowerCase().equals(username.toLowerCase())) { String[] splitMessage = savestate.getString("message").split("\\s+"); words.addAll(Arrays.asList(splitMessage)); } } if (words.isEmpty()) { return "helo there that person SUCKS for not having any SAVESTATES O:<"; } StringBuilder sb = new StringBuilder(); // all words are in "words" // pick a word out at random! int wordIndex = (int) (Math.random() * words.size()); if (sentenceSize <= 0) sentenceSize = ((int) (Math.random() * 6)) + 5; if (sentenceSize > 50) sentenceSize = 50; for (int i = 0; i < sentenceSize; i++) { // get current word sb.append(words.get(wordIndex)).append(' '); // 40% chance we'll stay on the same sentence. if (Math.random() > 0.40) { // different sentence // make an array of all the .toLowerCase() matches of the current word ArrayList<Integer> wordIndexes = new ArrayList<>(); for (int j = 0; j < words.size(); j++) { if (words.get(j).equalsIgnoreCase(words.get(wordIndex))) wordIndexes.add(j); } // we have all the word indexes in wordIndexes // ... if there are none, we'll just follow the current word (since it'll match) int sameWordIndex = (int) (Math.random() * wordIndexes.size()); wordIndex = wordIndexes.get(sameWordIndex) + 1; } else { wordIndex++; } if (wordIndex >= words.size()) { // in case we go over!!! // new random number wordIndex = (int) (Math.random() * words.size()); } } return sb.toString(); }
From source file:uk.ac.soton.itinnovation.sad.service.helpers.RssHelper.java
/** * Converts SAD job data in the database to a custom RSS feed for Digital * Schladming experiment./*from ww w .ja v a 2 s . c o m*/ * * @param jobData data entries. * @param type data type. * @param keywordsForTaggingAsString keywords for tagging. * @param href RSS href parameter value. * @return custom RSS feed for Digital Schladming experiment * @throws ParserConfigurationException * @throws ParseException * @throws TransformerException */ public String sadDataToCustomRss(ArrayList<SADJobData> jobData, String type, String keywordsForTaggingAsString, String href) throws ParserConfigurationException, ParseException, TransformerException { if (type.equalsIgnoreCase("twitter-hot-tweets")) { return sadDataToSchladmingTwitterRss(jobData, keywordsForTaggingAsString, href); } else if (type.equalsIgnoreCase("facebook-posts-topics-tagged")) { return sadDataToSchladmingFacebookRss(jobData); } else { if (jobData.isEmpty()) { builder = XMLBuilder.create("rss").a("version", "2.0") .a("xmlns:content", "http://purl.org/rss/1.0/modules/content/") .a("xmlns:wfw", "http://wellformedweb.org/CommentAPI/").e("channel").e("title") .t("Empty XML EXPERIMEDIA Feed").up().e("link").t("http://onmeedia.com/feeds/").up() .e("updated").t(dateFormatFacebook.format(new Date())).up().e("author").e("name") .t("http://onmeedia.com/feeds/"); return builder.asString(outputProperties); } else { if (jobData.get(0).getDataType().equalsIgnoreCase("twitter-hot-tweets")) { logger.warn( "Custom RSS type autodetected (based on first data entry type) to be 'twitter-hot-tweets'. All other data entries will be ignored"); return sadDataToSchladmingTwitterRss(jobData, keywordsForTaggingAsString, href); } else if (jobData.get(0).getDataType().equalsIgnoreCase("facebook-posts-topics-tagged")) { logger.warn( "Custom RSS type autodetected (based on first data entry type) to be 'facebook-posts-topics-tagged'. All other data entries will be ignored"); return sadDataToSchladmingFacebookRss(jobData); } else { builder = XMLBuilder.create("rss").a("version", "2.0") .a("xmlns:content", "http://purl.org/rss/1.0/modules/content/") .a("xmlns:wfw", "http://wellformedweb.org/CommentAPI/").e("channel").e("title") .t("Unknown data type XML EXPERIMEDIA Feed").up().e("link") .t("http://onmeedia.com/feeds/").up().e("updated") .t(dateFormatFacebook.format(new Date())).up().e("author").e("name") .t("http://onmeedia.com/feeds/"); return builder.asString(outputProperties); } } } }
From source file:com.evolveum.midpoint.web.component.wizard.resource.SynchronizationStep.java
private void deleteSyncObjectPerformed(AjaxRequestTarget target, ObjectSynchronizationType syncObject) { if (isSelected(syncObject)) { syncDtoModel.getObject().setSelected(null); insertEmptyThirdRow();/*www . j a v a2s .c om*/ resetSelections(target); target.add(getThirdRowContainer()); } ArrayList<ObjectSynchronizationType> list = (ArrayList<ObjectSynchronizationType>) syncDtoModel.getObject() .getObjectSynchronizationList(); list.remove(syncObject); if (list.isEmpty()) { insertEmptyThirdRow(); resetSelections(target); target.add(getThirdRowContainer()); } target.add(getSyncObjectEditor(), getSyncObjectTable(), getNavigator()); parentPage.refreshIssues(target); }
From source file:Emporium.Servlet.ServImportaVpne.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . ja va 2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession sessao = request.getSession(); String nomeBD = (String) sessao.getAttribute("nomeBD"); boolean isMultiPart = FileUpload.isMultipartContent(request); int idCliente = 0, idDepartamento = 0; if (nomeBD != null) { if (isMultiPart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 2); List items = upload.parseRequest(request); Iterator iter = items.iterator(); ArrayList<FileItem> listaArq = new ArrayList<>(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("idCliente")) { idCliente = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("idDepartamento")) { idDepartamento = Integer.parseInt(item.getString()); } } if (!item.isFormField()) { if (item.getName().length() > 0) { listaArq.add(item); } } } if (listaArq.isEmpty()) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Escolha um arquivo para importacao !"); } else if (listaArq.size() > 200) { response.sendRedirect( "Cliente/Servicos/vpne.jsp?msg=Importacao maxima de 200 arquivos de cada vez!"); } else { String condicao = ContrVpne.importaPedidoVpne(listaArq, idCliente, idDepartamento, nomeBD); if (condicao.startsWith("ERRO")) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao); } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao); } } } catch (FileUploadException ex) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex); } catch (Exception ex) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex); } } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=is not a multipart form"); } } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Sua sessao expirou!"); } }
From source file:com.tesora.dve.tools.analyzer.Analyzer.java
private void validateFKs(final String dbName, List<String> tableNames) { final SchemaContext sc = tee.getPersistenceContext(); final PEDatabase db = sc.findPEDatabase(new UnqualifiedName(dbName)); if (db == null) { return;/*from w w w . j a v a2 s . c o m*/ } final ArrayList<ValidateResult> results = new ArrayList<ValidateResult>(); for (final String tn : tableNames) { final TableInstance ti = db.getSchema().buildInstance(sc, new UnqualifiedName(tn), null); if (ti == null) { continue; } final PEAbstractTable<?> pet = ti.getAbstractTable(); if (pet.isView()) { continue; } final List<PEForeignKey> fks = pet.asTable().getForeignKeys(sc); for (final PEForeignKey pefk : fks) { results.addAll(pefk.validate(sc, false)); } } if (results.isEmpty()) { return; } final StringBuilder errorMessage = new StringBuilder(); for (final ValidateResult vr : results) { errorMessage.append(vr.getMessage(sc)).append(PEConstants.LINE_SEPARATOR); } throw new SchemaException(Pass.PLANNER, errorMessage.toString()); }