Java Code Examples for java.util.HashSet

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 addis, under directory /application/src/test/java/org/drugis/addis/presentation/.

Source file: PropertyListHolderTest.java

  17 
vote

@SuppressWarnings({"unchecked","rawtypes"}) @Test public void testListHolderSetsValuesInUnderlyingSetProperty(){
  ValueModel valueHolderModel=new ValueHolder(new HashSet<String>());
  List<String> values=new ArrayList<String>();
  values.add("a");
  values.add("b");
  values.add("c");
  PropertyListHolder<String> propertyListHolder=new PropertyListHolder<String>(valueHolderModel,"value",String.class);
  propertyListHolder.setValue(values);
  assertTrue(valueHolderModel.getValue() instanceof Set);
  assertEquals(new HashSet(values),valueHolderModel.getValue());
}
 

Example 2

From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/cli/.

Source file: CommonsCLISupport.java

  16 
vote

/** 
 */
static public String[] setOptions(Object target,CommandLine cli){
  Option[] options=cli.getOptions();
  for (  Option option : options) {
    String name=option.getLongOpt();
    if (name == null)     continue;
    String propName=convertOptionToPropertyName(name);
    String value=option.getValue();
    if (value != null) {
      Class<?> type=IntrospectionSupport.getPropertyType(target,propName);
      if (type.isArray()) {
        IntrospectionSupport.setProperty(target,propName,option.getValues());
      }
 else       if (type.isAssignableFrom(ArrayList.class)) {
        IntrospectionSupport.setProperty(target,propName,new ArrayList(option.getValuesList()));
      }
 else       if (type.isAssignableFrom(HashSet.class)) {
        IntrospectionSupport.setProperty(target,propName,new HashSet(option.getValuesList()));
      }
 else {
        IntrospectionSupport.setProperty(target,propName,value);
      }
    }
 else {
      IntrospectionSupport.setProperty(target,propName,true);
    }
  }
  return cli.getArgs();
}
 

Example 3

From project 16Blocks, under directory /src/main/java/de/minestar/sixteenblocks/Core/.

Source file: Core.java

  15 
vote

private void loadSupporter(){
  Core.supporter=new HashSet<String>(16);
  Core.vips=new HashSet<String>(16);
  this.loadUsers(Core.supporter,"supporter.txt");
  this.loadUsers(Core.vips,"vips.txt");
}
 

Example 4

From project Aardvark, under directory /aardvark-core/src/test/java/gw/vark/enums/.

Source file: EnumGenerator.java

  15 
vote

public static void main(String[] args) throws Exception {
  Gosu.setClasspath(getSystemClasspath());
  _filesInEnums=new HashSet<String>();
  for (  File enumFile : ENUMS_DIR.listFiles()) {
    _filesInEnums.add(enumFile.getName());
  }
  for (  CharSequence typeName : TypeSystem.getAllTypeNames()) {
    try {
      IType iType=TypeSystem.getByFullNameIfValid(typeName.toString());
      maybeGenEnum(iType,ENUMS_DIR);
    }
 catch (    Throwable e) {
      System.out.println("Error : " + e.getMessage());
    }
  }
  for (  String leftover : _filesInEnums) {
    System.err.println(leftover + " might be obsolete");
  }
}
 

Example 5

From project accesointeligente, under directory /src/org/accesointeligente/client/views/.

Source file: RegisterView.java

  15 
vote

@Override public Set<Activity> getInstitutionActivities(){
  Set<Activity> activities=new HashSet<Activity>();
  for (int i=0; i < institutionActivities.getWidgetCount(); i++) {
    Widget widget=institutionActivities.getWidget(i);
    if (widget instanceof CheckBox) {
      CheckBox cb=(CheckBox)widget;
      if (cb.getValue()) {
        Activity activity=new Activity();
        activity.setId(Integer.parseInt(cb.getFormValue()));
        activity.setName(cb.getText());
        activities.add(activity);
      }
    }
  }
  return activities;
}
 

Example 6

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

Source file: ACESentence.java

  15 
vote

public Set<OWLAxiom> getOWLAxioms(){
  if (parserResult == null) {
    update();
  }
  if (owlAxioms == null) {
    owlAxioms=new HashSet<OWLAxiom>();
  }
  return owlAxioms;
}
 

Example 7

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

Source file: StaticConfiguration.java

  15 
vote

public void setTrustedAddresses(Set<String> trustedAddresses) throws UnknownHostException {
  this.trustedAddresses=trustedAddresses;
  this.trustedInetAddresses=new HashSet<InetAddress>(trustedAddresses.size());
  for (  String address : trustedAddresses) {
    trustedInetAddresses.add(InetAddress.getByName(address));
  }
}
 

Example 8

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

Source file: IdentityTest.java

  15 
vote

private Object createStringSet(String... strings){
  Set<String> stringSet=new HashSet<String>();
  for (  String string : strings) {
    stringSet.add(string);
  }
  return stringSet;
}
 

Example 9

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

Source file: GroupSelectionPopupWindow.java

  15 
vote

@SuppressWarnings("unchecked") public Set<String> getSelectedGroupIds(){
  Set<String> groupIds=new HashSet<String>();
  for (  Object itemId : (Set<Object>)groupTable.getValue()) {
    groupIds.add((String)groupTable.getItem(itemId).getItemProperty("id").getValue());
  }
  return groupIds;
}
 

