Java Code Examples for java.util.SortedMap#size()

The following examples show how to use java.util.SortedMap#size() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImmutableDescriptor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Construct a descriptor where the names and values of the fields
 * are the keys and values of the given Map.</p>
 *
 * @throws IllegalArgumentException if the parameter is null, or
 * if a field name is null or empty, or if the same field name appears
 * more than once (which can happen because field names are not case
 * sensitive).
 */
public ImmutableDescriptor(Map<String, ?> fields) {
    if (fields == null)
        throw new IllegalArgumentException("Null Map");
    SortedMap<String, Object> map =
            new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
    for (Map.Entry<String, ?> entry : fields.entrySet()) {
        String name = entry.getKey();
        if (name == null || name.equals(""))
            throw new IllegalArgumentException("Empty or null field name");
        if (map.containsKey(name))
            throw new IllegalArgumentException("Duplicate name: " + name);
        map.put(name, entry.getValue());
    }
    int size = map.size();
    this.names = map.keySet().toArray(new String[size]);
    this.values = map.values().toArray(new Object[size]);
}
 
Example 2
Source File: ImmutableDescriptor.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Construct a descriptor where the names and values of the fields
 * are the keys and values of the given Map.</p>
 *
 * @throws IllegalArgumentException if the parameter is null, or
 * if a field name is null or empty, or if the same field name appears
 * more than once (which can happen because field names are not case
 * sensitive).
 */
public ImmutableDescriptor(Map<String, ?> fields) {
    if (fields == null)
        throw new IllegalArgumentException("Null Map");
    SortedMap<String, Object> map =
            new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
    for (Map.Entry<String, ?> entry : fields.entrySet()) {
        String name = entry.getKey();
        if (name == null || name.equals(""))
            throw new IllegalArgumentException("Empty or null field name");
        if (map.containsKey(name))
            throw new IllegalArgumentException("Duplicate name: " + name);
        map.put(name, entry.getValue());
    }
    int size = map.size();
    this.names = map.keySet().toArray(new String[size]);
    this.values = map.values().toArray(new Object[size]);
}
 
Example 3
Source File: TransactionSpout.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private void removeSuccessBatch(long successBatchId) {
    SortedMap<Long, Pair<Integer, Long>> obsoleteBatches = committingBatches.headMap(successBatchId);
    if (obsoleteBatches.size() > 0) {
        LOG.info("Obsolete batchIds are {}, successBatchId is {}", obsoleteBatches, successBatchId);
        for (Long batchId : obsoleteBatches.keySet()) {
            committingBatches.remove(batchId);
        }
    }

    Pair<Integer, Long> commitBatchInfo = committingBatches.remove(successBatchId);
    if (commitBatchInfo == null) {
        LOG.warn("Batch-{} has already been removed", successBatchId);
    } else {
        if (commitBatchInfo.getFirst() > 0)
            taskStats.spoutProcessLatency("", commitBatchInfo.getSecond(), System.currentTimeMillis(), commitBatchInfo.getFirst());
    }
    updateMaxPendingFlag();
}
 
Example 4
Source File: MaildirMessageMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private List<MailboxMessage> findMessagesInMailbox(Mailbox mailbox, FilenameFilter filter, int limit)
        throws MailboxException {
    MaildirFolder folder = maildirStore.createMaildirFolder(mailbox);
    try {
        SortedMap<MessageUid, MaildirMessageName> uidMap = folder.getUidMap(filter, limit);

        ArrayList<MailboxMessage> filtered = new ArrayList<>(uidMap.size());
        for (Entry<MessageUid, MaildirMessageName> entry : uidMap.entrySet()) {
            filtered.add(new MaildirMailboxMessage(mailbox, entry.getKey(), entry.getValue()));
        }
        return filtered;
    } catch (IOException e) {
        throw new MailboxException("Failure while search for Messages in Mailbox " + mailbox, e);
    }

}
 
Example 5
Source File: PowerManagementAction.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sets the page attributes.
 *
 * @param request the request
 * @param context the context
 * @param server the server
 * @param user the user
 * @param strutsDelegate the Struts delegate
 * @param errors ActionErrors that might have already been raised
 */
