List of usage examples for java.util TreeSet toArray
<T> T[] toArray(T[] a);
From source file:org.apache.accumulo.core.client.mapreduce.lib.partition.RangePartitioner.java
private synchronized Text[] getCutPoints() throws IOException { if (cutPointArray == null) { String cutFileName = conf.get(CUTFILE_KEY); Path[] cf = DistributedCacheHelper.getLocalCacheFiles(conf); if (cf != null) { for (Path path : cf) { if (path.toUri().getPath().endsWith(cutFileName.substring(cutFileName.lastIndexOf('/')))) { TreeSet<Text> cutPoints = new TreeSet<Text>(); Scanner in = new Scanner(new BufferedReader( new InputStreamReader(new FileInputStream(path.toString()), Constants.UTF8))); try { while (in.hasNextLine()) cutPoints/*from w ww. j av a 2s . co m*/ .add(new Text(Base64.decodeBase64(in.nextLine().getBytes(Constants.UTF8)))); } finally { in.close(); } cutPointArray = cutPoints.toArray(new Text[cutPoints.size()]); break; } } } if (cutPointArray == null) throw new FileNotFoundException(cutFileName + " not found in distributed cache"); } return cutPointArray; }
From source file:org.wso2.andes.kernel.slot.SlotManagerClusterMode.java
/** * {@inheritDoc}/*from w w w .jav a 2 s . c o m*/ */ @Override public long getSafeZoneLowerBoundId(String queueName) throws AndesException { long lowerBoundId = -1; String lockKey = queueName + SlotManagerClusterMode.class; synchronized (lockKey.intern()) { //get the upper bound messageID for each unassigned slots as a set for the specific queue TreeSet<Long> messageIDSet = slotAgent.getSlotBasedMessageIds(queueName); if (messageIDSet.size() >= safetySlotCount) { lowerBoundId = messageIDSet.toArray(new Long[messageIDSet.size()])[safetySlotCount - 1] + 1; // Inform the slot manager regarding the current expiry deletion range and queue setDeletionTaskState(queueName, lowerBoundId); } } return lowerBoundId; }
From source file:jetbrains.exodus.entitystore.PersistentEntityStoreRefactorings.java
void refactorMakePropTablesConsistent() { store.executeInReadonlyTransaction(new StoreTransactionalExecutable() { @Override//ww w. ja v a 2 s . c om public void execute(@NotNull final StoreTransaction tx) { final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx; for (final String entityType : store.getEntityTypes(txn)) { if (log.isInfoEnabled()) { log.info("Refactoring making props' tables consistent for [" + entityType + ']'); } try { final int entityTypeId = store.getEntityTypeId(txn, entityType, false); final PropertiesTable propTable = store.getPropertiesTable(txn, entityTypeId); final Transaction envTxn = txn.getEnvironmentTransaction(); final IntHashMap<LongHashMap<PropertyValue>> props = new IntHashMap<>(); final Cursor cursor = store.getPrimaryPropertyIndexCursor(txn, propTable); while (cursor.getNext()) { final PropertyKey propKey = PropertyKey.entryToPropertyKey(cursor.getKey()); final PropertyValue propValue = store.getPropertyTypes() .entryToPropertyValue(cursor.getValue()); final int propId = propKey.getPropertyId(); LongHashMap<PropertyValue> entitiesToValues = props.get(propId); if (entitiesToValues == null) { entitiesToValues = new LongHashMap<>(); props.put(propId, entitiesToValues); } entitiesToValues.put(propKey.getEntityLocalId(), propValue); } cursor.close(); final List<Pair<Integer, Pair<ByteIterable, ByteIterable>>> missingPairs = new ArrayList<>(); final IntHashMap<Set<Long>> allPropsMap = new IntHashMap<>(); for (final int propId : props.keySet()) { final Store valueIndex = propTable.getValueIndex(txn, propId, false); final Cursor valueCursor = valueIndex == null ? null : valueIndex.openCursor(envTxn); final LongHashMap<PropertyValue> entitiesToValues = props.get(propId); final Set<Long> localIdSet = entitiesToValues.keySet(); final TreeSet<Long> sortedLocalIdSet = new TreeSet<>(localIdSet); allPropsMap.put(propId, sortedLocalIdSet); final Long[] localIds = sortedLocalIdSet.toArray(new Long[entitiesToValues.size()]); for (final long localId : localIds) { final PropertyValue propValue = entitiesToValues.get(localId); final ByteIterable secondaryKey = PropertiesTable.createSecondaryKey( store.getPropertyTypes(), PropertyTypes.propertyValueToEntry(propValue), propValue.getType()); final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId); if (valueCursor == null || !valueCursor.getSearchBoth(secondaryKey, secondaryValue)) { missingPairs.add(new Pair<>(propId, new Pair<>(secondaryKey, secondaryValue))); } } if (valueCursor != null) { valueCursor.close(); } } if (!missingPairs.isEmpty()) { store.executeInTransaction(new StoreTransactionalExecutable() { @Override public void execute(@NotNull final StoreTransaction tx) { final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx; for (final Pair<Integer, Pair<ByteIterable, ByteIterable>> pair : missingPairs) { final Store valueIndex = propTable.getValueIndex(txn, pair.getFirst(), true); final Pair<ByteIterable, ByteIterable> missing = pair.getSecond(); if (valueIndex == null) { throw new NullPointerException("Can't be"); } valueIndex.put(txn.getEnvironmentTransaction(), missing.getFirst(), missing.getSecond()); } } }); if (log.isInfoEnabled()) { log.info(missingPairs.size() + " missing secondary keys found and fixed for [" + entityType + ']'); } } final List<Pair<Integer, Pair<ByteIterable, ByteIterable>>> phantomPairs = new ArrayList<>(); for (final Map.Entry<Integer, Store> entry : propTable.getValueIndices()) { final int propId = entry.getKey(); final LongHashMap<PropertyValue> entitiesToValues = props.get(propId); final Cursor c = entry.getValue().openCursor(envTxn); while (c.getNext()) { final ByteIterable keyEntry = c.getKey(); final ByteIterable valueEntry = c.getValue(); final PropertyValue propValue = entitiesToValues .get(LongBinding.compressedEntryToLong(valueEntry)); if (propValue == null) { phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry))); } else { final ComparableBinding objectBinding = propValue.getBinding(); final Comparable value; try { value = objectBinding.entryToObject(keyEntry); } catch (Throwable t) { throwJVMError(t); phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry))); continue; } final Comparable data = propValue.getData(); //noinspection unchecked if (!data.getClass().equals(value.getClass()) || PropertyTypes.toLowerCase(data).compareTo(value) != 0) { phantomPairs.add(new Pair<>(propId, new Pair<>(keyEntry, valueEntry))); } } } c.close(); } if (!phantomPairs.isEmpty()) { store.executeInTransaction(new StoreTransactionalExecutable() { @Override public void execute(@NotNull final StoreTransaction tx) { final PersistentStoreTransaction txn = (PersistentStoreTransaction) tx; final Transaction envTxn = txn.getEnvironmentTransaction(); for (final Pair<Integer, Pair<ByteIterable, ByteIterable>> pair : phantomPairs) { final Store valueIndex = propTable.getValueIndex(txn, pair.getFirst(), true); final Pair<ByteIterable, ByteIterable> phantom = pair.getSecond(); if (valueIndex == null) { throw new NullPointerException("Can't be"); } deletePair(valueIndex.openCursor(envTxn), phantom.getFirst(), phantom.getSecond()); } } }); if (log.isInfoEnabled()) { log.info(phantomPairs.size() + " phantom secondary keys found and fixed for [" + entityType + ']'); } } final List<Pair<Integer, Long>> phantomIds = new ArrayList<>(); final Cursor c = propTable.getAllPropsIndex().openCursor(envTxn); while (c.getNext()) { final int propId = IntegerBinding.compressedEntryToInt(c.getKey()); final long localId = LongBinding.compressedEntryToLong(c.getValue()); final Set<Long> localIds = allPropsMap.get(propId); if (localIds == null || !localIds.remove(localId)) { phantomIds.add(new Pair<>(propId, localId)); } else { if (localIds.isEmpty()) { allPropsMap.remove(propId); } } } c.close(); if (!allPropsMap.isEmpty()) { final int[] added = { 0 }; store.executeInTransaction(new StoreTransactionalExecutable() { @Override public void execute(@NotNull final StoreTransaction txn) { int count = 0; final Store allPropsIndex = propTable.getAllPropsIndex(); final Transaction envTxn = ((PersistentStoreTransaction) txn) .getEnvironmentTransaction(); for (Map.Entry<Integer, Set<Long>> entry : allPropsMap.entrySet()) { final ArrayByteIterable keyEntry = IntegerBinding .intToCompressedEntry(entry.getKey()); for (long localId : entry.getValue()) { allPropsIndex.put(envTxn, keyEntry, LongBinding.longToCompressedEntry(localId)); ++count; } } added[0] = count; } }); if (log.isInfoEnabled()) { log.info(added[0] + " missing id pairs found and fixed for [" + entityType + ']'); } } if (!phantomIds.isEmpty()) { store.executeInTransaction(new StoreTransactionalExecutable() { @Override public void execute(@NotNull final StoreTransaction txn) { final Store allPropsIndex = propTable.getAllPropsIndex(); final Transaction envTxn = ((PersistentStoreTransaction) txn) .getEnvironmentTransaction(); final Cursor c = allPropsIndex.openCursor(envTxn); for (final Pair<Integer, Long> phantom : phantomIds) { if (!c.getSearchBoth( IntegerBinding.intToCompressedEntry(phantom.getFirst()), LongBinding.longToCompressedEntry(phantom.getSecond()))) { throw new EntityStoreException("Can't be"); } c.deleteCurrent(); } c.close(); } }); if (log.isInfoEnabled()) { log.info(phantomIds.size() + " phantom id pairs found and fixed for [" + entityType + ']'); } } } catch (Throwable t) { log.error("Failed to execute refactoring for entity type: " + entityType, t); throwJVMError(t); } } } }); }
From source file:org.eclipse.gyrex.admin.ui.http.internal.EditApplicationDialog.java
@Override protected Control createDialogArea(final Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); final GridData gd = (GridData) composite.getLayoutData(); gd.minimumHeight = convertVerticalDLUsToPixels(200); gd.minimumWidth = convertHorizontalDLUsToPixels(400); idField.setLabelText("Id"); contextPathField.setLabelText("Context"); providerField.setLabelText("Provider"); final IDialogFieldListener validateListener = new IDialogFieldListener() { @Override//from ww w . ja v a2 s .c o m public void dialogFieldChanged(final DialogField field) { validate(); } }; idField.setDialogFieldListener(validateListener); contextPathField.setDialogFieldListener(validateListener); providerField.setDialogFieldListener(validateListener); providerItemToIdMap.clear(); final TreeSet<String> providerItems = new TreeSet<String>(); final Collection<ApplicationProviderRegistration> providers = HttpActivator.getInstance() .getProviderRegistry().getRegisteredProviders().values(); for (final ApplicationProviderRegistration registration : providers) { final String label = HttpUiAdapter.getLabel(registration); providerItemToIdMap.put(label, registration.getProviderId()); providerItems.add(label); } providerField.setItems(providerItems.toArray(new String[providerItems.size()])); contextPathField.setContentProposalProcessor(new IContentProposalProvider() { /** serialVersionUID */ private static final long serialVersionUID = 1L; @Override public IContentProposal[] getProposals(final String contents, final int position) { final List<IContentProposal> resultList = new ArrayList<IContentProposal>(); final String patternString = StringUtils.trimToNull(StringUtils.substring(contents, 0, position)); final Collection<ContextDefinition> contexts = ContextActivator.getInstance() .getContextRegistryImpl().getDefinedContexts(); for (final ContextDefinition contextDefinition : contexts) { if ((null == patternString) || StringUtils.contains(contextDefinition.getPath().toString(), patternString)) { resultList.add(new ContentProposal(contextDefinition.getPath().toString(), contextDefinition.toString())); } } return resultList.toArray(new IContentProposal[resultList.size()]); } }); propertiesField.setLabelText("Properties"); mountsField.setLabelText("Mounts"); final Text warning = new Text(composite, SWT.WRAP | SWT.READ_ONLY); warning.setText( "Warning: this dialog is ugly. Please help us improve the UI. Any mockups and/or patches are very much appreciated!"); warning.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); LayoutUtil.doDefaultLayout(composite, new DialogField[] { new Separator(), idField, providerField, contextPathField, new Separator(), propertiesField, mountsField }, false); LayoutUtil.setHorizontalGrabbing(idField.getTextControl(null)); LayoutUtil.setHorizontalGrabbing(providerField.getComboControl(null)); LayoutUtil.setHorizontalGrabbing(contextPathField.getTextControl(null)); LayoutUtil.setHorizontalGrabbing(propertiesField.getListControl(null)); LayoutUtil.setHorizontalGrabbing(mountsField.getListControl(null)); if (null != applicationRegistration) { idField.setText(applicationRegistration.getApplicationId()); idField.setEnabled(false); contextPathField.setText(applicationRegistration.getContext().getContextPath().toString()); contextPathField.setEnabled(false); for (final Entry<String, String> e : providerItemToIdMap.entrySet()) { if (e.getValue().equals(applicationRegistration.getProviderId())) { providerField.selectItem(e.getKey()); } } providerField.setEnabled(false); applicationProperties.putAll(applicationRegistration.getInitProperties()); mountsField.setElements(applicationManager.getMounts(applicationRegistration.getApplicationId())); } refreshProperties(); final GridLayout masterLayout = (GridLayout) composite.getLayout(); masterLayout.marginWidth = 5; masterLayout.marginHeight = 5; LayoutUtil.setHorizontalSpan(warning, masterLayout.numColumns); return composite; }
From source file:edu.umass.cs.msocket.proxy.console.ConsoleModule.java
/** * Loads the commands for this module/*ww w . j ava 2 s . com*/ */ protected void loadCompletor() { List completors = new LinkedList(); int size = commands.size(); if (size > 0) { TreeSet set = new TreeSet(); Iterator it = commands.iterator(); while (it.hasNext()) { set.add(((ConsoleCommand) it.next()).getCommandName()); } completors.add(new SimpleCompletor((String[]) set.toArray(new String[size]))); } completors.add(new FileNameCompletor()); Completor[] completorsArray = (Completor[]) completors.toArray(new Completor[completors.size()]); consoleCompletor = new ArgumentCompletor(completorsArray, new CommandDelimiter()); }
From source file:com.autentia.intra.jsf.schedule.renderer.BitacoreScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer) throws IOException { final String clientId = schedule.getClientId(context); FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }//from ww w .j a v a 2s . c o m EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth)); String entryBorderColor = getEntryRenderer(schedule).getColor(context, schedule, wrapper.entry, selected); if (entryBorderColor != null) { entryStyle.append(" border-color: "); entryStyle.append(entryBorderColor); entryStyle.append(";"); } if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { writer.writeAttribute("href", "#", null); writer.writeAttribute(HTML.ONMOUSEUP_ATTR, "fireEntrySelected('" + formId + "', '" + clientId + "', '" + wrapper.entry.getId() + "');", null); } writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:com.autentia.tnt.jsf.schedule.renderer.BitacoreScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer) throws IOException { final String clientId = schedule.getClientId(context); FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }// ww w . j ava 2 s . com EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = (float) 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth)); String entryBorderColor = getEntryRenderer(schedule).getColor(context, schedule, wrapper.entry, selected); if (entryBorderColor != null) { entryStyle.append(" border-color: "); entryStyle.append(entryBorderColor); entryStyle.append(";"); } if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { writer.writeAttribute("href", "#", null); writer.writeAttribute(HTML.ONMOUSEUP_ATTR, "fireEntrySelected('" + formId + "', '" + clientId + "', '" + wrapper.entry.getId() + "');", null); } writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:org.wso2.carbon.mdm.api.User.java
/** * Update user in user store/*from www . j av a 2 s . c o m*/ * * @param userWrapper Wrapper object representing input json payload * @return {Response} Status of the request wrapped inside Response object * @throws MDMAPIException */ @PUT @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) throws MDMAPIException { UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); ResponsePayload responsePayload = new ResponsePayload(); try { if (userStoreManager.isExistingUser(userWrapper.getUsername())) { Map<String, String> defaultUserClaims = buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(), userWrapper.getEmailAddress()); if (StringUtils.isNotEmpty(userWrapper.getPassword())) { // Decoding Base64 encoded password byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword()); userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(), new String(decodedBytes, "UTF-8")); log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed"); } List<String> listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername()); final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]); /* Use the Set theory to find the roles to delete and roles to add The difference of roles in existingRolesSet and newRolesSet needed to be deleted new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet */ final TreeSet<String> existingRolesSet = new TreeSet<>(); Collections.addAll(existingRolesSet, existingRoles); final TreeSet<String> newRolesSet = new TreeSet<>(); Collections.addAll(newRolesSet, userWrapper.getRoles()); existingRolesSet.removeAll(newRolesSet); // Now we have the roles to delete String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]); List<String> roles = new ArrayList<>(Arrays.asList(rolesToDelete)); roles.remove(ROLE_EVERYONE); rolesToDelete = new String[0]; // Clearing and re-initializing the set existingRolesSet.clear(); Collections.addAll(existingRolesSet, existingRoles); newRolesSet.removeAll(existingRolesSet); // Now we have the roles to add String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]); userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd); userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null); // Outputting debug message upon successful addition of user if (log.isDebugEnabled()) { log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated."); } // returning response with success state responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer( "User by username: " + userWrapper.getUsername() + " was successfully updated."); return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); } else { if (log.isDebugEnabled()) { log.debug("User by username: " + userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); } // returning response with bad request state responsePayload.setStatusCode(HttpStatus.SC_CONFLICT); responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() + " doesn't exists. Therefore, request made to update user was refused."); return Response.status(HttpStatus.SC_CONFLICT).entity(responsePayload).build(); } } catch (UserStoreException | UnsupportedEncodingException e) { String msg = "Exception in trying to update user by username: " + userWrapper.getUsername(); log.error(msg, e); throw new MDMAPIException(msg, e); } }
From source file:com.idega.block.cal.renderer.ScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer, int index) throws IOException { //final String clientId = schedule.getClientId(context); //FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); //String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }/* www .ja va2s .com*/ EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth, index)); if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { DateFormat format; String pattern = null; if ((pattern != null) && (pattern.length() > 0)) { format = new SimpleDateFormat(pattern); } else { if (context.getApplication().getDefaultLocale() != null) { format = DateFormat.getDateInstance(DateFormat.MEDIUM, context.getApplication().getDefaultLocale()); } else { format = DateFormat.getDateInstance(DateFormat.MEDIUM); } } String startTime = format.format(wrapper.entry.getStartTime()); startTime += " "; startTime += wrapper.entry.getStartTime().getHours(); startTime += ":"; if (wrapper.entry.getStartTime().getMinutes() < 10) { startTime += "0"; startTime += wrapper.entry.getStartTime().getMinutes(); } else { startTime += wrapper.entry.getStartTime().getMinutes(); } String endTime = ""; endTime += wrapper.entry.getEndTime().getHours(); endTime += ":"; if (wrapper.entry.getEndTime().getMinutes() < 10) { endTime += "0"; endTime += wrapper.entry.getEndTime().getMinutes(); } else { endTime += wrapper.entry.getEndTime().getMinutes(); } writer.writeAttribute(HTML.HREF_ATTR, "javascript:void(0)", null); writer.writeAttribute("entryid", wrapper.entry.getId(), null); } if (schedule.getModel().size() == 1) { writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); } else { writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "workweekEntry"), null); } writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:org.apache.myfaces.custom.schedule.ScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer) throws IOException { final String clientId = schedule.getClientId(context); FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }/*from w w w . j a v a2s. c om*/ EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth)); String entryBorderColor = getEntryRenderer(schedule).getColor(context, schedule, wrapper.entry, selected); if (entryBorderColor != null) { entryStyle.append(" border-color: "); entryStyle.append(entryBorderColor); entryStyle.append(";"); } if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the tooltip if (schedule.isTooltip()) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (schedule.isTooltip()) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { writer.writeAttribute(HTML.HREF_ATTR, "#", null); writer.writeAttribute(HTML.ONCLICK_ATTR, "fireEntrySelected('" + formId + "', '" + clientId + "', '" + wrapper.entry.getId() + "');", null); } writer.writeAttribute(HTML.CLASS_ATTR, getEntryRenderer(schedule).getEntryClass(schedule, wrapper.entry), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM); } } }