Example 10

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

Source file: ProcessDiagramGenerator.java

  15 
vote

public InputStream execute(){
  this.startX=0;
  this.startY=calculateMaximumHeight() / 2 + 10;
  this.currentWidth=0;
  int width=calculateMaximumWidth() + 50;
  int height=calculateMaximumHeight() + 50;
  processDiagramCanvas=new ProcessDiagramCanvas(width,height);
  Definitions definitions=marshallingService.convertToBpmn(kickstartWorkflow);
  Process process=getProcess(definitions);
  this.plane=getPlane(definitions);
  List<FlowElement> flowElements=process.getFlowElement();
  generateSequenceflowMappings(flowElements);
  this.handledElements=new HashSet<String>();
  for (  FlowElement flowElement : flowElements) {
    if (!handledElements.contains(flowElement.getId())) {
      if (flowElement instanceof StartEvent) {
        drawStartEvent(flowElement,startX,startY,EVENT_WIDTH,EVENT_WIDTH);
      }
 else       if (flowElement instanceof EndEvent) {
        drawSequenceFlow(incomingSequenceFlowMapping.get(flowElement.getId()).get(0),currentWidth,startY + EVENT_WIDTH / 2,currentWidth + SEQUENCE_FLOW_WIDTH,startY + EVENT_WIDTH / 2);
        drawEndEvent(flowElement,currentWidth,startY,EVENT_WIDTH,EVENT_WIDTH);
      }
 else       if (flowElement instanceof ParallelGateway && outgoingSequenceFlowMapping.get(flowElement.getId()).size() > 1) {
        ParallelGateway parallelGateway=(ParallelGateway)flowElement;
        drawSequenceFlow(incomingSequenceFlowMapping.get(flowElement.getId()).get(0),currentWidth,startY + EVENT_WIDTH / 2,currentWidth + SEQUENCE_FLOW_WIDTH,startY + EVENT_WIDTH / 2);
        drawParallelBlock(currentWidth,startY - EVENT_WIDTH / 2,parallelGateway);
      }
 else       if (flowElement instanceof Task) {
        drawSequenceFlow(incomingSequenceFlowMapping.get(flowElement.getId()).get(0),currentWidth,startY + EVENT_WIDTH / 2,currentWidth + SEQUENCE_FLOW_WIDTH,startY + EVENT_WIDTH / 2);
        drawTask(flowElement,currentWidth,startY - ((TASK_HEIGHT - EVENT_WIDTH) / 2),TASK_WIDTH,TASK_HEIGHT);
      }
    }
  }
  return processDiagramCanvas.generateImage("png");
}
 

Example 11

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/session/.

Source file: HttpSessionContext.java

  15 
vote

public Set<String> getKeySet(){
  HashSet<String> result=new HashSet<String>();
  for (@SuppressWarnings("unchecked") Enumeration<String> e=session.getAttributeNames(); e.hasMoreElements(); ) {
    result.add(e.nextElement());
  }
  return result;
}
 

Example 12

From project adbcj, under directory /api/src/main/java/org/adbcj/support/.

Source file: DefaultRow.java

  15 
vote

@Override public Set<java.util.Map.Entry<Object,Value>> entrySet(){
  if (entrySet == null) {
    Set<java.util.Map.Entry<Object,Value>> set=new HashSet<Entry<Object,Value>>();
    for (    Value value : values) {
      set.add(new AbstractMap.SimpleEntry<Object,Value>(value.getField(),value));
    }
    entrySet=Collections.unmodifiableSet(set);
  }
  return entrySet;
}
 

Example 13

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

Source file: ACHelper.java

  15 
vote

/** 
 * Get the list of kit.
 * @return
 */
public String getKitList(final CommandSender sender){
  String kitList="";
  final HashSet<String> list=new HashSet<String>();
  try {
    list.addAll(kits.keySet());
    if (Utils.oddItem != null) {
    }
  }
 catch (  final Throwable e) {
  }
  for (  final String kit : list) {
    if (PermissionManager.hasPerm(sender,"admincmd.kit." + kit,false)) {
      kitList+=kit + ", ";
    }
  }
  if (!kitList.equals("")) {
    if (kitList.endsWith(", ")) {
      kitList=kitList.substring(0,kitList.lastIndexOf(","));
    }
  }
  return kitList.trim();
}
 

Example 14

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

Source file: cmdChat.java

  15 
vote

private void createRecipientList(String[] args,Player player){
  StringBuilder output=new StringBuilder(256);
  Set<String> recipientSet=new HashSet<String>();
  Player temp=null;
  for (  String arg : args) {
    temp=PlayerUtils.getOnlinePlayer(arg);
    if (temp != null) {
      recipientSet.add(temp.getName().toLowerCase());
      output.append(temp.getName());
      output.append(", ");
    }
  }
  if (recipientSet.isEmpty()) {
    PlayerUtils.sendError(player,pluginName,"Kein Empfaenger gefunden!");
    return;
  }
  output.delete(output.length() - 2,output.length());
  pManager.setRecipients(player.getName().toLowerCase(),recipientSet);
  PlayerUtils.sendSuccess(player,pluginName,"Folgende Spieler erhalten jetzt deine Nachrichten:");
  PlayerUtils.sendInfo(player,output.toString());
}
 

Example 15

From project adt-maven-plugin, under directory /src/test/java/com/yelbota/plugins/adt/.

