Java Code Examples for java.util.Arrays

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project ACLS-protocol-library, under directory /aclslib/src/main/java/au/edu/uq/cmm/aclslib/dummy/.

Source file: RequestProcessor.java

  43 
vote

private void processLoginRequest(Request m,BufferedWriter w) throws AclsException {
  LoginRequest login=(LoginRequest)m;
  String timestamp=DateFormat.getInstance().format(new Date());
  List<String> accounts=Arrays.asList("general","special");
  Response r;
  if (!login.getPassword().equals("secret")) {
    r=new RefusedResponse(ResponseType.VIRTUAL_LOGIN_REFUSED);
  }
 else   if (login.getUserName().equals("junior")) {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.NONE,true);
  }
 else   if (login.getUserName().equals("badboy")) {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.NONE,false);
  }
 else {
    r=new LoginResponse(ResponseType.VIRTUAL_LOGIN_ALLOWED,login.getUserName(),"CMMMM",timestamp,accounts,Certification.VALID,false);
  }
  sendResponse(w,r);
}
 

Example 2

From project action-core, under directory /src/main/java/com/ning/metrics/action/hdfs/data/parser/.

Source file: StringRowSerializer.java

  31 
vote

@Override public Rows toRows(final Registrar r,final Object value) throws RowAccessException {
  final String[] data=value.toString().split("\t");
  final List<ColumnKey> columnKeyList=new ArrayList<ColumnKey>();
  for (int i=0; i < data.length; i++) {
    columnKeyList.add(new DynamicColumnKey(String.valueOf("col-" + i)));
  }
  final Row row=RowFactory.getRow(new RowSchema("Text",columnKeyList),Arrays.asList(data));
  final Rows rows=new Rows();
  rows.add(row);
  return rows;
}
 

Example 3

From project ActionBarSherlock, under directory /library/src/com/actionbarsherlock/internal/nineoldandroids/animation/.

Source file: KeyframeSet.java

  31 
vote

public KeyframeSet(Keyframe... keyframes){
  mNumKeyframes=keyframes.length;
  mKeyframes=new ArrayList<Keyframe>();
  mKeyframes.addAll(Arrays.asList(keyframes));
  mFirstKeyframe=mKeyframes.get(0);
  mLastKeyframe=mKeyframes.get(mNumKeyframes - 1);
  mInterpolator=mLastKeyframe.getInterpolator();
}
 

Example 4

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: LogFilter.java

  31 
vote

static void logQuery(Logger logger,String query,Object[] params,long queryStartTime){
  long time=System.currentTimeMillis() - queryStartTime;
  if (Registry.instance().getConfiguration().collectStatistics()) {
    Registry.instance().getStatisticsQueue().enqueue(new QueryExecutionEvent(query,time));
  }
  StringBuffer log=new StringBuffer("Query: \"").append(query).append("\"");
  if (params != null && params.length != 0)   log.append(", with parameters: ").append("<").append(Util.join(Arrays.asList(params),">, <")).append(">");
  log(logger,log.append(", took: ").append(time).append(" milliseconds").toString());
}
 

Example 5

From project activemq-apollo, under directory /apollo-dto/src/main/java/org/apache/activemq/apollo/dto/.

Source file: ApolloTypeIdResolver.java

  31 
vote

public void init(JavaType baseType){
  this.baseType=baseType;
  ArrayList<Class<?>> classes=new ArrayList<Class<?>>();
  classes.add(baseType.getRawClass());
  classes.addAll(Arrays.asList(DtoModule$.MODULE$.extension_classes()));
  for (  Class<?> c : classes) {
    if (baseType.getRawClass().isAssignableFrom(c)) {
      JsonTypeName jsonAnnoation=c.getAnnotation(JsonTypeName.class);
      if (jsonAnnoation != null && jsonAnnoation.value() != null) {
        typeToId.put(c,jsonAnnoation.value());
        idToType.put(jsonAnnoation.value(),TypeFactory.specialize(baseType,c));
        idToType.put(c.getName(),TypeFactory.specialize(baseType,c));
      }
 else {
        XmlRootElement xmlAnnoation=c.getAnnotation(XmlRootElement.class);
        if (xmlAnnoation != null && xmlAnnoation.name() != null) {
          typeToId.put(c,xmlAnnoation.name());
          idToType.put(xmlAnnoation.name(),TypeFactory.specialize(baseType,c));
          idToType.put(c.getName(),TypeFactory.specialize(baseType,c));
        }
      }
    }
  }
}
 

