List of usage examples for java.util Set toArray
<T> T[] toArray(T[] a);
From source file:com.twinsoft.convertigo.engine.admin.services.engine.Authenticate.java
@Override protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { boolean logIn = "login".equals(ServiceUtils.getRequiredParameter(request, "authType")); HttpSession httpSession = request.getSession(); // Login/*from ww w .j a v a2 s . c om*/ if (logIn) { String authToken = request.getParameter("authToken"); String user = null; String password = null; if (authToken != null) { try { Class.forName("com.twinsoft.convertigo.eclipse.actions.AdministrationAction") .getMethod("checkAuthToken", String.class).invoke(null, authToken); user = EnginePropertiesManager.getProperty(PropertyName.ADMIN_USERNAME); } catch (Throwable t) { authToken = null; } } if (authToken == null) { user = ServiceUtils.getRequiredParameter(request, "authUserName"); password = ServiceUtils.getRequiredParameter(request, "authPassword"); } httpSession.setAttribute(SessionKey.ADMIN_USER.toString(), user); Engine.logAdmin.info("User '" + user + "' is trying to login"); // Check authentication attempts AuthenticationAttempt authenticationAttempt = Authenticate.authenticationAttempts.get(user); if (authenticationAttempt != null && authenticationAttempt.accountBlockedUntil != 0) { long now = System.currentTimeMillis(); if (now > authenticationAttempt.accountBlockedUntil) { // Unblock the account authenticationAttempt.accountBlockedUntil = 0; authenticationAttempt.numberOfFailedRequests = 0; } else { // Continue blocking the account Engine.logAdmin.warn("Detected possible brute force attack: user '" + user + "' has failed to login too many times; authentication request is blocked."); Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession); long secondsRemaining = (authenticationAttempt.accountBlockedUntil - now) / 1000; ServiceUtils.addMessage(document, document.getDocumentElement(), "The '" + user + "' account is blocked during " + secondsRemaining + " seconds, due to too many failed authentication attempts.\n\n" + "Please wait and retry it later.", "error", false); return; } } Role[] roles = null; // Legacy authentication if (authToken != null || (EnginePropertiesManager.getProperty(PropertyName.ADMIN_USERNAME).equals(user) && EnginePropertiesManager.checkProperty(PropertyName.ADMIN_PASSWORD, password))) { roles = new Role[] { Role.WEB_ADMIN, Role.TEST_PLATFORM, Role.AUTHENTICATED }; } else if (EnginePropertiesManager.getProperty(PropertyName.TEST_PLATFORM_USERNAME).equals(user) && EnginePropertiesManager.checkProperty(PropertyName.TEST_PLATFORM_PASSWORD, password)) { roles = new Role[] { Role.TEST_PLATFORM, Role.AUTHENTICATED }; } else if (Engine.authenticatedSessionManager.hasUser(user) && Engine.authenticatedSessionManager.getPassword(user).equals(DigestUtils.md5Hex(password))) { Set<Role> set = Engine.authenticatedSessionManager.getRoles(user); roles = new Role[set.size() + 1]; set.toArray(roles); roles[roles.length - 1] = Role.AUTHENTICATED; } // Trial authentication else { File hackTrial = new File(Engine.CONFIGURATION_PATH + "/hackTrial.txt"); if (hackTrial.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(hackTrial)); String line = br.readLine(); br.close(); if (!"ok, you can deploy !!".equals(line)) { Engine.logAdmin.error("Trial authentication failure: wrong internal data!"); } else if (user.matches(".+@.+\\.[a-z]+") && user.equals(SimpleCipher.decode(password))) { roles = new Role[] { Role.TRIAL }; httpSession.setAttribute("trial_user", true); } else { Engine.logAdmin.error("Trial authentication failure: wrong username/password"); } } catch (Exception e) { Engine.logAdmin.error("Trial authentication failure: wrong internal data!", e); } } } if (roles == null) { if (authenticationAttempt == null) { //The AuthenticationAttempt object does not exist; we must create a new one authenticationAttempt = new AuthenticationAttempt(); Authenticate.authenticationAttempts.put(user, authenticationAttempt); } Engine.logAdmin.error("Invalid password or user name '" + user + "' (attempt #" + authenticationAttempt.numberOfFailedRequests + ")"); authenticationAttempt.numberOfFailedRequests++; Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession); if (authenticationAttempt.numberOfFailedRequests > Authenticate.MAX_NUMBER_OF_WRONG_AUTHENTICATION_ATTEMPTS) { Engine.logAdmin.warn("Detected possible brute force attack: user '" + user + "' has failed to login too many times; authentication request is blocked."); if (authenticationAttempt.accountBlockedUntil == 0) { authenticationAttempt.accountBlockedUntil = System.currentTimeMillis() + Authenticate.AUTHENTICATION_DELAY * 1000; } long now = System.currentTimeMillis(); long secondsRemaining = (authenticationAttempt.accountBlockedUntil - now) / 1000; ServiceUtils.addMessage(document, document.getDocumentElement(), "The '" + user + "' account is blocked during " + secondsRemaining + " seconds, due to too many failed authentication attempts.\n\n" + "Please wait and retry it later.", "error", false); } else { ServiceUtils.addMessage(document, document.getDocumentElement(), "Invalid authentication!\n\nPlease verify your user ID and/or your password.", "error", false); } } else { Authenticate.authenticationAttempts.remove(user); Engine.authenticatedSessionManager.addAuthenticatedSession(httpSession, roles); ServiceUtils.addMessage(document, document.getDocumentElement(), "", "success"); ServiceUtils.addMessage(document, document.getDocumentElement(), "" + httpSession.getAttribute(SessionKey.ADMIN_USER.toString()), "user", false); ServiceUtils.addRoleNodes(document.getDocumentElement(), roles); SessionAttribute.authenticatedUser.set(httpSession, "c8o:admin"); Engine.logAdmin.info("User '" + user + "' has been successfully authenticated"); } } // Logout else { Engine.authenticatedSessionManager.removeAuthenticatedSession(httpSession); SessionAttribute.authenticatedUser.remove(httpSession); ServiceUtils.addMessage(document, document.getDocumentElement(), "", "success"); } }
From source file:de.fhbingen.wbs.wpOverview.tabs.AvailabilityGraphAction.java
/** * Add the action listener to the graph. *//*from ww w. ja va2 s .c o m*/ private void setAction() { gui.pnlGraph.addChartMouseListener(new ChartMouseListener() { @Override public void chartMouseClicked(final ChartMouseEvent e) { if (e.getEntity() instanceof PlotEntity) { Point2D p = gui.pnlGraph.translateScreenToJava2D(e.getTrigger().getPoint()); CategoryPlot plot = (CategoryPlot) gui.pnlGraph.getChart().getPlot(); Rectangle2D plotArea = gui.pnlGraph.getScreenDataArea(); DateAxis rangeAxis = (DateAxis) plot.getRangeAxis(); RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge(); CategoryAxis catAxis = plot.getDomainAxis(); RectangleEdge domainAxisEdge = plot.getDomainAxisEdge(); double chartY = rangeAxis.java2DToValue(p.getX(), plotArea, rangeAxisEdge); CategoryDataset categories = (CategoryDataset) plot.getDataset(0); int categoryCount = categories.getColumnCount(); for (int i = 0; i < categoryCount; i++) { double catStart = catAxis.getCategoryStart(i, categoryCount, plotArea, domainAxisEdge); double catEnd = catAxis.getCategoryEnd(i, categoryCount, plotArea, domainAxisEdge); if (e.getTrigger().getY() >= catStart && e.getTrigger().getY() < catEnd) { new EditAvailabilityController(gui.function, gui.function.getWorkers().get(i), new Day(new Date((long) chartY)), parent); } } } else { CategoryItemEntity item = (CategoryItemEntity) e.getEntity(); CategoryPlot plot = (CategoryPlot) gui.pnlGraph.getChart().getPlot(); Rectangle2D plotArea = gui.pnlGraph.getScreenDataArea(); RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge(); DateAxis dateAxis = (DateAxis) plot.getRangeAxis(); double d = dateAxis.java2DToValue(e.getEntity().getArea().getBounds2D().getX(), plotArea, rangeAxisEdge); double d2 = dateAxis.java2DToValue(e.getEntity().getArea().getBounds2D().getX() + e.getEntity().getArea().getBounds2D().getWidth(), plotArea, rangeAxisEdge); Date startDate = new Date((long) d); Date endDate = new Date((long) d2); CategoryDataset categories = (CategoryDataset) plot.getDataset(0); int workerIndex = categories.getColumnIndex(item.getColumnKey()); Worker worker = gui.function.getWorkers().get(workerIndex); Set<Availability> found = CalendarService.getAllWorkerAvailability(worker.getId(), startDate, endDate); Availability foundAv = found.toArray(new Availability[1])[0]; if (foundAv != null) { new EditAvailabilityController(gui.function, foundAv, parent); } else { found = CalendarService.getProjectAvailability(startDate, endDate); foundAv = found.toArray(new Availability[1])[0]; if (foundAv != null) { new EditAvailabilityController(gui.function, foundAv, parent); } else { JOptionPane.showMessageDialog( new JFrame(LocalizedStrings.getGeneralStrings().warning()), LocalizedStrings.getErrorMessages().availabilityCanNotBeChanged()); } } } } @Override public void chartMouseMoved(final ChartMouseEvent arg0) { } }); /** * ActionListener */ gui.btnNext.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { gui.function.increment(); } }); /** * ActionListener */ gui.btnPrev.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { gui.function.decrement(); } }); for (int i = 0; i < gui.buttons.length; i++) { addButtonListener(i); } /** * ActionListener */ gui.btnManualAv.addItemListener(new ItemListener() { @Override public void itemStateChanged(final ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { gui.function.setManualAv(true); } else { gui.function.setManualAv(false); } } }); }
From source file:org.pentaho.di.ui.spoon.trans.StepPerformanceSnapShotDialog.java
public StepPerformanceSnapShotDialog(Shell parent, String title, Map<String, List<StepPerformanceSnapShot>> stepPerformanceSnapShots, long timeDifference) { super(parent); this.parent = parent; this.display = parent.getDisplay(); this.props = PropsUI.getInstance(); this.timeDifference = timeDifference; this.title = title; this.stepPerformanceSnapShots = stepPerformanceSnapShots; Set<String> stepsSet = stepPerformanceSnapShots.keySet(); steps = stepsSet.toArray(new String[stepsSet.size()]); Arrays.sort(steps);//from ww w . java 2 s.c o m }
From source file:com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.java
/** * Returns the class configuration of the given {@code klass}. * * @param klass the class/* w ww . ja v a 2 s .c om*/ * @param browser the browser version * @return the class configuration */ public static ClassConfiguration getClassConfiguration(final Class<? extends HtmlUnitScriptable> klass, final BrowserVersion browser) { if (browser != null) { final String expectedBrowserName; if (browser.isIE()) { expectedBrowserName = "IE"; } else if (browser.isFirefox()) { expectedBrowserName = "FF"; } else if (browser.isEdge()) { expectedBrowserName = "EDGE"; } else { expectedBrowserName = "CHROME"; } final float browserVersionNumeric = browser.getBrowserVersionNumeric(); final String hostClassName = klass.getName(); final JsxClasses jsxClasses = klass.getAnnotation(JsxClasses.class); if (jsxClasses != null) { if (klass.getAnnotation(JsxClass.class) != null) { throw new RuntimeException( "Invalid JsxClasses/JsxClass annotation; class '" + hostClassName + "' has both."); } final JsxClass[] jsxClassValues = jsxClasses.value(); final Set<Class<?>> domClasses = new HashSet<>(); boolean isJsObject = false; boolean isDefinedInStandardsMode = false; String className = null; for (int i = 0; i < jsxClassValues.length; i++) { final JsxClass jsxClass = jsxClassValues[i]; if (jsxClass != null && isSupported(jsxClass.browsers(), expectedBrowserName, browserVersionNumeric)) { domClasses.add(jsxClass.domClass()); if (jsxClass.isJSObject()) { isJsObject = true; } if (jsxClass.isDefinedInStandardsMode()) { isDefinedInStandardsMode = true; } if (!jsxClass.className().isEmpty()) { className = jsxClass.className(); } } } final ClassConfiguration classConfiguration = new ClassConfiguration(klass, domClasses.toArray(new Class<?>[0]), isJsObject, isDefinedInStandardsMode, className); process(classConfiguration, hostClassName, expectedBrowserName, browserVersionNumeric); return classConfiguration; } final JsxClass jsxClass = klass.getAnnotation(JsxClass.class); if (jsxClass != null && isSupported(jsxClass.browsers(), expectedBrowserName, browserVersionNumeric)) { final Set<Class<?>> domClasses = new HashSet<>(); final Class<?> domClass = jsxClass.domClass(); if (domClass != null && domClass != Object.class) { domClasses.add(domClass); } String className = jsxClass.className(); if (className.isEmpty()) { className = null; } final ClassConfiguration classConfiguration = new ClassConfiguration(klass, domClasses.toArray(new Class<?>[0]), jsxClass.isJSObject(), jsxClass.isDefinedInStandardsMode(), className); process(classConfiguration, hostClassName, expectedBrowserName, browserVersionNumeric); return classConfiguration; } } return null; }
From source file:io.kamax.mxisd.backend.ldap.LdapAuthProvider.java
@Override public BackendAuthResult authenticate(_MatrixID mxid, String password) { log.info("Performing auth for {}", mxid); try (LdapConnection conn = getConn()) { bind(conn);//from w w w. j a v a 2 s . c o m String uidType = getAt().getUid().getType(); String userFilterValue = StringUtils.equals(LdapBackend.UID, uidType) ? mxid.getLocalPart() : mxid.getId(); if (StringUtils.isBlank(userFilterValue)) { log.warn("Username is empty, failing auth"); return BackendAuthResult.failure(); } String userFilter = "(" + getUidAtt() + "=" + userFilterValue + ")"; userFilter = buildWithFilter(userFilter, getCfg().getAuth().getFilter()); Set<String> attributes = new HashSet<>(); attributes.add(getUidAtt()); attributes.add(getAt().getName()); getAt().getThreepid().forEach((k, v) -> attributes.addAll(v)); String[] attArray = new String[attributes.size()]; attributes.toArray(attArray); log.debug("Base DN: {}", getBaseDn()); log.debug("Query: {}", userFilter); log.debug("Attributes: {}", GsonUtil.build().toJson(attArray)); try (EntryCursor cursor = conn.search(getBaseDn(), userFilter, SearchScope.SUBTREE, attArray)) { while (cursor.next()) { Entry entry = cursor.get(); String dn = entry.getDn().getName(); log.info("Checking possible match, DN: {}", dn); if (!getAttribute(entry, getUidAtt()).isPresent()) { continue; } log.info("Attempting authentication on LDAP for {}", dn); try { conn.bind(entry.getDn(), password); } catch (LdapException e) { log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage()); return BackendAuthResult.failure(); } Attribute nameAttribute = entry.get(getAt().getName()); String name = nameAttribute != null ? nameAttribute.get().toString() : null; log.info("Authentication successful for {}", entry.getDn().getName()); log.info("DN {} is a valid match", dn); // TODO should we canonicalize the MXID? BackendAuthResult result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name); log.info("Processing 3PIDs for profile"); getAt().getThreepid().forEach((k, v) -> { log.info("Processing 3PID type {}", k); v.forEach(attId -> { List<String> values = getAttributes(entry, attId); log.info("\tAttribute {} has {} value(s)", attId, values.size()); getAttributes(entry, attId).forEach(tpidValue -> { if (ThreePidMedium.PhoneNumber.is(k)) { tpidValue = getMsisdn(tpidValue).orElse(tpidValue); } result.withThreePid(new ThreePid(k, tpidValue)); }); }); }); log.info("Found {} 3PIDs", result.getProfile().getThreePids().size()); return result; } } catch (CursorLdapReferralException e) { log.warn("Entity for {} is only available via referral, skipping", mxid); } log.info("No match were found for {}", mxid); return BackendAuthResult.failure(); } catch (LdapException | IOException | CursorException e) { throw new RuntimeException(e); } }
From source file:org.jboss.spring.support.SpringInjectionSupport.java
protected Method[] getAllMethods(Object bean) { Class<?> beanClass = bean.getClass(); Set<Method> methods = new TreeSet<Method>(METHOD_COMPARATOR); while (beanClass != Object.class) { methods.addAll(Arrays.asList(beanClass.getDeclaredMethods())); beanClass = beanClass.getSuperclass(); }/*from ww w. j a v a 2 s. co m*/ return methods.toArray(new Method[methods.size()]); }
From source file:be.fgov.kszbcss.rhq.websphere.component.pme.WorkManagerJndiNamesQuery.java
public String[] execute(Config config) throws JMException, ConnectorException, InterruptedException, ConfigQueryException { Set<String> result = new HashSet<String>(); for (WorkManagerInfoCO wm : config.allScopes(node, server).path(WorkManagerProviderCO.class) .path(WorkManagerInfoCO.class).resolve(false)) { result.add(wm.getJndiName());/*from w ww.j a v a2 s .c o m*/ } if (log.isDebugEnabled()) { log.debug("Loaded work managers for node '" + node + "' and server '" + server + "': " + result); } return result.toArray(new String[result.size()]); }
From source file:com.servoy.extensions.plugins.http.Response.java
public String[] getAllowedMethods() { HeaderIterator it = res.headerIterator(OptionsRequest.OPTIONS_HEADER); Set<String> methods = new HashSet<String>(); while (it.hasNext()) { Header header = it.nextHeader(); HeaderElement[] elements = header.getElements(); for (HeaderElement element : elements) { methods.add(element.getName()); }//from w w w . ja v a2 s . c om } return methods.toArray(new String[0]); }
From source file:be.fgov.kszbcss.rhq.websphere.component.pme.TimerManagerJndiNamesQuery.java
public String[] execute(Config config) throws JMException, ConnectorException, InterruptedException, ConfigQueryException { Set<String> result = new HashSet<String>(); for (TimerManagerInfoCO tm : config.allScopes(node, server).path(TimerManagerProviderCO.class) .path(TimerManagerInfoCO.class).resolve(false)) { result.add(tm.getJndiName());/* ww w. jav a2 s . c o m*/ } if (log.isDebugEnabled()) { log.debug("Loaded timer managers for node '" + node + "' and server '" + server + "': " + result); } return result.toArray(new String[result.size()]); }
From source file:com.impetus.kundera.persistence.AssociationBuilder.java
/** * Retrieves associated entities via running query into Lucene indexing. *//*from ww w. j a va2s . co m*/ private List getAssociatedEntitiesFromLucene(Object entity, String entityId, Class<?> childClass, Client childClient) { List associatedEntities; // Lucene query, where entity class is child class, parent class is // entity's class // and parent Id is entity ID! that's it! String query = LuceneQueryUtils.getQuery(DocumentIndexer.PARENT_ID_CLASS, entity.getClass().getCanonicalName().toLowerCase(), DocumentIndexer.PARENT_ID_FIELD, entityId, childClass.getCanonicalName().toLowerCase()); Map<String, String> results = childClient.getIndexManager().search(query); Set<String> rsSet = new HashSet<String>(results.values()); if (childClass.equals(entity.getClass())) { associatedEntities = (List<Object>) childClient.findAll(childClass, rsSet.toArray(new String[] {})); } else { associatedEntities = (List<Object>) childClient.findAll(childClass, rsSet.toArray(new String[] {})); } return associatedEntities; }