Source file: PackageAdtMojoTest.java

  15 
vote

@Test public void prepareAneDirTest() throws MojoFailureException {
  Set<Artifact> artifactList=new HashSet<Artifact>();
  ArtifactStub stub=new ArtifactStub();
  stub.setGroupId("com.example");
  stub.setArtifactId("myExt1");
  stub.setVersion("1.0");
  stub.setType("ane");
  stub.setFile(FileUtils.resolveFile(wd,"src/test/resources/unit/myExt1-1.0.ane"));
  artifactList.add(stub);
  stub=new ArtifactStub();
  stub.setGroupId("com.example");
  stub.setArtifactId("myLib");
  stub.setVersion("1.0");
  stub.setType("swc");
  artifactList.add(stub);
  stub=new ArtifactStub();
  stub.setGroupId("com.example");
  stub.setArtifactId("myExt2");
  stub.setVersion("1.1");
  stub.setType("ane");
  stub.setFile(FileUtils.resolveFile(wd,"src/test/resources/unit/myExt2-1.1.ane"));
  artifactList.add(stub);
  PackageAdtMojo mojo=new PackageAdtMojo();
  mojo.outputDirectory=FileUtils.resolveFile(wd,"target/unit/extDirTest");
  mojo.outputDirectory.mkdirs();
  mojo.project=new MavenProjectStub();
  mojo.project.setDependencyArtifacts(artifactList);
  File dir=mojo.prepareAneDir();
  String[] dirList=dir.list();
  String[] pattern=new String[]{"myExt1-1.0.ane","myExt2-1.1.ane"};
  Assert.assertTrue(dir.exists());
  Assert.assertEquals(dirList.length,pattern.length);
  for (int i=0; i < pattern.length; i++) {
    Assert.assertEquals(dirList[i],pattern[i]);
  }
}
 

Example 16

From project AeminiumRuntime, under directory /src/aeminium/runtime/implementations/implicitworkstealing/task/.

Source file: ImplicitAtomicTask.java

  15 
vote

public void addDataGroupDependecy(DataGroup required){
  if (requiredGroups == null) {
synchronized (this) {
      if (requiredGroups == null) {
        requiredGroups=Collections.synchronizedSet(new HashSet<DataGroup>());
      }
    }
  }
  requiredGroups.add(required);
}
 

Example 17

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

Source file: RouteBuilderImpl.java

  15 
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 18

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

Source file: AntModelResolver.java

  15 
vote

public AntModelResolver(RepositorySystemSession session,String context,RepositorySystem repoSys,RemoteRepositoryManager remoteRepositoryManager,List<RemoteRepository> repositories){
  this.session=session;
  this.context=context;
  this.repoSys=repoSys;
  this.remoteRepositoryManager=remoteRepositoryManager;
  this.repositories=repositories;
  this.repositoryIds=new HashSet<String>();
}
 

Example 19

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

Source file: AetherModule.java

  15 
vote

@Provides @Singleton Set<LocalRepositoryManagerFactory> provideLocalRepositoryManagerFactories(@Named("simple") LocalRepositoryManagerFactory simple,@Named("enhanced") LocalRepositoryManagerFactory enhanced){
  Set<LocalRepositoryManagerFactory> factories=new HashSet<LocalRepositoryManagerFactory>();
  factories.add(simple);
  factories.add(enhanced);
  return Collections.unmodifiableSet(factories);
}
 

Example 20

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

Source file: AddAccount.java

  15 
vote

public void onSubmit(){
  User exists=getSecurityManager().getUserByUsername(username);
  if (exists != null) {
    info("An account with username " + username + " already exists");
    return;
  }
  StoredUser created=new StoredUser(username);
  created.setPassword(password);
  created.setEmail(email);
  created.setFirstname(firstname);
  created.setLastname(lastname);
  created.addRole(getSecurityManager().getRoleById((new MemberRole()).getId()));
  HashSet<Project> allProjects=new HashSet<Project>(getStorage().getProjects());
  allProjects.add(StoredProject.getDefault());
  created.setProjects(allProjects);
  for (  Project project : allProjects) {
    project.getUsers().add(created);
  }
  Set<User> defaultProjectMembers=StoredProject.getDefault().getUsers();
  defaultProjectMembers.add(created);
  StoredProject.setDefaultProjectMembers(defaultProjectMembers);
  ((AdminApplication)getHeadsUpApplication()).addUser(created);
  PageParameters params=new PageParameters();
  params.add("username",created.getUsername());
  setResponsePage(getPageClass("account"),params);
}
 

Example 21

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

Source file: AppUser.java

  15 
vote

public void sendPasswordReset(String appUrl) throws CantDoThatException, CodingErrorException, MessagingException {
  if (this.getEmail() == null) {
    throw new CantDoThatException("The user has no email address");
  }
  if (!this.getEmail().contains("@")) {
    throw new CantDoThatException("The user's email isn't valid");
  }
  try {
    String password=RandomString.generate();
    this.hashAndSetPassword(password);
    String passwordResetLink=appUrl + "?return=gui/set_password/email_reset&u=" + this.getUserName()+ "&x="+ password;
    if (this.getAllowPasswordReset()) {
      throw new CantDoThatException("The previous password reset request hasn't timed out yet, please use that: " + passwordResetLink);
    }
    Set<String> recipients=new HashSet<String>();
    recipients.add(this.getEmail());
    String subject="Set your password";
    String body="Please choose a password for your account by following this link:\n\n";
    body+=passwordResetLink + "\n";
    Helpers.sendEmail(recipients,body,subject);
  }
 catch (  MissingParametersException mpex) {
    throw new CodingErrorException("Error generating a password: " + mpex);
  }
  this.passwordResetSent=System.currentTimeMillis();
}
 