Example 6

From project activiti, under directory /src/activiti-examples/org/activiti/examples/mgmt/.

Source file: ManagementServiceTest.java

  31 
vote

private void assertOneOf(String[] possibleValues,String currentValue){
  for (  String value : possibleValues) {
    if (currentValue.equals(value)) {
      return;
    }
  }
  fail("Value '" + currentValue + "' should be one of: "+ Arrays.deepToString(possibleValues));
}
 

Example 7

From project AdminCmd, under directory /src/main/java/be/Balor/Importer/.

Source file: SubDirFileFilter.java

  31 
vote

/** 
 * Returns a List<File> of all Dirs/Files depending on the filter. If recursive is set to true it will get dirs/files in sub-diretories too.
 * @param basedir
 * @param filter
 * @param recursive
 * @return A list of files and/or directories matching the input pattern
 */
public final List<File> getFiles(final File basedir,final FileFilter filter,boolean recursive){
  List<File> files=new ArrayList<File>();
  if (basedir != null && basedir.isDirectory()) {
    if (recursive)     for (    File subdir : basedir.listFiles())     files.addAll(this.getFiles(subdir,filter,recursive));
    files.addAll(Arrays.asList(basedir.listFiles(filter)));
  }
  return files;
}
 

Example 8

From project aerogear-controller, under directory /src/main/java/org/jboss/aerogear/controller/router/.

Source file: RouteBuilderImpl.java

  31 
vote

@SuppressWarnings("unchecked") private Set<Class<? extends Throwable>> exceptions(final Class<?>... exceptions){
  final List<Class<?>> list=Arrays.asList(exceptions);
  final HashSet<Class<? extends Throwable>> set=new HashSet<Class<? extends Throwable>>();
  for (  Class<?> e : list) {
    if (!Throwable.class.isAssignableFrom(e)) {
      throw new IllegalArgumentException("Class '" + e.getName() + "' must be a subclass of Throwable");
    }
    set.add((Class<? extends Throwable>)e);
  }
  return new HashSet<Class<? extends Throwable>>(set);
}
 

Example 9

From project 2Degrees-Toolbox, under directory /ActionBarSherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/.

Source file: KeyframeSet.java

  30 
vote

public KeyframeSet(Keyframe... keyframes){
  mNumKeyframes=keyframes.length;
  mKeyframes=new ArrayList<Keyframe>();
  mKeyframes.addAll(Arrays.asList(keyframes));
  mFirstKeyframe=mKeyframes.get(0);
  mLastKeyframe=mKeyframes.get(mNumKeyframes - 1);
  mInterpolator=mLastKeyframe.getInterpolator();
}
 

Example 10

From project 4308Cirrus, under directory /Extras/actionbarsherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/.

Source file: KeyframeSet.java

  30 
vote

public KeyframeSet(Keyframe... keyframes){
  mNumKeyframes=keyframes.length;
  mKeyframes=new ArrayList<Keyframe>();
  mKeyframes.addAll(Arrays.asList(keyframes));
  mFirstKeyframe=mKeyframes.get(0);
  mLastKeyframe=mKeyframes.get(mNumKeyframes - 1);
  mInterpolator=mLastKeyframe.getInterpolator();
}
 

Example 11

From project Aardvark, under directory /aardvark/src/main/test/gw/vark/it/.

Source file: ForkedAntProcess.java

  30 
vote