private void setAttributes(HttpServletRequest request, RequestContext context,
        Server server, User user, StrutsDelegate strutsDelegate, ActionErrors errors) {
    request.setAttribute(RequestContext.SID, server.getId());
    request.setAttribute(RequestContext.SYSTEM, server);

    SortedMap<String, String> types = setUpPowerTypes(request, strutsDelegate, errors);

    if (types.size() > 0) {
        SystemRecord record = getSystemRecord(user, server);

        if (record == null) {
            request.setAttribute(POWER_TYPE, types.get(types.firstKey()));
        }
        else {
            request.setAttribute(POWER_TYPE, record.getPowerType());
            request.setAttribute(POWER_ADDRESS, record.getPowerAddress());
            request.setAttribute(POWER_USERNAME, record.getPowerUsername());
            request.setAttribute(POWER_PASSWORD, record.getPowerPassword());
            request.setAttribute(POWER_ID, record.getPowerId());
        }
    }
}
 
Example 6
Source File: CompletionMinibuffer.java    From e4macs with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.minibuffer.WithMinibuffer#showCompletions()
 */
@Override
protected void showCompletions() {
	String name = getMBString();
	SortedMap<String, ?> compTree;
	if (isSearching() && getSearchStr().length() > 0) {
		compTree = getSearchResults();
	} else {
		compTree = getCompletions(name); 
	}
	if (compTree != null) {
		if (compTree.size() > 1) {
			if (getMiniDialog() == null) {
				setMiniDialog(new SelectionDialog(null, this, getEditor()));
			}
			((SelectionDialog) getMiniDialog()).open(compTree);
			setShowingCompletions(true);
		}
		EmacsPlusUtils.forceStatusUpdate(getEditor());
		showCompletionStatus(compTree,name);
	} else {
		updateStatusLine(name + NOMATCH_MSG);
	}
}
 
Example 7
Source File: MetaXMinibuffer.java    From e4macs with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see com.mulgasoft.emacsplus.minibuffer.ExecutingMinibuffer#executeResult(org.eclipse.ui.texteditor.ITextEditor, java.lang.Object)
 */
protected boolean executeResult(ITextEditor editor, Object command) {
	boolean result = true;
	closeDialog();
	CommandSupport commandControl = getCommandSupport();
	if (commandControl != null) {
		String commandS = (String) command;
		Command com = commandList.get(commandS);
		// Invoke completion on exit, if the string came through uncompleted
		if (completeOnExit && com == null) {
			try {
				SortedMap<String, Command> viewTree = commandControl
						.getCommandSubTree(commandList, commandS, false,
								isIgnoreDisabled());
				if (viewTree.size() == 1) {
					commandS = viewTree.firstKey();
					com = commandList.get(commandS);
				}
			} catch (Exception e) {
				// Could be a java.util.regex.PatternSyntaxException on weird input
				// when looking for a match; just ignore and command will abort
			}
		}
		if (com != null) {
			addToHistory(commandS); // add to command history
			setExecuting(true);
			setResultString(commandS);
			//				setResultMessage(commandS,false);
			try {
				setMxLaunch(true);
				result = exitExecuteResult(getEditor(), copyCommand(com,
						commandS));
			} finally {
				setMxLaunch(false);
			}
		}
	} 
	return result;
}
 
Example 8
Source File: UserTable.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * for attribute sortedMap serialization
 */
public static byte[] serializeSortedMap(SortedMap<String, String> value) {
  if (value==null) {
    return null;
  }
  KriptonJsonContext context=KriptonBinder.jsonBind();
  try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) {
    JsonGenerator jacksonSerializer=wrapper.jacksonGenerator;
    jacksonSerializer.writeStartObject();
    int fieldCount=0;
    if (value!=null)  {
      fieldCount++;
      // write wrapper tag
      if (value.size()>0) {
        jacksonSerializer.writeFieldName("element");
        jacksonSerializer.writeStartArray();
        for (Map.Entry<String, String> item: value.entrySet()) {
          jacksonSerializer.writeStartObject();
          jacksonSerializer.writeStringField("key", item.getKey());
          if (item.getValue()==null) {
            jacksonSerializer.writeNullField("value");
          } else {
            jacksonSerializer.writeStringField("value", item.getValue());
          }
          jacksonSerializer.writeEndObject();
        }
        jacksonSerializer.writeEndArray();
      } else {
        jacksonSerializer.writeNullField("element");
      }
    }
    jacksonSerializer.writeEndObject();
    jacksonSerializer.flush();
    return stream.toByteArray();
  } catch(Exception e) {
    e.printStackTrace();
    throw(new KriptonRuntimeException(e.getMessage()));
  }
}
 