Example 22

From project Agot-Java, under directory /src/main/java/got/pojo/.

Source file: GameInfo.java

  15 
vote

public Boolean needIronJudgemenet(){
  Set<Integer> diff=new HashSet<Integer>();
  for (  FamilyInfo fi : familiesMap.values()) {
    diff.add(fi.getCompetePower());
  }
  return diff.size() < addrmap.size();
}
 

Example 23

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

Source file: AGGraphMaker.java

  15 
vote

/** 
 * Returns a graph that is the union of specified graphs. By convention, the first graph mentioned will be used for add operations on the union.  All other operations will apply to all graphs in the union.  If no graphs are supplied, the union of all graphs is assumed, and add operations apply to the default graph.
 * @param graphs the graphs in the union
 * @return the union of the specified graphs
 */
public AGGraphUnion createUnion(AGGraph... graphs){
  Set<Resource> contexts=new HashSet<Resource>();
  for (  AGGraph g : graphs) {
    contexts.addAll(Arrays.asList(g.getGraphContexts()));
  }
  Resource context=null;
  if (graphs.length > 0) {
    context=graphs[0].getGraphContext();
  }
  return new AGGraphUnion(this,context,contexts.toArray(new Resource[contexts.size()]));
}
 

Example 24

From project Aion-Extreme, under directory /AE-go_DataPack/loginserver/data/scripts/system/database/mysql5/.

Source file: MySQL5BannedIpDAO.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public Set<BannedIP> getAllBans(){
  final Set<BannedIP> result=new HashSet<BannedIP>();
  DB.select("SELECT * FROM banned_ip",new ReadStH(){
    @Override public void handleRead(    ResultSet resultSet) throws SQLException {
      while (resultSet.next()) {
        BannedIP ip=new BannedIP();
        ip.setId(resultSet.getInt("id"));
        ip.setMask(resultSet.getString("mask"));
        ip.setTimeEnd(resultSet.getTimestamp("time_end"));
        result.add(ip);
      }
    }
  }
);
  return result;
}
 

Example 25

From project airlift, under directory /configuration/src/main/java/io/airlift/configuration/testing/.

Source file: ConfigAssertions.java

  15 
vote

public static <T>void assertRecordedDefaults(T recordedConfig){
  $$RecordedConfigData<T> recordedConfigData=getRecordedConfig(recordedConfig);
  Set<Method> invokedMethods=recordedConfigData.getInvokedMethods();
  T config=recordedConfigData.getInstance();
  Class<T> configClass=(Class<T>)config.getClass();
  ConfigurationMetadata<?> metadata=ConfigurationMetadata.getValidConfigurationMetadata(configClass);
  Map<String,Object> attributeValues=new TreeMap<String,Object>();
  Set<String> setDeprecatedAttributes=new TreeSet<String>();
  Set<Method> validSetterMethods=new HashSet<Method>();
  for (  AttributeMetadata attribute : metadata.getAttributes().values()) {
    if (attribute.getInjectionPoint().getProperty() != null) {
      validSetterMethods.add(attribute.getInjectionPoint().getSetter());
    }
    if (invokedMethods.contains(attribute.getInjectionPoint().getSetter())) {
      if (attribute.getInjectionPoint().getProperty() != null) {
        Object value=invoke(config,attribute.getGetter());
        attributeValues.put(attribute.getName(),value);
      }
 else {
        setDeprecatedAttributes.add(attribute.getName());
      }
    }
  }
  if (!setDeprecatedAttributes.isEmpty()) {
    Assert.fail("Invoked deprecated attribute setter methods: " + setDeprecatedAttributes);
  }
  if (!validSetterMethods.containsAll(invokedMethods)) {
    Set<Method> invalidInvocations=new HashSet<Method>(invokedMethods);
    invalidInvocations.removeAll(validSetterMethods);
    Assert.fail("Invoked non-attribute setter methods: " + invalidInvocations);
  }
  assertDefaults(attributeValues,configClass);
}
 

Example 26

From project Airports, under directory /src/com/nadmm/airports/.

Source file: ActivityBase.java

  15 
vote

protected Intent checkData(){
  if (!SystemUtils.isExternalStorageAvailable()) {
    Intent intent=new Intent(this,ExternalStorageActivity.class);
    return intent;
  }
  Cursor c=mDbManager.getCurrentFromCatalog();
  String msg=null;
  HashSet<String> installed=new HashSet<String>();
  if (c.moveToFirst()) {
    do {
      String type=c.getString(c.getColumnIndex(Catalog.TYPE));
      installed.add(type);
      int age=c.getInt(c.getColumnIndex("age"));
      if (age <= 0) {
        msg="One or more data items have expired";
        break;
      }
      SQLiteDatabase db=mDbManager.getDatabase(type);
      if (db == null) {
        msg="Database is corrupted. Please delete and re-install";
        break;
      }
    }
 while (c.moveToNext());
  }
  c.close();
  if (installed.size() < 4) {
    msg="Please download the required database";
  }
  Intent intent=null;
  if (msg != null) {
    intent=new Intent(this,DownloadActivity.class);
    intent.putExtra("MSG",msg);
  }
  return intent;
}
 