@Override protected List<File> createClasspath(){
  try {
    File assemblyDir=ITUtil.getAssemblyDir();
    File libDir=new File(assemblyDir,"lib");
    File antJar=ITUtil.findFile(libDir,"ant-[\\d\\.]+\\.jar");
    File antLauncherJar=ITUtil.findFile(libDir,"ant-launcher-[\\d\\.]+\\.jar");
    return Arrays.asList(antJar,antLauncherJar);
  }
 catch (  FileNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 

Example 12

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/core/.

Source file: FileBasedStorage.java

  30 
vote

/** 
 * Loads an ontology element from its serialized form.
 * @param serializedElement The serialized ontology element.
 * @param id The id of the ontology element.
 * @param ontology The ontology at which the ontology element should be registered.
 */
private static void loadOntologyElement(String serializedElement,long id,Ontology ontology){
  List<String> lines=new ArrayList<String>(Arrays.asList(serializedElement.split("\n")));
  if (lines.size() == 0 || !lines.get(0).startsWith("type:")) {
    System.err.println("Cannot read ontology element (missing 'type')");
    return;
  }
  String type=lines.remove(0).substring("type:".length());
  OntologyElement oe=ontology.getEngine().createOntologyElement(type);
  if (oe != null) {
    if (!lines.get(0).startsWith("words:")) {
      System.err.println("Cannot read ontology element (missing 'words')");
      return;
    }
    String serializedWords=lines.remove(0).substring("words:".length());
    ontology.change(oe,serializedWords);
  }
  if (type.equals("mainpage")) {
    id=0;
    oe=new DummyOntologyElement("mainpage","Main Page");
  }
  if (oe != null) {
    oe.initOntology(ontology);
    oe.initArticle(loadArticle(lines,oe));
    oe.initId(id);
    ontology.register(oe);
  }
 else {
    System.err.println("Failed to load ontology element with id " + id);
  }
  return;
}
 

Example 13

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/ui/custom/.

Source file: SelectUsersPopupWindow.java

  30 
vote

protected void selectUser(String userId,String userName){
  if (!selectedUsersTable.containsId(userId)) {
    Item item=selectedUsersTable.addItem(userId);
    item.getItemProperty("userName").setValue(userName);
    if (showRoles) {
      ComboBox comboBox=new ComboBox(null,Arrays.asList(i18nManager.getMessage(Messages.TASK_ROLE_CONTRIBUTOR),i18nManager.getMessage(Messages.TASK_ROLE_IMPLEMENTER),i18nManager.getMessage(Messages.TASK_ROLE_MANAGER),i18nManager.getMessage(Messages.TASK_ROLE_SPONSOR)));
      comboBox.select(i18nManager.getMessage(Messages.TASK_ROLE_CONTRIBUTOR));
      comboBox.setNewItemsAllowed(true);
      item.getItemProperty("role").setValue(comboBox);
    }
  }
}
 

Example 14

From project Activiti-KickStart, under directory /activiti-kickstart-ui/src/main/java/org/activiti/kickstart/ui/table/.

Source file: PropertyTable.java

  30 
vote

protected void addPropertyRow(Object itemId,String propertyName,String propertyType,Boolean required){
  Object newItemId=null;
  if (itemId == null) {
    newItemId=addItem();
  }
 else {
    newItemId=addItemAfter(itemId);
  }
  Item newItem=getItem(newItemId);
  newItem.getItemProperty("property").setValue(propertyName == null ? "My Property" : propertyName);
  ComboBox typeComboBox=new ComboBox("types",Arrays.asList("text","number","date"));
  typeComboBox.setNullSelectionAllowed(false);
  if (propertyType == null) {
    typeComboBox.setValue(typeComboBox.getItemIds().iterator().next());
  }
 else {
    typeComboBox.setValue(propertyType);
  }
  newItem.getItemProperty("type").setValue(typeComboBox);
  CheckBox requiredCheckBox=new CheckBox();
  requiredCheckBox.setValue(required == null ? false : required);
  newItem.getItemProperty("required").setValue(requiredCheckBox);
  HorizontalLayout actionButtons=new HorizontalLayout();
  Button deleteRowButton=new Button("-");
  deleteRowButton.setData(newItemId);
  deleteRowButton.addListener(new DeletePropertyClickListener(this));
  actionButtons.addComponent(deleteRowButton);
  Button addRowButton=new Button("+");
  addRowButton.setData(newItemId);
  addRowButton.addListener(new AddPropertyClickListener(this));
  actionButtons.addComponent(addRowButton);
  newItem.getItemProperty("actions").setValue(actionButtons);
}
 

Example 15

From project addis, under directory /application/src/integration-test/java/org/drugis/addis/mtc/.

Source file: ContinuousInconsistencyModelIT.java

  30 
vote

private NetworkMetaAnalysis buildContinuousNetworkMetaAnalysis(){
  List<Study> studies=Arrays.asList(new Study[]{ExampleData.buildStudyBennie(),ExampleData.buildStudyChouinard(),ExampleData.buildStudyAdditionalThreeArm()});
  List<TreatmentDefinition> drugs=Arrays.asList(new TreatmentDefinition[]{TreatmentDefinition.createTrivial(ExampleData.buildDrugFluoxetine()),TreatmentDefinition.createTrivial(ExampleData.buildDrugParoxetine()),TreatmentDefinition.createTrivial(ExampleData.buildDrugSertraline())});
  NetworkMetaAnalysis analysis=new NetworkMetaAnalysis("Test Network",ExampleData.buildIndicationDepression(),ExampleData.buildEndpointCgi(),studies,drugs,ExampleData.buildMap(studies,drugs));
  return analysis;
}
 

Example 16

From project ades, under directory /src/main/java/com/cloudera/science/pig/.

Source file: Combinatorial.java

  30 
vote

private void process(List<Comparable> values,Comparable[] subset,int curSubsetSize,int nextIndex,DataBag output){
  if (curSubsetSize == subset.length) {
    output.add(tupleFactory.newTuple(Arrays.asList(subset)));
  }
 else {
    for (int i=nextIndex; i < values.size(); i++) {
      subset[curSubsetSize]=values.get(i);
      process(values,subset,curSubsetSize + 1,i + 1,output);
    }
  }
}
 

Example 17

From project AdminStuff, under directory /src/main/java/de/minestar/AdminStuff/commands/.

Source file: cmdTempBan.java

  30 
vote

private int[] parseString(String date,CommandSender sender){
  int[] result=new int[3];
  try {
    StringTokenizer st=new StringTokenizer(date,"[d,h,m]",true);
    int i=0;
    char c=0;
    while (st.hasMoreTokens()) {
      i=Integer.parseInt(st.nextToken());
      c=st.nextToken().charAt(0);
      fillDates(result,c,i);
    }
  }
 catch (  Exception e) {
    ChatUtils.writeError(sender,pluginName,"Falsche Syntax! Beispiele: ");
    showExamples(sender);
    return null;
  }
  if (result[0] < 1 && result[1] < 1 && result[2] < 1) {
    ChatUtils.writeError(sender,pluginName,Arrays.toString(result) + "sind ungueltige Eingabe! Eine Zahl muss wenigstens positiv ungleich null sein!");
    showExamples(sender);
    return null;
  }
  return result;
}
 

Example 18

From project AeminiumRuntime, under directory /src/aeminium/runtime/tests/.

Source file: Cycle.java

  30 
vote

@Test(timeout=2000) public void testRoundDeadlock(){
  final AtomicBoolean cycle=new AtomicBoolean();
  Runtime rt=getRuntime();
  rt.init();
  rt.addErrorHandler(new ErrorHandler(){
    @Override public void handleTaskException(    Task task,    Throwable t){
    }
    @Override public void handleTaskDuplicatedSchedule(    Task task){
    }
    @Override public void handleLockingDeadlock(){
    }
    @Override public void handleInternalError(    Error err){
    }
    @Override public void handleDependencyCycle(    Task task){
      cycle.set(true);
    }
  }
);
  Task t1=rt.createNonBlockingTask(createBody(1),Runtime.NO_HINTS);
  Task t2=rt.createNonBlockingTask(createBody(2),Runtime.NO_HINTS);
  Task t3=rt.createNonBlockingTask(createBody(3),Runtime.NO_HINTS);
  Task t4=rt.createNonBlockingTask(createBody(4),Runtime.NO_HINTS);
  rt.schedule(t1,Runtime.NO_PARENT,Arrays.asList(t4));
  rt.schedule(t2,Runtime.NO_PARENT,Arrays.asList(t1));
  rt.schedule(t3,Runtime.NO_PARENT,Arrays.asList(t2));
  rt.schedule(t4,Runtime.NO_PARENT,Arrays.asList(t3));
  if (!cycle.get()) {
    Assert.fail("Did not detect self cylcle.");
    rt.shutdown();
  }
}
 

Example 19

From project aether-ant, under directory /src/main/java/org/eclipse/aether/ant/tasks/.

Source file: Layout.java

  30 
vote

public Layout(String layout) throws BuildException {
  Collection<String> valid=new HashSet<String>(Arrays.asList(GID,GID_DIRS,AID,VER,BVER,EXT,CLS));
  List<String> tokens=new ArrayList<String>();
  Matcher m=Pattern.compile("(\\{[^}]*\\})|([^{]+)").matcher(layout);
  while (m.find()) {
    if (m.group(1) != null && !valid.contains(m.group(1))) {
      throw new BuildException("Invalid variable '" + m.group() + "' in layout, supported variables are "+ new TreeSet<String>(valid));
    }
    tokens.add(m.group());
  }
  this.tokens=tokens.toArray(new String[tokens.size()]);
}
 

Example 20

From project aether-core, under directory /aether-api/src/main/java/org/eclipse/aether/repository/.

Source file: AuthenticationContext.java

  30 
vote

/** 
 * Puts the specified authentication data into this context. This method should only be called from implementors of {@link Authentication#fill(AuthenticationContext,String,Map)}. Passed in character arrays are not cloned and become owned by this context, i.e. get erased when the context gets closed.
 * @param key The key to associate the authentication data with, must not be {@code null}.
 * @param value The (cleartext) authentication data to store, may be {@code null}.
 */
public void put(String key,Object value){
  if (key == null) {
    throw new IllegalArgumentException("authentication data key missing");
  }
synchronized (authData) {
    Object oldValue=authData.put(key,value);
    if (oldValue instanceof char[]) {
      Arrays.fill((char[])oldValue,'\0');
    }
  }
}
 

Example 21

From project agile, under directory /agile-apps/agile-app-dashboard/src/main/java/org/headsupdev/agile/app/dashboard/.

Source file: Account.java

  30 
vote

public SortableEntityProvider<Issue> getIssuesWatchedBy(final org.headsupdev.agile.api.User user){
  return new SortableEntityProvider<Issue>(){
    @Override protected Criteria createCriteria(){
      Session session=((HibernateStorage)Manager.getStorageInstance()).getHibernateSession();
      Criteria c=session.createCriteria(Issue.class);
      c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
      c.add(Restrictions.lt("status",Issue.STATUS_RESOLVED));
      c.createCriteria("watchers").add(Restrictions.eq("username",user.getUsername()));
      return c;
    }
    @Override protected List<Order> getDefaultOrder(){
      return Arrays.asList(Order.asc("priority"),Order.asc("status"),Order.asc("id.id"));
    }
  }
;
}
 

Example 22

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.

Source file: ViewMethods.java

  30 
vote

private SortedSet<WordInfo> getReportWordCloud(BaseReportInfo report,Set<BaseField> reportBaseFields,Set<String> stopWords,int minWeight,int maxWeight,int maxTags) throws ObjectNotFoundException, DisallowedException, CodingErrorException, CantDoThatException, SQLException {
  Map<BaseField,String> filters=this.sessionData.getReportFilterValues();
  Set<BaseField> textFields=new HashSet<BaseField>();
  FIELDS:   for (  BaseField field : reportBaseFields) {
    if (field.getDbType().equals(DatabaseFieldType.VARCHAR)) {
      if (field instanceof TextField) {
        if (((TextField)field).usesLookup()) {
          continue FIELDS;
        }
      }
      if (!field.getHidden()) {
        textFields.add(field);
      }
    }
  }
  if (stopWords == null) {
    stopWords=new HashSet<String>();
  }
  for (  BaseField field : report.getReportBaseFields()) {
    String filterValue=filters.get(field);
    if (filterValue != null) {
      filterValue=Helpers.rinseString(filterValue);
      if (!filterValue.equals("")) {
        Set<String> fieldStopWords=new HashSet<String>(Arrays.asList(filterValue.split("\\s")));
        stopWords.addAll(fieldStopWords);
      }
    }
  }
  if (textFields.size() == 0) {
    return new TreeSet<WordInfo>();
  }
  String conglomoratedText=this.databaseDefn.getDataManagement().getReportDataText(report,textFields,this.sessionData.getReportFilterValues(),1000000);
  WordCloud cloud=new WordCloud(conglomoratedText,minWeight,maxWeight,maxTags,stopWords);
  return cloud.getWords();
}
 

Example 23

From project agit, under directory /agit/src/main/java/com/madgag/agit/ssh/.

Source file: CuriousHostKeyRepository.java

  30 
vote

public int check(String host,byte[] key){
  byte[] knownKey=knownKeys.get(host);
  if (knownKey == null) {
    return userCheckKey(host,key);
  }
  return Arrays.equals(knownKey,key) ? OK : CHANGED;
}
 

Example 24

From project agraph-java-client, under directory /src/com/franz/agraph/http/.

Source file: AGHttpRepoClient.java

  30 
vote

/** 
 * Returns a list of indices for this repository.  When listValid is true, return all possible valid index types for this store; when listValid is  false, return only the current actively managed index types.
 * @param listValid true yields all valid types, false yields active types. 
 * @return list of indices, never null
 * @throws AGHttpException
 */
public List<String> listIndices(boolean listValid) throws AGHttpException {
  String url=AGProtocol.getIndicesURL(getRoot());
  Header[] headers=new Header[0];
  NameValuePair[] data={new NameValuePair("listValid",Boolean.toString(listValid))};
  AGStringHandler handler=new AGStringHandler();
  getHTTPClient().get(url,headers,data,handler);
  return Arrays.asList(handler.getResult().split("\n"));
}