Example 9
Source File: Sampler.java    From geowave with Apache License 2.0 5 votes vote down vote up
public void sample(
    final Iterable<CentroidPairing<T>> pairings,
    final SampleNotification<T> notification,
    final double normalizingConstant) {
  int putCounter = 0;

  final SortedMap<Double, T> reservoir = Maps.newTreeMap();
  for (final CentroidPairing<T> pairing : pairings) {
    final double weight = pairing.getDistance();
    if (weight > 0.0) {
      final double score =
          sampleProbabilityFn.getProbability(weight, normalizingConstant, sampleSize);
      // could add extra to make sure new point is far enough away
      // from the rest
      if (reservoir.size() < sampleSize) {
        reservoir.put(score, pairing.getPairedItem().getWrappedItem());
        putCounter++;
      } else if (score > reservoir.firstKey()) {
        reservoir.remove(reservoir.firstKey());
        reservoir.put(score, pairing.getPairedItem().getWrappedItem());
      }
      if (putCounter > putLimit) {
        // On the off-chance this gets huge, cleanup
        // Can occur if sampleSize > PUT_LIMIT
        notifyAll(notification, reservoir.values(), true);
        reservoir.clear();
        putCounter = 0;
      }
    }
  }
  notifyAll(notification, reservoir.values(), false);
}
 
Example 10
Source File: DefaultMXBeanMappingFactory.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private MXBeanMapping makeCompositeMapping(Class<?> c,
                                           MXBeanMappingFactory factory)
        throws OpenDataException {

    // For historical reasons GcInfo implements CompositeData but we
    // shouldn't count its CompositeData.getCompositeType() field as
    // an item in the computed CompositeType.
    final boolean gcInfoHack =
        (c.getName().equals("com.sun.management.GcInfo") &&
            c.getClassLoader() == null);

    ReflectUtil.checkPackageAccess(c);
    final List<Method> methods =
            MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
    final SortedMap<String,Method> getterMap = newSortedMap();

    /* Select public methods that look like "T getX()" or "boolean
       isX()", where T is not void and X is not the empty
       string.  Exclude "Class getClass()" inherited from Object.  */
    for (Method method : methods) {
        final String propertyName = propertyName(method);

        if (propertyName == null)
            continue;
        if (gcInfoHack && propertyName.equals("CompositeType"))
            continue;

        Method old =
            getterMap.put(decapitalize(propertyName),
                        method);
        if (old != null) {
            final String msg =
                "Class " + c.getName() + " has method name clash: " +
                old.getName() + ", " + method.getName();
            throw new OpenDataException(msg);
        }
    }

    final int nitems = getterMap.size();

    if (nitems == 0) {
        throw new OpenDataException("Can't map " + c.getName() +
                                    " to an open data type");
    }

    final Method[] getters = new Method[nitems];
    final String[] itemNames = new String[nitems];
    final OpenType<?>[] openTypes = new OpenType<?>[nitems];
    int i = 0;
    for (Map.Entry<String,Method> entry : getterMap.entrySet()) {
        itemNames[i] = entry.getKey();
        final Method getter = entry.getValue();
        getters[i] = getter;
        final Type retType = getter.getGenericReturnType();
        openTypes[i] = factory.mappingForType(retType, factory).getOpenType();
        i++;
    }

    CompositeType compositeType =
        new CompositeType(c.getName(),
                          c.getName(),
                          itemNames, // field names
                          itemNames, // field descriptions
                          openTypes);

    return new CompositeMapping(c,
                                compositeType,
                                itemNames,
                                getters,
                                factory);
}
 
Example 11
Source File: XlsSchemaParser.java    From data-prep with Apache License 2.0 4 votes vote down vote up
/**
 * Return the columns metadata for the given sheet.
 *
 * @param sheet the sheet to look at.
 * @param datasetId the dataset id.
 * @return the columns metadata for the given sheet.
 */