Example 27

From project akela, under directory /src/main/java/com/mozilla/hadoop/hbase/mapreduce/.

Source file: MultiScanTableInputFormat.java

  15 
vote

@Override public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {
  if (table == null) {
    throw new IOException("No table was provided.");
  }
  Pair<byte[][],byte[][]> keys=table.getStartEndKeys();
  if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) {
    throw new IOException("Expecting at least one region.");
  }
  Set<InputSplit> splits=new HashSet<InputSplit>();
  for (int i=0; i < keys.getFirst().length; i++) {
    String regionLocation=table.getRegionLocation(keys.getFirst()[i]).getServerAddress().getHostname();
    for (    Scan s : scans) {
      byte[] startRow=s.getStartRow();
      byte[] stopRow=s.getStopRow();
      if ((startRow.length == 0 || keys.getSecond()[i].length == 0 || Bytes.compareTo(startRow,keys.getSecond()[i]) < 0) && (stopRow.length == 0 || Bytes.compareTo(stopRow,keys.getFirst()[i]) > 0)) {
        byte[] splitStart=startRow.length == 0 || Bytes.compareTo(keys.getFirst()[i],startRow) >= 0 ? keys.getFirst()[i] : startRow;
        byte[] splitStop=(stopRow.length == 0 || Bytes.compareTo(keys.getSecond()[i],stopRow) <= 0) && keys.getSecond()[i].length > 0 ? keys.getSecond()[i] : stopRow;
        InputSplit split=new TableSplit(table.getTableName(),splitStart,splitStop,regionLocation);
        splits.add(split);
      }
    }
  }
  return new ArrayList<InputSplit>(splits);
}
 

Example 28

From project akubra, under directory /akubra-core/src/main/java/org/akubraproject/impl/.

Source file: StreamManager.java

  15 
vote

/** 
 * Notification that a connection is closed. All its open streams are closed.
 * @param con the connection that is closed
 */
public void connectionClosed(BlobStoreConnection con){
  Set<Closeable> closeables=new HashSet<Closeable>();
synchronized (openOutputStreams) {
    for (    ManagedOutputStream c : openOutputStreams)     if (c.getConnection().equals(con))     closeables.add(c);
  }
synchronized (openInputStreams) {
    for (    ManagedInputStream c : openInputStreams)     if (c.getConnection().equals(con))     closeables.add(c);
  }
  if (!closeables.isEmpty()) {
    log.warn("Auto-closing " + closeables.size() + " open streams for closed connection "+ con);
    for (    Closeable c : closeables) {
      if (c instanceof InputStream)       IOUtils.closeQuietly((InputStream)c);
 else       IOUtils.closeQuietly((OutputStream)c);
    }
  }
}
 

Example 29

From project AlarmApp-Android, under directory /src/org/alarmapp/model/classes/.

Source file: AlarmData.java

  15 
vote

@SuppressWarnings("unchecked") public static AlarmData create(Bundle extra){
  AlarmData a=new AlarmData();
  a.operation_id=extra.getString(OPERATION_ID);
  a.alarmed=DateUtil.parse(extra.getString(ALARMED));
  a.title=extra.getString(TITLE);
  a.text=extra.getString(TEXT);
  if (extra.containsKey(ALARMED_USER_LIST)) {
    a.alarmedUsers=(HashSet<AlarmedUser>)extra.getSerializable(ALARMED_USER_LIST);
  }
  if (extra.containsKey(IS_ALARMSTATUS_VIEWER))   a.isAlarmstatusViewer=Boolean.parseBoolean(extra.getString(IS_ALARMSTATUS_VIEWER).toLowerCase());
  LogEx.verbose("AlarmData Extra status is " + extra.getInt(OPERATION_STATUS));
  if (extra.containsKey(OPERATION_STATUS))   a.state=AlarmState.create(extra.getInt(OPERATION_STATUS));
  for (  String key : extra.keySet()) {
    if (isExtra(key)) {
      a.extraValues.put(key,extra.getString(key));
      LogEx.debug("Additional Data " + key + " = "+ extra.getString(key));
    }
  }
  return a;
}
 

Example 30

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/server/.

Source file: KerberosAuthenticationHandler.java

  15 
vote

/** 
 * Initializes the authentication handler instance. <p/> It creates a Kerberos context using the principal and keytab specified in the configuration. <p/> This method is invoked by the  {@link AuthenticationFilter#init} method.
 * @param config configuration properties to initialize the handler.
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override public void init(Properties config) throws ServletException {
  try {
    principal=config.getProperty(PRINCIPAL,principal);
    if (principal == null || principal.trim().length() == 0) {
      throw new ServletException("Principal not defined in configuration");
    }
    keytab=config.getProperty(KEYTAB,keytab);
    if (keytab == null || keytab.trim().length() == 0) {
      throw new ServletException("Keytab not defined in configuration");
    }
    if (!new File(keytab).exists()) {
      throw new ServletException("Keytab does not exist: " + keytab);
    }
    Set<Principal> principals=new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));
    Subject subject=new Subject(false,principals,new HashSet<Object>(),new HashSet<Object>());
    KerberosConfiguration kerberosConfiguration=new KerberosConfiguration(keytab,principal);
    loginContext=new LoginContext("",subject,null,kerberosConfiguration);
    loginContext.login();
    Subject serverSubject=loginContext.getSubject();
    try {
      gssManager=Subject.doAs(serverSubject,new PrivilegedExceptionAction<GSSManager>(){
        @Override public GSSManager run() throws Exception {
          return GSSManager.getInstance();
        }
      }
);
    }
 catch (    PrivilegedActionException ex) {
      throw ex.getException();
    }
    LOG.info("Initialized, principal [{}] from keytab [{}]",principal,keytab);
  }
 catch (  Exception ex) {
    throw new ServletException(ex);
  }
}
 

Example 31

From project AlgorithmsNYC, under directory /Algorithms/Graph/Kruskal/.

Source file: Kruskal_Rahul.java

  15 
vote

public static void main(String[] args){
  Node a=new Node("a");
  Node b=new Node("b");
  Node c=new Node("c");
  Node d=new Node("d");
  Node e=new Node("e");
  Node f=new Node("f");
  Node g=new Node("g");
  Node h=new Node("h");
  Node i=new Node("i");
  Edge[] edges={new Edge(new Node[]{a,b},4),new Edge(new Node[]{b,c},8),new Edge(new Node[]{a,h},8),new Edge(new Node[]{h,g},1),new Edge(new Node[]{g,f},2),new Edge(new Node[]{f,e},10),new Edge(new Node[]{f,d},14),new Edge(new Node[]{f,c},4),new Edge(new Node[]{e,d},9),new Edge(new Node[]{h,i},7),new Edge(new Node[]{i,g},6),new Edge(new Node[]{c,d},7),new Edge(new Node[]{c,i},2),new Edge(new Node[]{h,b},11)};
  List<Edge> sortedEdges=Arrays.asList(edges);
  Collections.sort(sortedEdges);
  Node[] nodes={a,b,c,d,e,f,g,h,i};
  List<Set<Node>> sets=new ArrayList<Set<Node>>();
  for (  Node node : nodes) {
    Set<Node> set=new HashSet<Node>();
    set.add(node);
    sets.add(set);
  }
  List<Edge> mst=new ArrayList<Edge>();
  for (  Edge edge : sortedEdges) {
    Set<Node> s1=getSet(sets,edge.nodes[0]);
    Set<Node> s2=getSet(sets,edge.nodes[1]);
    if (!s1.equals(s2)) {
      mst.add(edge);
      sets.remove(s2);
      sets.remove(s1);
      Set<Node> set=new HashSet<Node>();
      set.addAll(s2);
      set.addAll(s1);
      sets.add(set);
    }
  }
  for (  Edge edge : mst) {
    System.out.println(edge);
  }
}
 

Example 32

From project alljoyn_java, under directory /test/org/alljoyn/bus/.

Source file: AuthListenerTest.java

  15 
vote

public RsaAuthListener(String certificate,String privateKey,char[] password) throws Exception {
  this.certificate=certificate;
  this.privateKey=privateKey;
  this.password=password;
  if ("The Android Project".equals(System.getProperty("java.vendor"))) {
    factory=CertificateFactory.getInstance("X.509","BC");
    validator=CertPathValidator.getInstance("PKIX","BC");
  }
 else {
    factory=CertificateFactory.getInstance("X.509");
    validator=CertPathValidator.getInstance("PKIX");
  }
  trustAnchors=new HashSet<TrustAnchor>();
}
 

Example 33

From project ALP, under directory /workspace/alp-flexpilot/src/main/java/com/lohika/alp/flexpilot/.

Source file: Annotations.java

  15 
vote

/** 
 * Assert valid find by.
 * @param findBy the find by
 */
private void assertValidFindBy(FindBy findBy){
  if (findBy.how() != null) {
    if (findBy.using() == null) {
      throw new IllegalArgumentException("If you set the 'how' property, you must also set 'using'");
    }
  }
  Set<String> finders=new HashSet<String>();
  if (!"".equals(findBy.using()))   finders.add("how: " + findBy.using());
  if (!"".equals(findBy.id()))   finders.add("id: " + findBy.id());
  if (!"".equals(findBy.linkText()))   finders.add("link text: " + findBy.linkText());
  if (!"".equals(findBy.name()))   finders.add("name: " + findBy.name());
  if (!"".equals(findBy.chain()))   finders.add("chain: " + findBy.chain());
  if (finders.size() > 1) {
    throw new IllegalArgumentException(String.format("You must specify at most one location strategy. Number found: %d (%s)",finders.size(),finders.toString()));
  }
}
 

Example 34

From project alphaportal_dev, under directory /sys-src/alphaportal/core/src/test/java/alpha/portal/model/.

Source file: UserExtensionTest.java

  15 
vote

/** 
 * Test hash code equals.
 */
@Test public void testHashCodeEquals(){
  final ContributorRole r=new ContributorRole("test");
  final UserExtension ue=new UserExtension();
  ue.setUserId(1L);
  ue.addRole(r);
  final UserExtension ue2=new UserExtension();
  ue2.setUserId(1L);
  ue2.addRole(r);
  Assert.assertEquals(ue,ue2);
  Assert.assertEquals(ue.hashCode(),ue2.hashCode());
  Assert.assertNotSame(ue,new User());
  ue.toString();
  ue.setUser(new User());
  ue.setRoles(new HashSet<ContributorRole>());
  Assert.assertFalse(ue.equals(new String("I am not an User Extension! Please don?t shoot!")));
}
 