private List<ColumnMetadata> parsePerSheet(Sheet sheet, String datasetId, FormulaEvaluator formulaEvaluator) {

    LOGGER.debug(Markers.dataset(datasetId), "parsing sheet '{}'", sheet.getSheetName());

    // Map<ColId, Map<RowId, type>>
    SortedMap<Integer, SortedMap<Integer, String>> cellsTypeMatrix =
            collectSheetTypeMatrix(sheet, formulaEvaluator);
    int averageHeaderSize = guessHeaderSize(cellsTypeMatrix);

    // here we have information regarding types for each rows/col (yup a Matrix!! :-) )
    // so we can analyse and guess metadata (column type, header value)
    final List<ColumnMetadata> columnsMetadata = new ArrayList<>(cellsTypeMatrix.size());

    cellsTypeMatrix.forEach((colId, typePerRowMap) -> {

        Type type = guessColumnType(colId, typePerRowMap, averageHeaderSize);

        String headerText = null;
        if (averageHeaderSize == 1 && sheet.getRow(0) != null) {
            // so header value is the first row of the column
            Cell headerCell = sheet.getRow(0).getCell(colId);
            headerText = XlsUtils.getCellValueAsString(headerCell, formulaEvaluator);
        }

        // header text cannot be null so use a default one
        if (StringUtils.isEmpty(headerText)) {
            // +1 because it starts from 0
            headerText = message("import.local.generated_column_name", colId + 1);
        }

        // FIXME what do we do if header size is > 1 concat all lines?
        columnsMetadata.add(ColumnMetadata.Builder //
                .column() //
                .headerSize(averageHeaderSize) //
                .name(headerText) //
                .type(type) //
                .build());

    });

    return columnsMetadata;
}
 
Example 12
Source File: CobarSqlMapClientTemplate.java    From cobarclient with Apache License 2.0 4 votes vote down vote up
/**
 * We support insert in 3 ways here:<br>
 * 
 * <pre>
 *      1- if no partitioning requirement is found:
 *          the insert will be delegated to the default insert behavior of {@link SqlMapClientTemplate};
 *      2- if partitioning support is enabled and 'parameterObject' is NOT a type of collection:
 *          we will search for routing rules against it and execute insertion as per the rule if found, 
 *          if no rule is found, the default data source will be used.
 *      3- if partitioning support is enabled and 'parameterObject' is a type of {@link BatchInsertTask}:
 *           this is a specific solution, mainly aimed for "insert into ..values(), (), ()" style insertion.
 *           In this situation, we will regroup the entities in the original collection into several sub-collections as per routing rules, 
 *           and submit the regrouped sub-collections to their corresponding target data sources.
 *           One thing to NOTE: in this situation, although we return a object as the result of insert, but it doesn't mean any thing to you, 
 *           because, "insert into ..values(), (), ()" style SQL doesn't return you a sensible primary key in this way. 
 *           this, function is optional, although we return a list of sub-insert result, but don't guarantee precise semantics.
 * </pre>
 * 
 * we can't just decide the execution branch on the Collection<?> type of
 * the 'parameterObject', because sometimes, maybe the application does want
 * to do insertion as per the parameterObject of its own.<br>
 */
@Override
public Object insert(final String statementName, final Object parameterObject)
        throws DataAccessException {
    auditSqlIfNecessary(statementName, parameterObject);
    long startTimestamp = System.currentTimeMillis();
    try {
        if (isPartitioningBehaviorEnabled()) {
            /**
             * sometimes, client will submit batch insert request like
             * "insert into ..values(), (), ()...", it's a rare situation,
             * but does exist, so we will create new executor on this kind
             * of request processing, and map each values to their target
             * data source and then reduce to sub-collection, finally,
             * submit each sub-collection of entities to executor to
             * execute.
             */
            if (parameterObject != null && parameterObject instanceof BatchInsertTask) {
                // map collection into mapping of data source and sub collection of entities
                logger.info(
                        "start to prepare batch insert operation with parameter type of:{}.",
                        parameterObject.getClass());

                return batchInsertAfterReordering(statementName, parameterObject);

            } else {
                DataSource targetDataSource = null;
                SqlMapClientCallback action = new SqlMapClientCallback() {
                    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                        return executor.insert(statementName, parameterObject);
                    }
                };
                SortedMap<String, DataSource> resultDataSources = lookupDataSourcesByRouter(
                        statementName, parameterObject);
                if (MapUtils.isEmpty(resultDataSources) || resultDataSources.size() == 1) {
                    targetDataSource = getSqlMapClient().getDataSource(); // fall back to default data source.
                    if (resultDataSources.size() == 1) {
                        targetDataSource = resultDataSources.values().iterator().next();
                    }
                    return executeWith(targetDataSource, action);
                } else {
                    return executeInConcurrency(action, resultDataSources);
                }
            }

        } // end if for partitioning status checking
        return super.insert(statementName, parameterObject);
    } finally {
        if (isProfileLongTimeRunningSql()) {
            long interval = System.currentTimeMillis() - startTimestamp;
            if (interval > getLongTimeRunningSqlIntervalThreshold()) {
                logger
                        .warn(
                                "SQL Statement [{}] with parameter object [{}] ran out of the normal time range, it consumed [{}] milliseconds.",
                                new Object[] { statementName, parameterObject, interval });
            }
        }
    }
}
 