Example 35

From project amber, under directory /oauth-2.0/client/src/main/java/org/apache/amber/oauth2/client/validator/.

Source file: OAuthClientValidator.java

  15 
vote

public void validateRequiredParameters(OAuthClientResponse response) throws OAuthProblemException {
  Set<String> missingParameters=new HashSet<String>();
  for (  Map.Entry<String,String[]> requiredParam : requiredParams.entrySet()) {
    String paramName=requiredParam.getKey();
    String val=response.getParam(paramName);
    if (OAuthUtils.isEmpty(val)) {
      missingParameters.add(paramName);
    }
 else {
      String[] dependentParams=requiredParam.getValue();
      if (!OAuthUtils.hasEmptyValues(dependentParams)) {
        for (        String dependentParam : dependentParams) {
          val=response.getParam(dependentParam);
          if (OAuthUtils.isEmpty(val)) {
            missingParameters.add(dependentParam);
          }
        }
      }
    }
  }
  if (!missingParameters.isEmpty()) {
    throw OAuthUtils.handleMissingParameters(missingParameters);
  }
}
 

Example 36

From project ambrose, under directory /common/src/main/java/azkaban/common/utils/.

Source file: Props.java

  15 
vote

public Set<String> getKeySet(){
  HashSet<String> keySet=new HashSet<String>();
  keySet.addAll(localKeySet());
  if (_parent != null) {
    keySet.addAll(_parent.getKeySet());
  }
  return keySet;
}
 

Example 37

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/client/methods/.

Source file: HttpOptions.java

  15 
vote

public Set<String> getAllowedMethods(final HttpResponse response){
  if (response == null) {
    throw new IllegalArgumentException("HTTP response may not be null");
  }
  HeaderIterator it=response.headerIterator("Allow");
  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());
    }
  }
  return methods;
}
 

Example 38

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: ResourceLockManager.java

  15 
vote

/** 
 * @param task
 * @param pruneReleased
 * @return the dependencies if this task was to add its lock requests.
 */
public synchronized Collection<ResourceLocker> getDependentTasks(DependentPrioritizedTask task,boolean pruneReleased){
  Set<ResourceLocker> dependencies=new HashSet<ResourceLocker>();
  Collection<?> taskLocks=task.getResourceLocksNeeded();
  if (taskLocks != null) {
    for (    Object name : taskLocks) {
      ResourceLock lock=(ResourceLock)name;
      List<ResourceLock> lockList=getResourceLockListCopy(lock.getResourceName(),pruneReleased);
      if (pruneReleased && lock.isLockReleased()) {
        continue;
      }
      ResourceLock current=null;
      for (Iterator<ResourceLock> iter0=lockList.iterator(); iter0.hasNext(); ) {
        current=iter0.next();
        if (current == lock) {
          break;
        }
 else         if (current.getTask() == lock.getTask()) {
          throw new RuntimeException("Task has multiple locks on resource " + lock.getResourceName());
        }
 else         if (lock.isSharedLock() && current.isSharedLock()) {
          if (!isLockBeingShared(lock,current)) {
            dependencies.add(current.getTask());
          }
        }
 else         if (lock.isExclusiveLock()) {
          dependencies.add(current.getTask());
        }
 else         if (current.isExclusiveLock()) {
          dependencies.add(current.getTask());
        }
      }
      if (current != lock) {
        throw new ApplicationGeneralException(task + ": Did not find lock " + lock.getLockStr()+ " on list for resource="+ lock.getResourceName());
      }
    }
  }
  return dependencies;
}
 

Example 39

From project anadix, under directory /anadix-tests/src/main/java/org/anadix/test/.

Source file: SourceTestTemplate.java

  15 
vote

/** 
 * Data provider preparing Boolean values - null, true and false
 * @return data provider (Iterator<Object[]>)
 */
@DataProvider(name="booleans") public Iterator<Object[]> prepareBooleans(){
  Set<Object[]> s=new HashSet<Object[]>();
  s.add(new Object[]{null});
  s.add(new Object[]{true});
  s.add(new Object[]{false});
  return s.iterator();
}
 

Example 40

From project and-bible, under directory /AndBible/src/net/bible/android/control/bookmark/.

Source file: BookmarkControl.java

  15 
vote

/** 
 * label the bookmark with these and only these labels 
 */
public void setBookmarkLabels(BookmarkDto bookmark,List<LabelDto> labels){
  labels.remove(LABEL_ALL);
  labels.remove(LABEL_UNLABELLED);
  BookmarkDBAdapter db=new BookmarkDBAdapter();
  db.open();
  try {
    List<LabelDto> prevLabels=db.getBookmarkLabels(bookmark);
    Set<LabelDto> deleted=new HashSet<LabelDto>(prevLabels);
    deleted.removeAll(labels);
    for (    LabelDto label : deleted) {
      db.removeBookmarkLabelJoin(bookmark,label);
    }
    Set<LabelDto> added=new HashSet<LabelDto>(labels);
    added.removeAll(prevLabels);
    for (    LabelDto label : added) {
      db.insertBookmarkLabelJoin(bookmark,label);
    }
  }
  finally {
    db.close();
  }
}
 

Example 41