Example 13
Source File: MetaXMinibuffer.java    From e4macs with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Expose the command completion dialog
 */
protected void showCompletions() {
	
	CommandSupport commandControl = getCommandSupport();
	if (commandControl != null) {
		String command = getMBString();
		SortedMap<String, Command> viewTree;
		if (isSearching() && getSearchStr().length() > 0) {
			@SuppressWarnings("unchecked")	// need local variable for unchecked annotation 
			SortedMap<String, Command> tmpTree = (SortedMap<String,Command>)getSearchResults();
			viewTree = tmpTree;
		} else {
			viewTree = commandControl.getCommandSubTree(commandList, command, false, isIgnoreDisabled());
		}
		if (viewTree != null) {
			if (viewTree.size() > 1) {
				if (getMiniDialog() == null) {
					setMiniDialog(new MetaXDialog(null, this, getEditor()));
				}
				((MetaXDialog) getMiniDialog()).open(viewTree);
				setShowingCompletions(true);
			}
			EmacsPlusUtils.forceStatusUpdate(getEditor());
			String newCommand;
			if (viewTree.size() == 0) {
				updateStatusLine((isSearching() ? EMPTY_STR : command) + NOMATCH_MSG);
			} else if (viewTree.size() == 1) {
				closeDialog();
				newCommand = viewTree.firstKey();
				if (!command.equals(newCommand) && !isSearching()) {
					initMinibuffer(newCommand);
				}
				updateStatusLine(newCommand + COMPLETE_MSG);
			} else if (!isSearching()) {
				if (command.length() > 0) {
					newCommand = commandControl.getCommonString(viewTree, command);
					if (!command.equals(newCommand)) {
						initMinibuffer(newCommand);
					}
				}
				updateStatusLine(getMBString());
			}
		} else {
			updateStatusLine(command + NOMATCH_MSG);
		}
	}
}
 
Example 14
Source File: NodePropertyHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public Map<QName, Serializable> convertToPublicProperties(Map<NodePropertyKey, NodePropertyValue> propertyValues)
{
    Map<QName, Serializable> propertyMap = new HashMap<QName, Serializable>(propertyValues.size(), 1.0F);
    // Shortcut
    if (propertyValues.size() == 0)
    {
        return propertyMap;
    }
    // We need to process the properties in order
    SortedMap<NodePropertyKey, NodePropertyValue> sortedPropertyValues = new TreeMap<NodePropertyKey, NodePropertyValue>(
            propertyValues);
    // A working map. Ordering is important.
    SortedMap<NodePropertyKey, NodePropertyValue> scratch = new TreeMap<NodePropertyKey, NodePropertyValue>();
    // Iterate (sorted) over the map entries and extract values with the same qname
    Long currentQNameId = Long.MIN_VALUE;
    Iterator<Map.Entry<NodePropertyKey, NodePropertyValue>> iterator = sortedPropertyValues.entrySet().iterator();
    while (true)
    {
        Long nextQNameId = null;
        NodePropertyKey nextPropertyKey = null;
        NodePropertyValue nextPropertyValue = null;
        // Record the next entry's values
        if (iterator.hasNext())
        {
            Map.Entry<NodePropertyKey, NodePropertyValue> entry = iterator.next();
            nextPropertyKey = entry.getKey();
            nextPropertyValue = entry.getValue();
            nextQNameId = nextPropertyKey.getQnameId();
        }
        // If the QName is going to change, and we have some entries to process, then process them.
        if (scratch.size() > 0 && (nextQNameId == null || !nextQNameId.equals(currentQNameId)))
        {
            QName currentQName = qnameDAO.getQName(currentQNameId).getSecond();
            PropertyDefinition currentPropertyDef = dictionaryService.getProperty(currentQName);
            // We have added something to the scratch properties but the qname has just changed
            Serializable collapsedValue = null;
            // We can shortcut if there is only one value
            if (scratch.size() == 1)
            {
                // There is no need to collapse list indexes
                collapsedValue = collapsePropertiesWithSameQNameAndListIndex(currentPropertyDef, scratch);
            }
            else
            {
                // There is more than one value so the list indexes need to be collapsed
                collapsedValue = collapsePropertiesWithSameQName(currentPropertyDef, scratch);
            }
            boolean forceCollection = false;
            // If the property is multi-valued then the output property must be a collection
            if (currentPropertyDef != null && currentPropertyDef.isMultiValued())
            {
                forceCollection = true;
            }
            else if (scratch.size() == 1 && scratch.firstKey().getListIndex().intValue() > -1)
            {
                // This is to handle cases of collections where the property is d:any but not
                // declared as multiple.
                forceCollection = true;
            }
            if (forceCollection && collapsedValue != null && !(collapsedValue instanceof Collection<?>))
            {
                // Can't use Collections.singletonList: ETHREEOH-1172
                ArrayList<Serializable> collection = new ArrayList<Serializable>(1);
                collection.add(collapsedValue);
                collapsedValue = collection;
            }
            
            // Store the value
            propertyMap.put(currentQName, collapsedValue);
            // Reset
            scratch.clear();
        }
        if (nextQNameId != null)
        {
            // Add to the current entries
            scratch.put(nextPropertyKey, nextPropertyValue);
            currentQNameId = nextQNameId;
        }
        else
        {
            // There is no next value to process
            break;
        }
    }
    // Done
    return propertyMap;
}
 
Example 15
Source File: DefaultMXBeanMappingFactory.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private MXBeanMapping makeCompositeMapping(Class<?> c,
                                           MXBeanMappingFactory factory)
        throws OpenDataException {

    // For historical reasons GcInfo implements CompositeData but we
    // shouldn't count its CompositeData.getCompositeType() field as
    // an item in the computed CompositeType.
    final boolean gcInfoHack =
        (c.getName().equals("com.sun.management.GcInfo") &&
            c.getClassLoader() == null);

    ReflectUtil.checkPackageAccess(c);
    final List<Method> methods =
            MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
    final SortedMap<String,Method> getterMap = newSortedMap();

    /* Select public methods that look like "T getX()" or "boolean
       isX()", where T is not void and X is not the empty
       string.  Exclude "Class getClass()" inherited from Object.  */
    for (Method method : methods) {
        final String propertyName = propertyName(method);

        if (propertyName == null)
            continue;
        if (gcInfoHack && propertyName.equals("CompositeType"))
            continue;

        Method old =
            getterMap.put(decapitalize(propertyName),
                        method);
        if (old != null) {
            final String msg =
                "Class " + c.getName() + " has method name clash: " +
                old.getName() + ", " + method.getName();
            throw new OpenDataException(msg);
        }
    }

    final int nitems = getterMap.size();

    if (nitems == 0) {
        throw new OpenDataException("Can't map " + c.getName() +
                                    " to an open data type");
    }

    final Method[] getters = new Method[nitems];
    final String[] itemNames = new String[nitems];
    final OpenType<?>[] openTypes = new OpenType<?>[nitems];
    int i = 0;
    for (Map.Entry<String,Method> entry : getterMap.entrySet()) {
        itemNames[i] = entry.getKey();
        final Method getter = entry.getValue();
        getters[i] = getter;
        final Type retType = getter.getGenericReturnType();
        openTypes[i] = factory.mappingForType(retType, factory).getOpenType();
        i++;
    }

    CompositeType compositeType =
        new CompositeType(c.getName(),
                          c.getName(),
                          itemNames, // field names
                          itemNames, // field descriptions
                          openTypes);

    return new CompositeMapping(c,
                                compositeType,
                                itemNames,
                                getters,
                                factory);
}
 