From project Android, under directory /app/src/main/java/com/github/mobile/persistence/.

Source file: AccountDataManager.java

  15 
vote

/** 
 * Add issue filter to store <p/> This method may perform file I/O and should never be called on the UI-thread
 * @param filter
 */
public void addIssueFilter(IssueFilter filter){
  final File cache=new File(root,"issue_filters.ser");
  Collection<IssueFilter> filters=read(cache);
  if (filters == null)   filters=new HashSet<IssueFilter>();
  if (filters.add(filter))   write(cache,filters);
}
 

Example 42

From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/rest/transformation/.

Source file: DocLaunchPadForXML.java

  15 
vote

public DocLaunchPadForXML(){
  newObjects=new ArrayList<Object>();
  editedObjects=new Hashtable<String,Object>();
  deletedObjects=new ArrayList<String>();
  newComments=new ArrayList<Comment>();
  editedComments=new ArrayList<Comment>();
  deletedComments=new ArrayList<String>();
  attatchmentsToupload=new ArrayList<org.xwiki.android.xmodel.entity.Attachment>();
  deletedAttachments=new HashSet<String>();
}
 

Example 43

From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.

Source file: FeatureNegotiationEngine.java

  15 
vote

/** 
 * Run a sasl based login. Most sals parts are handled by {@link SASLEngine#login(XmppInputStream,XmppOutputStream,java.util.Set,XmppAccount)}.
 * @param saslMechanisms Node The DOM node of the sasl mechanisms.
 * @param account XmppAccount The xmpp account to use.
 * @return boolean True on success. False on failore.
 * @throws XmppException On critical connection errors-
 */
protected boolean saslLogin(Node saslMechanisms,XmppAccount account) throws XmppException {
  Log.d("BC/XMPP/Negotiation","SASL Login");
  NodeList nodes=saslMechanisms.getChildNodes();
  HashSet<String> methods=new HashSet<String>(13);
  for (int i=0, l=nodes.getLength(); i < l; i++) {
    Node node=nodes.item(i);
    if (!XMLUtils.isInstance(node,null,"mechanism")) {
      continue;
    }
    methods.add(node.getFirstChild().getNodeValue().toUpperCase().trim());
  }
  if (SASLEngine.login(xmppInput,xmppOutput,methods,account)) {
    xmppInput.detach();
    try {
      xmppOutput.detach();
      xmppInput.attach(inputStream);
      xmppOutput.attach(outputStream,true,false);
    }
 catch (    IllegalArgumentException e) {
      throw new XmppMalformedException("Please report",e);
    }
catch (    IllegalStateException e) {
      throw new XmppMalformedException("Please report",e);
    }
catch (    IOException e) {
      throw new XmppTransportException("Couldn't restart connection",e);
    }
    return true;
  }
  return false;
}
 

Example 44

From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.

Source file: CoastlineAlgorithm.java

  15 
vote

/** 
 * Constructs a new CoastlineAlgorithm instance to generate closed polygons.
 */
CoastlineAlgorithm(){
  this.coastlineWayComparator=new Comparator<CoastlineWay>(){
    @Override public int compare(    CoastlineWay o1,    CoastlineWay o2){
      if (o1.entryAngle > o2.entryAngle) {
        return 1;
      }
      return -1;
    }
  }
;
  this.helperPoints=new HelperPoint[4];
  this.helperPoints[0]=new HelperPoint();
  this.helperPoints[1]=new HelperPoint();
  this.helperPoints[2]=new HelperPoint();
  this.helperPoints[3]=new HelperPoint();
  this.additionalCoastlinePoints=new ArrayList<HelperPoint>(4);
  this.coastlineWays=new ArrayList<CoastlineWay>(4);
  this.coastlineSegments=new ArrayList<float[]>(8);
  this.coastlineEnds=new TreeMap<ImmutablePoint,float[]>();
  this.coastlineStarts=new TreeMap<ImmutablePoint,float[]>();
  this.handledCoastlineSegments=new HashSet<EndPoints>(64);
  this.virtualTileBoundaries=new int[4];
}
 

Example 45

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerApplication.java

  15 
vote

public MobeelizerOperationError login(final String instance,final String user,final String password){
  if (isLoggedIn()) {
    logout();
  }
  Log.i(TAG,"login: " + vendor + ", "+ application+ ", "+ instance+ ", "+ user+ ", "+ password);
  this.instance=instance;
  this.user=user;
  this.password=password;
  MobeelizerLoginResponse status=connectionManager.login();
  Log.i(TAG,"Login result: " + status.getError() + ", "+ status.getRole()+ ", "+ status.getInstanceGuid());
  if (status.getError() != null) {
    this.instance=null;
    this.user=null;
    this.password=null;
    return status.getError();
  }
  role=status.getRole();
  instanceGuid=status.getInstanceGuid();
  group=role.split("-")[0];
  loggedIn=true;
  Set<MobeelizerAndroidModel> androidModels=new HashSet<MobeelizerAndroidModel>();
  for (  MobeelizerModel model : definitionConverter.convert(definition,entityPackage,role)) {
    androidModels.add(new MobeelizerAndroidModel((MobeelizerModelImpl)model,user,group));
  }
  database=new MobeelizerDatabaseImpl(this,androidModels);
  database.open();
  if (status.isInitialSyncRequired()) {
    sync(true);
  }
  return null;
}