Example 16
Source File: CobarSqlMapClientTemplate.java    From cobarclient with Apache License 2.0 4 votes vote down vote up
@Override
public int delete(final String statementName, final Object parameterObject)
        throws DataAccessException {
    auditSqlIfNecessary(statementName, parameterObject);

    long startTimestamp = System.currentTimeMillis();
    try {
        if (isPartitioningBehaviorEnabled()) {
            SortedMap<String, DataSource> dsMap = lookupDataSourcesByRouter(statementName,
                    parameterObject);
            if (!MapUtils.isEmpty(dsMap)) {

                SqlMapClientCallback action = new SqlMapClientCallback() {
                    public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
                        return executor.delete(statementName, parameterObject);
                    }
                };

                if (dsMap.size() == 1) {
                    DataSource dataSource = dsMap.get(dsMap.firstKey());
                    return (Integer) executeWith(dataSource, action);
                } else {
                    List<Object> results = executeInConcurrency(action, dsMap);
                    Integer rowAffacted = 0;
                    for (Object item : results) {
                        rowAffacted += (Integer) item;
                    }
                    return rowAffacted;
                }
            }
        } // end if for partitioning status checking
        return super.delete(statementName, parameterObject);
    } finally {
        if (isProfileLongTimeRunningSql()) {
            long interval = System.currentTimeMillis() - startTimestamp;
            if (interval > getLongTimeRunningSqlIntervalThreshold()) {
                logger
                        .warn(
                                "SQL Statement [{}] with parameter object [{}] ran out of the normal time range, it consumed [{}] milliseconds.",
                                new Object[] { statementName, parameterObject, interval });
            }
        }
    }
}
 
Example 17
Source File: IndexDefinition.java    From Eagle with Apache License 2.0 4 votes vote down vote up
private byte[] generateUniqueIndexRowkey(byte[][] indexValues, int[] partitionHashCodes, SortedMap<Integer, Integer> tagMap) {
	final int prefixHashCode = indexPrefix.hashCode();
	int totalLength = 4;
	totalLength += (partitionHashCodes != null) ? (4 * partitionHashCodes.length) : 0;
	
	totalLength += (2 * indexValues.length);
	for (int i = 0; i < indexValues.length; ++i) {
		final byte[] value = indexValues[i];
		totalLength += value.length;
	}
	if (tagMap != null && (!tagMap.isEmpty())) {
		totalLength += tagMap.size() * 8;
	}
	
	int offset = 0;
	final byte[] rowkey = new byte[totalLength];
	
	// 1. set prefix
	ByteUtil.intToBytes(prefixHashCode, rowkey, offset);
	offset += 4;
	
	// 2. set partition
	if (partitionHashCodes != null) {
		for (Integer partitionHashCode : partitionHashCodes) {
			ByteUtil.intToBytes(partitionHashCode, rowkey, offset);
			offset += 4;
		}
	}
	
	// 3. set index values
	for (int i = 0; i < columns.length; ++i) {
		ByteUtil.shortToBytes((short)indexValues[i].length, rowkey, offset);
		offset += 2;
		for (int j = 0; j < indexValues[i].length; ++j) {
			rowkey[offset++] = indexValues[i][j];
		}
	}
	
	// Check if it's non clustered index, then set the tag/value hash code
	if (tagMap != null && (!tagMap.isEmpty())) {
		// 4. set tag key/value hashes
		for (Map.Entry<Integer, Integer> entry : tagMap.entrySet()) {
			ByteUtil.intToBytes(entry.getKey(), rowkey, offset);
			offset += 4;
			ByteUtil.intToBytes(entry.getValue(), rowkey, offset);
			offset += 4;
		}
	}
	
	return rowkey;
}
 
Example 18
Source File: DefaultMXBeanMappingFactory.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
private MXBeanMapping makeCompositeMapping(Class<?> c,
                                           MXBeanMappingFactory factory)
        throws OpenDataException {

    // For historical reasons GcInfo implements CompositeData but we
    // shouldn't count its CompositeData.getCompositeType() field as
    // an item in the computed CompositeType.
    final boolean gcInfoHack =
        (c.getName().equals("com.sun.management.GcInfo") &&
            c.getClassLoader() == null);

    ReflectUtil.checkPackageAccess(c);
    final List<Method> methods =
            MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
    final SortedMap<String,Method> getterMap = newSortedMap();

    /* Select public methods that look like "T getX()" or "boolean
       isX()", where T is not void and X is not the empty
       string.  Exclude "Class getClass()" inherited from Object.  */
    for (Method method : methods) {
        final String propertyName = propertyName(method);

        if (propertyName == null)
            continue;
        if (gcInfoHack && propertyName.equals("CompositeType"))
            continue;

        Method old =
            getterMap.put(decapitalize(propertyName),
                        method);
        if (old != null) {
            final String msg =
                "Class " + c.getName() + " has method name clash: " +
                old.getName() + ", " + method.getName();
            throw new OpenDataException(msg);
        }
    }

    final int nitems = getterMap.size();

    if (nitems == 0) {
        throw new OpenDataException("Can't map " + c.getName() +
                                    " to an open data type");
    }

    final Method[] getters = new Method[nitems];
    final String[] itemNames = new String[nitems];
    final OpenType<?>[] openTypes = new OpenType<?>[nitems];
    int i = 0;
    for (Map.Entry<String,Method> entry : getterMap.entrySet()) {
        itemNames[i] = entry.getKey();
        final Method getter = entry.getValue();
        getters[i] = getter;
        final Type retType = getter.getGenericReturnType();
        openTypes[i] = factory.mappingForType(retType, factory).getOpenType();
        i++;
    }

    CompositeType compositeType =
        new CompositeType(c.getName(),
                          c.getName(),
                          itemNames, // field names
                          itemNames, // field descriptions
                          openTypes);

    return new CompositeMapping(c,
                                compositeType,
                                itemNames,
                                getters,
                                factory);
}
 
Example 19
Source File: DefaultMXBeanMappingFactory.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private MXBeanMapping makeCompositeMapping(Class<?> c,
                                           MXBeanMappingFactory factory)
        throws OpenDataException {

    // For historical reasons GcInfo implements CompositeData but we
    // shouldn't count its CompositeData.getCompositeType() field as
    // an item in the computed CompositeType.
    final boolean gcInfoHack =
        (c.getName().equals("com.sun.management.GcInfo") &&
            c.getClassLoader() == null);

    ReflectUtil.checkPackageAccess(c);
    final List<Method> methods =
            MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
    final SortedMap<String,Method> getterMap = newSortedMap();

    /* Select public methods that look like "T getX()" or "boolean
       isX()", where T is not void and X is not the empty
       string.  Exclude "Class getClass()" inherited from Object.  */
    for (Method method : methods) {
        final String propertyName = propertyName(method);

        if (propertyName == null)
            continue;
        if (gcInfoHack && propertyName.equals("CompositeType"))
            continue;

        Method old =
            getterMap.put(decapitalize(propertyName),
                        method);
        if (old != null) {
            final String msg =
                "Class " + c.getName() + " has method name clash: " +
                old.getName() + ", " + method.getName();
            throw new OpenDataException(msg);
        }
    }

    final int nitems = getterMap.size();

    if (nitems == 0) {
        throw new OpenDataException("Can't map " + c.getName() +
                                    " to an open data type");
    }

    final Method[] getters = new Method[nitems];
    final String[] itemNames = new String[nitems];
    final OpenType<?>[] openTypes = new OpenType<?>[nitems];
    int i = 0;
    for (Map.Entry<String,Method> entry : getterMap.entrySet()) {
        itemNames[i] = entry.getKey();
        final Method getter = entry.getValue();
        getters[i] = getter;
        final Type retType = getter.getGenericReturnType();
        openTypes[i] = factory.mappingForType(retType, factory).getOpenType();
        i++;
    }

    CompositeType compositeType =
        new CompositeType(c.getName(),
                          c.getName(),
                          itemNames, // field names
                          itemNames, // field descriptions
                          openTypes);

    return new CompositeMapping(c,
                                compositeType,
                                itemNames,
                                getters,
                                factory);
}
 
Example 20
Source File: ExprPolynomial.java    From symja_android_library with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Constructor for GenPolynomial.
 * 
 * @param r
 *            polynomial ring factory.
 * @param v
 *            the SortedMap of some other polynomial.
 */
protected ExprPolynomial(ExprPolynomialRing r, SortedMap<ExpVectorLong, IExpr> v) {
	this(r);
	if (v.size() > 0) {
		// ExprPolynomialRing.creations++;
		val.putAll(v); // assume no zero coefficients and val is empty
	}
}