Пример #1
1
  /**
   * Update the system, request the assigned emitters update the particles
   *
   * @param delta The amount of time thats passed since last update in milliseconds
   */
  public void update(int delta) {
    if ((sprite == null) && (defaultImageName != null)) {
      loadSystemParticleImage();
    }

    ArrayList removeMe = new ArrayList();
    for (int i = 0; i < emitters.size(); i++) {
      ParticleEmitter emitter = (ParticleEmitter) emitters.get(i);
      if (emitter.isEnabled()) {
        emitter.update(this, delta);
        if (removeCompletedEmitters) {
          if (emitter.completed()) {
            removeMe.add(emitter);
            particlesByEmitter.remove(emitter);
          }
        }
      }
    }
    emitters.removeAll(removeMe);

    pCount = 0;

    if (!particlesByEmitter.isEmpty()) {
      Iterator it = particlesByEmitter.values().iterator();
      while (it.hasNext()) {
        ParticlePool pool = (ParticlePool) it.next();
        for (int i = 0; i < pool.particles.length; i++) {
          if (pool.particles[i].life > 0) {
            pool.particles[i].update(delta);
            pCount++;
          }
        }
      }
    }
  }
  /**
   * Queries the defined tag-descriptions whether the given tag and namespace is defined to allow
   * character-data.
   *
   * @param namespace the namespace.
   * @param tagname the xml-tagname.
   * @return true, if the element may contain character data, false otherwise.
   */
  public boolean hasCData(String namespace, final String tagname) {
    if (tagname == null) {
      throw new NullPointerException();
    }

    if (namespace == null) {
      namespace = defaultNamespace;
    }

    if (tagData.isEmpty() == false) {
      lookupKey.update(namespace, tagname);
      final Object tagVal = tagData.get(lookupKey);
      if (tagVal != null) {
        return Boolean.FALSE.equals(tagVal) == false;
      }
    }

    if (defaultDefinitions.isEmpty()) {
      return true;
    }

    final Object obj = defaultDefinitions.get(namespace);
    if (obj != null) {
      return Boolean.FALSE.equals(obj) == false;
    }

    final Object defaultValue = defaultDefinitions.get(null);
    return Boolean.FALSE.equals(defaultValue) == false;
  }
Пример #3
0
 @Override
 public void sendButtonPressed(int index) {
   if (selectedAlbum != null) {
     if (selectedPhotos.isEmpty()) {
       if (index < 0 || index >= selectedAlbum.photos.size()) {
         return;
       }
       MediaController.PhotoEntry photoEntry = selectedAlbum.photos.get(index);
       selectedPhotos.put(photoEntry.imageId, photoEntry);
     }
   } else if (selectedPhotos.isEmpty()) {
     ArrayList<MediaController.SearchImage> array;
     if (searchResult.isEmpty() && lastSearchString == null) {
       array = recentImages;
     } else {
       array = searchResult;
     }
     if (index < 0 || index >= array.size()) {
       return;
     }
     MediaController.SearchImage photoEntry = array.get(index);
     selectedWebPhotos.put(photoEntry.id, photoEntry);
   }
   sendSelectedPhotos();
 }
Пример #4
0
    /** Displays the labels and the values for the panel. */
    protected void displayPnlFields(HashMap hmPnl) {
      if (hmPnl == null || hmPnl.isEmpty()) return;

      Iterator keySetItr = hmPnl.keySet().iterator();
      String strLabel = "";
      String strValue = "";

      // if the file is empty, then create an empty set of textfields.
      if (hmPnl == null || hmPnl.isEmpty()) {
        displayNewTxf("", "");
        return;
      }

      Container container = getParent();
      if (container != null) container.setVisible(false);
      try {
        // Get each set of label and value, and display them.
        while (keySetItr.hasNext()) {
          strLabel = (String) keySetItr.next();
          strValue = (String) hmPnl.get(strLabel);

          displayNewTxf(strLabel, strValue);
        }

        if (container != null) container.setVisible(true);
        revalidate();
        repaint();
      } catch (Exception e) {
        Messages.writeStackTrace(e);
        // e.printStackTrace();
        Messages.postDebug(e.toString());
      }
    }
Пример #5
0
 private void sendSelectedPhotos() {
   if (selectedPhotos.isEmpty() && selectedWebPhotos.isEmpty()
       || delegate == null
       || sendPressed) {
     return;
   }
   sendPressed = true;
   delegate.actionButtonPressed(false);
   finishFragment();
 }
Пример #6
0
  @SuppressWarnings("deprecation")
  @Override
  public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
    this.br = newBrowser();
    final boolean forceNewLinkGeneration = true;

    synchronized (hostUnavailableMap) {
      HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
      if (unavailableMap != null) {
        Long lastUnavailable = unavailableMap.get(link.getHost());
        if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
          final long wait = lastUnavailable - System.currentTimeMillis();
          throw new PluginException(
              LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE,
              "Host is temporarily unavailable via " + this.getHost(),
              wait);
        } else if (lastUnavailable != null) {
          unavailableMap.remove(link.getHost());
          if (unavailableMap.size() == 0) {
            hostUnavailableMap.remove(account);
          }
        }
      }
    }

    /*
     * When JD is started the first time and the user starts downloads right away, a full login might not yet have happened but it is
     * needed to get the individual host limits.
     */
    synchronized (CTRLLOCK) {
      if (hostMaxchunksMap.isEmpty() || hostMaxdlsMap.isEmpty()) {
        logger.info("Performing full login to set individual host limits");
        this.fetchAccountInfo(account);
      } else {
        login(account, false);
      }
    }
    this.setConstants(account, link);

    String dllink = checkDirectLink(link, NICE_HOSTproperty + "directlink");
    if (dllink == null || forceNewLinkGeneration) {
      /* request creation of downloadlink */
      br.setFollowRedirects(true);
      this.postAPISafe(
          "http://jetdebrid.com/index.php?rand=0." + System.currentTimeMillis(),
          "urllist=" + Encoding.urlEncode(link.getDownloadURL()) + "&captcha=none&");
      dllink = br.getRegex("(https?://[a-z0-9\\-]+\\.jetdebrid\\.com/dl/[^<>\"\\']+)").getMatch(0);
      if (dllink == null) {
        logger.warning("Final downloadlink is null");
        handleErrorRetries("dllinknull", 10, 10 * 60 * 1000l);
      }
    }
    handleDL(account, link, dllink);
  }
  /**
   * This method calculates the differences between the files inside a Jar file and generates an
   * output file. The output only contains the files that have difference in their CRC.
   *
   * @param olderVersionJar - file to be compared to.
   * @param newerVersionJar - source file of the comparisson.
   * @param outputDestination - path to the file that will contain the differences in those Jars.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   * @return true if the output file was generated AND has at least one entry inside it, false
   *     otherwise.
   */
  private static boolean calculate(
      File olderVersionJar, File newerVersionJar, String outputDestination)
      throws ZipException, IOException {
    ZipFile oldZip = new ZipFile(olderVersionJar);
    ZipFile newZip = new ZipFile(newerVersionJar);
    Enumeration oldEntries = oldZip.entries();
    Enumeration newEntries = newZip.entries();

    HashMap<String, Long> map = new HashMap<String, Long>();
    while (newEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) newEntries.nextElement();
      map.put(entry.getName(), entry.getCrc());
    }

    while (oldEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) oldEntries.nextElement();
      Long l = map.get(entry.getName());
      if (l != null && l.longValue() == entry.getCrc()) {
        map.remove(entry.getName());
      }
    }

    if (!map.isEmpty()) {
      ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputDestination));

      Set<Entry<String, Long>> set = map.entrySet();
      Iterator<Entry<String, Long>> it = set.iterator();
      while (it.hasNext()) {
        Entry<String, Long> entry = it.next();
        ZipEntry zipEntry = newZip.getEntry(entry.getKey());
        InputStream is = newZip.getInputStream(zipEntry);
        zos.putNextEntry(zipEntry);
        copyInputStream(is, zos);
        zos.closeEntry();
        is.close();
      }

      zos.flush();
      zos.close();
    }

    oldZip.close();
    newZip.close();

    if (map.isEmpty()) {
      return false;
    } else {
      return true;
    }
  }
  /**
   * Returns false if its the last quad in the quadmap for this node (ie: remove it)
   *
   * @param quad
   * @return
   */
  private boolean removeParticleFromNode(E3DParticle particle) {
    if (!particleMap.containsKey(particle)) return true;

    particleMap.remove(particle);
    particleList.remove(particle);
    return !particleMap.isEmpty();
  }
  public void processClassReferences(ClassNode node) {

    ClassWrapper wrapper = node.wrapper;

    //		int major_version = wrapper.getClassStruct().major_version;
    //		int minor_version = wrapper.getClassStruct().minor_version;
    //
    //		if(major_version > 48 || (major_version == 48 && minor_version > 0)) {
    //			// version 1.5 or above
    //			return;
    //		}

    if (wrapper.getClassStruct().isVersionGE_1_5()) {
      // version 1.5 or above
      return;
    }

    // find the synthetic method Class class$(String) if present
    HashMap<ClassWrapper, MethodWrapper> mapClassMeths = new HashMap<ClassWrapper, MethodWrapper>();
    mapClassMethods(node, mapClassMeths);

    if (mapClassMeths.isEmpty()) {
      return;
    }

    HashSet<ClassWrapper> setFound = new HashSet<ClassWrapper>();
    processClassRec(node, mapClassMeths, setFound);

    if (!setFound.isEmpty()) {
      for (ClassWrapper wrp : setFound) {
        StructMethod mt = mapClassMeths.get(wrp).methodStruct;
        wrp.getHiddenMembers().add(InterpreterUtil.makeUniqueKey(mt.getName(), mt.getDescriptor()));
      }
    }
  }
Пример #10
0
 public String toString() {
   synchronized (tableLock) {
     if (entries.isEmpty()) {
       return "RouteRequestTable is empty\n";
     }
     String returnString =
         "---------------------\n" + "|Route Request Table:\n" + "---------------------";
     for (RouteRequestEntry f : entries.values()) {
       returnString +=
           "\n"
               + "|Dest: "
               + f.getDestinationAddress()
               + " destSeqN: "
               + f.getDestinationSequenceNumber()
               + " src: "
               + f.getSourceAddress()
               + " broadID: "
               + f.getBroadcastID()
               + " retries left: "
               + f.getRetriesLeft()
               + " hopCount: "
               + f.getHopCount()
               + " TTL: "
               + (f.getAliveTimeLeft() - System.currentTimeMillis());
     }
     return returnString + "\n---------------------\n";
   }
 }
Пример #11
0
 /**
  * If rating categories are enabled, get the average rating by category.<br>
  * - The index corresponds to the index of the category in the config
  *
  * @param plot
  * @return
  */
 public static double[] getAverageRatings(Plot plot) {
   HashMap<UUID, Integer> rating;
   if (plot.getSettings().ratings != null) {
     rating = plot.getSettings().ratings;
   } else if (Settings.Enabled_Components.RATING_CACHE) {
     rating = new HashMap<>();
   } else {
     rating = DBFunc.getRatings(plot);
   }
   int size = 1;
   if (!Settings.Ratings.CATEGORIES.isEmpty()) {
     size = Math.max(1, Settings.Ratings.CATEGORIES.size());
   }
   double[] ratings = new double[size];
   if (rating == null || rating.isEmpty()) {
     return ratings;
   }
   for (Map.Entry<UUID, Integer> entry : rating.entrySet()) {
     int current = entry.getValue();
     if (Settings.Ratings.CATEGORIES.isEmpty()) {
       ratings[0] += current;
     } else {
       for (int i = 0; i < Settings.Ratings.CATEGORIES.size(); i++) {
         ratings[i] += current % 10 - 1;
         current /= 10;
       }
     }
   }
   for (int i = 0; i < size; i++) {
     ratings[i] /= rating.size();
   }
   return ratings;
 }
Пример #12
0
  /** Returns an HttpEntity containing all request parameters */
  public HttpEntity getEntity() {

    if (bodyEntity != null) {
      return bodyEntity;
    }

    HttpEntity result = null;

    if (fileParams != null && !fileParams.isEmpty()) {

      MultipartEntity multipartEntity =
          new MultipartEntity(HttpMultipartMode.STRICT, boundary, Charset.forName(charset));

      if (bodyParams != null && !bodyParams.isEmpty()) {
        for (NameValuePair param : bodyParams) {
          try {
            multipartEntity.addPart(param.getName(), new StringBody(param.getValue()));
          } catch (UnsupportedEncodingException e) {
            LogUtils.e(e.getMessage(), e);
          }
        }
      }

      for (ConcurrentHashMap.Entry<String, ContentBody> entry : fileParams.entrySet()) {
        multipartEntity.addPart(entry.getKey(), entry.getValue());
      }

      result = multipartEntity;
    } else if (bodyParams != null && !bodyParams.isEmpty()) {
      result = new BodyParamsEntity(bodyParams, charset);
    }

    return result;
  }
Пример #13
0
  private void getRemouteValues(
      HashMap<String, String> values,
      long customer_id,
      HashMap<String, String> listSqls,
      final boolean datasettings) {
    if (datasettings && listSqls.isEmpty()) {
      setData(values);
      return;
    }
    final HashMap<String, String> valuesFinal = values;
    SplashDialog.showSplash();
    DocFlow.docFlowService.getListTypesForDocument(
        listSqls,
        customer_id,
        new AsyncCallback<HashMap<String, ArrayList<ClSelectionItem>>>() {

          @Override
          public void onFailure(Throwable caught) {
            SplashDialog.hideSplash();
          }

          @Override
          public void onSuccess(HashMap<String, ArrayList<ClSelectionItem>> result) {
            setFieldLists(result, valuesFinal, datasettings);
            SplashDialog.hideSplash();
          }
        });
  }
Пример #14
0
  /**
   * 管理类的接口查询Broker地址,Master优先
   *
   * @param brokerName
   * @return
   */
  public FindBrokerResult findBrokerAddressInAdmin(final String brokerName) {
    String brokerAddr = null;
    boolean slave = false;
    boolean found = false;

    HashMap<Long /* brokerId */, String /* address */> map = this.brokerAddrTable.get(brokerName);
    if (map != null && !map.isEmpty()) {
      // TODO 如果有多个Slave,可能会每次都选中相同的Slave,这里需要优化
      FOR_SEG:
      for (Map.Entry<Long, String> entry : map.entrySet()) {
        Long id = entry.getKey();
        brokerAddr = entry.getValue();
        if (brokerAddr != null) {
          found = true;
          if (MixAll.MASTER_ID == id) {
            slave = false;
            break FOR_SEG;
          } else {
            slave = true;
          }
          break;
        }
      } // end of for
    }

    if (found) {
      return new FindBrokerResult(brokerAddr, slave);
    }

    return null;
  }
  public void testGetTypeInfo() throws Exception {
    String schema =
        "create table Table1 (Column1 varchar(200) not null, Column2 integer);"
            + "partition table Table1 on column Column1;"
            + "create procedure proc1 as select * from Table1 where Column1=?;"
            + "partition procedure proc1 on table Table1 column Column1;"
            + "create procedure proc2 as select * from Table1 where Column2=?;";

    VoltCompiler c = compileForDDLTest2(schema);
    JdbcDatabaseMetaDataGenerator dut =
        new JdbcDatabaseMetaDataGenerator(c.getCatalog(), null, new InMemoryJarfile(testout_jar));
    VoltTable typeInfo = dut.getMetaData("typEINfo");
    System.out.println(typeInfo);
    // just do some minor sanity checks on size of table and that it contains the types
    // we expect
    HashMap<String, VoltType> expectedTypes = new HashMap<String, VoltType>();
    for (VoltType type : VoltType.values()) {
      if (type.isJdbcVisible()) {
        expectedTypes.put(type.toSQLString().toUpperCase(), type);
      }
    }
    assertEquals(expectedTypes.size(), typeInfo.getRowCount());
    assertEquals(18, typeInfo.getColumnCount());
    typeInfo.resetRowPosition();
    while (typeInfo.advanceRow()) {
      String gotName = typeInfo.getString("TYPE_NAME");
      VoltType expectedType = expectedTypes.remove(gotName);
      assertTrue(expectedType != null);
    }
    assertTrue(expectedTypes.isEmpty());
  }
  /** @param position */
  public void switchToFragment(int position) {
    if (position == mCurrentFragmentPosition) {
      return;
    }

    HashMap<Integer, DSFragment> subfragments = getSubFragments();

    if (subfragments.isEmpty()) {

      // sub fragments not yet created
      mCurrentFragmentPosition = position;
      return;
    }

    if (subfragments.get(mOrder.get(mCurrentFragmentPosition)).isActive()) {
      subfragments.get(mOrder.get(mCurrentFragmentPosition)).setActive(false);
    }

    mCurrentFragmentPosition = position;

    if (subfragments.get(mOrder.get(mCurrentFragmentPosition)).isActive() != isActive()) {
      subfragments.get(mOrder.get(mCurrentFragmentPosition)).setActive(isActive());
    }

    showCurrentFragment();

    handleSwitchOptions(isActive());
  }
Пример #17
0
  public static _SparseFeature[] createSpVct(ArrayList<HashMap<Integer, Double>> vcts) {
    HashMap<Integer, _SparseFeature> spVcts = new HashMap<Integer, _SparseFeature>();
    HashMap<Integer, Double> vPtr;
    _SparseFeature spV;

    int dim = vcts.size();
    for (int i = 0; i < dim; i++) {
      vPtr = vcts.get(i);
      if (vPtr == null || vPtr.isEmpty())
        continue; // it is possible that we are missing this dimension

      // iterate through all the features in this section
      Iterator<Entry<Integer, Double>> it = vPtr.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<Integer, Double> pairs = (Map.Entry<Integer, Double>) it.next();
        int index = pairs.getKey();
        double value = pairs.getValue();
        if (spVcts.containsKey(index)) {
          spV = spVcts.get(index);
          spV.addValue(value); // increase the total value
        } else {
          spV = new _SparseFeature(index, value, dim);
          spVcts.put(index, spV);
        }
        spV.setValue4Dim(value, i);
      }
    }

    int size = spVcts.size();
    _SparseFeature[] resultVct = spVcts.values().toArray(new _SparseFeature[size]);

    Arrays.sort(resultVct);
    return resultVct;
  }
Пример #18
0
 /**
  * If empty, will return false.
  *
  * @return true if all values are equal to the given integer.
  */
 public boolean allValuesEqual(final int integer) {
   if (m_values.isEmpty()) return false;
   for (final int value : m_values.values()) {
     if (integer != value) return false;
   }
   return true;
 }
  private synchronized CacheDownload getNextRedditInQueue() {

    while (redditDownloadsQueued.isEmpty()) {
      try {
        wait();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    CacheDownload next = null;
    RequestIdentifier nextKey = null;

    for (final Map.Entry<RequestIdentifier, CacheDownload> entry :
        redditDownloadsQueued.entrySet()) {
      if (next == null || entry.getValue().isHigherPriorityThan(next)) {
        next = entry.getValue();
        nextKey = entry.getKey();
      }
    }

    redditDownloadsQueued.remove(nextKey);
    downloadsInProgress.put(nextKey, next);

    return next;
  }
Пример #20
0
 /**
  * Worker method called by the retry processing timer. This checks any reliable messages that have
  * not yet had an acknowledgement (or explicit error) to see if they need retrying, or if they are
  * due for expiry. Any expired messages have the expiry process, including any user-supplied
  * expiry handler, called on them.
  *
  * <p>It also requests that the listener checks its de-duplication list against persist durations,
  * and clears out any message ids from that list that are out of scope.
  */
 void processRetries() {
   if ((requests == null) || (requests.isEmpty())) {
     listener.cleanDeduplicationList();
     return;
   }
   Calendar check = Calendar.getInstance();
   ArrayList<Sendable> expires = new ArrayList<>();
   for (Sendable s : requests.values()) {
     Calendar expiryTime = s.getStarted();
     expiryTime.add(Calendar.SECOND, s.getPersistDuration());
     if (expiryTime.before(check)) {
       expires.add(s);
     } else {
       Calendar retryAfter = s.lastTry();
       if (retryAfter == null) return;
       retryAfter.add(Calendar.SECOND, s.getRetryInterval());
       if (retryAfter.before(check)) {
         (new Transmitter(s)).start();
       }
     }
   }
   for (Sendable s : expires) {
     try {
       removeRequest(s.getMessageId());
       s.expire();
     } catch (Exception e) {
       SpineToolsLogger.getInstance()
           .log("org.warlock.spine.connection.ConnectionManager.expireException", e);
     }
   }
 }
  @Override
  public void actionPerformed(ActionEvent ae) {
    // align components to grid
    HashMap<HwComponentGraphic, Dimension> movedComponentsMap;

    GraphOuterInterface graph = drawPanel.getGraphOuterInterface();

    if (graph.getMarkedAbstractHWComponentsCount() > 0) {
      movedComponentsMap = graph.doAlignMarkedComponentsToGrid();
    } else {
      movedComponentsMap = graph.doAlignComponentsToGrid();
    }

    graph.doUnmarkAllComponents();

    // if map not empty set undoable edit
    if (!movedComponentsMap.isEmpty()) {
      // add to undo manager
      undoManager.undoableEditHappened(
          new UndoableEditEvent(
              this, new UndoableChagePositionOfAllComponents(graph, movedComponentsMap)));

      // update Undo and Redo buttons
      mainWindow.updateUndoRedoButtons();
    }
    // repaint draw Panel
    drawPanel.repaint();
  }
Пример #22
0
 /**
  * Dump du contenu d'une Hashmap.
  *
  * @param h La map a dumper
  * @return La représentation textuelle
  */
 public static String dump(final HashMap h) {
   final StringBuffer sb = new StringBuffer("");
   Object item = null;
   if (h == null) {
     sb.append("Variable non initialisée (null)");
   } else {
     if (h.isEmpty()) {
       sb.append("Tableau vide");
     } else {
       final Vector v = new Vector(h.keySet());
       Collections.sort(v);
       final Iterator iterator = v.iterator();
       sb.append("Nombre d'elements <" + h.size() + ">\n");
       while (iterator.hasNext()) {
         item = iterator.next();
         sb.append("<");
         sb.append(item.toString());
         sb.append("> = <");
         sb.append(h.get(item).toString());
         sb.append(">\n");
       }
     }
   }
   return (sb.toString());
 }
Пример #23
0
  /**
   * 将QQ表情、图片、自定义表情按类型进行汇总。
   *
   * @param exts
   * @return
   */
  public static Map<String, LinkedList<String>> sort(HashMap<String, String> exts) {
    if (exts != null && !exts.isEmpty()) {
      Map<String, LinkedList<String>> map = new HashMap<String, LinkedList<String>>();
      TreeMap<String, String> sortExts =
          new TreeMap<String, String>(exts); // 先按Key进行顺序排序(因为表情是按顺序添加的,图片等也是如此)

      for (Entry<String, String> entry : sortExts.entrySet()) {
        String key = entry.getKey();
        String prefix = null;
        if (key.contains(MessageDetail.FACE_PREFIX)) {
          prefix = MessageDetail.FACE_PREFIX;
        } else if (key.contains(MessageDetail.OFFPIC_PREFIX)) {
          prefix = MessageDetail.OFFPIC_PREFIX;
        } else if (key.contains(MessageDetail.CFACE_PREFIX)) {
          prefix = MessageDetail.CFACE_PREFIX;
        }

        if (prefix == null) continue;
        LinkedList<String> values = map.get(prefix);
        if (values == null) {
          values = new LinkedList<String>();
        }

        values.add(entry.getValue());
        map.put(prefix, values);
      }

      if (map.isEmpty()) {
        map = null;
      }
      return map;
    }
    return null;
  }
Пример #24
0
  @Override
  public void onClick(View v) {
    if (v.getId() == R.id.app_connect_button) {
      // Intent intent = new Intent(getBaseContext(), CollectDataActivity.class);
      // startActivity(intent);;
      BluetoothHelper bluetoothHelper = BluetoothHelper.getInstance();
      final HashMap<String, String> pairedDevices = bluetoothHelper.GetPairedDevices();

      if (pairedDevices.isEmpty())
        Toast.makeText(this, "No paired devices found.", Toast.LENGTH_LONG).show();
      else
        SimpleDialogs.ChooseOption(
            this,
            pairedDevices.keySet().toArray(new String[pairedDevices.keySet().size()]),
            new DialogResponse() {
              @Override
              public void onDialogResponse(String deviceName) {
                String deviceAddress = pairedDevices.get(deviceName);
                Toast.makeText(
                        EntranceActivity.this, "Choosed device:" + deviceAddress, Toast.LENGTH_LONG)
                    .show();
                EntranceActivity.this.ConnectDevice(deviceAddress);
              }
            });
    }

    if (v.getId() == R.id.app_last_trips_button) {
      Intent intent = new Intent(getBaseContext(), LastTripsActivity.class);
      startActivity(intent);
    }
  }
Пример #25
0
  /** 订阅消息过程中,寻找Broker地址,取Master还是Slave由参数决定 */
  public FindBrokerResult findBrokerAddressInSubscribe( //
      final String brokerName, //
      final long brokerId, //
      final boolean onlyThisBroker //
      ) {
    String brokerAddr = null;
    boolean slave = false;
    boolean found = false;

    HashMap<Long /* brokerId */, String /* address */> map = this.brokerAddrTable.get(brokerName);
    if (map != null && !map.isEmpty()) {
      brokerAddr = map.get(brokerId);
      slave = (brokerId != MixAll.MASTER_ID);
      found = (brokerAddr != null);

      // 尝试寻找其他Broker
      if (!found && !onlyThisBroker) {
        Entry<Long, String> entry = map.entrySet().iterator().next();
        brokerAddr = entry.getValue();
        slave = (entry.getKey() != MixAll.MASTER_ID);
        found = true;
      }
    }

    if (found) {
      return new FindBrokerResult(brokerAddr, slave);
    }

    return null;
  }
Пример #26
0
  private void findSerialPortDevice() {
    // This snippet will try to open the first encountered usb device connected, excluding usb root
    // hubs
    HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
    if (!usbDevices.isEmpty()) {
      boolean keep = true;
      for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
        device = entry.getValue();
        int deviceVID = device.getVendorId();
        int devicePID = device.getProductId();

        if (deviceVID != 0x1d6b
            && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
          // There is a device connected to our Android device. Try to open it as a Serial Port.
          requestUserPermission();
          keep = false;
        } else {
          connection = null;
          device = null;
        }

        if (!keep) break;
      }
      if (!keep) {
        // There is no USB devices connected (but usb host were listed). Send an intent to
        // MainActivity.
        Intent intent = new Intent(ACTION_NO_USB);
        sendBroadcast(intent);
      }
    } else {
      // There is no USB devices connected. Send an intent to MainActivity
      Intent intent = new Intent(ACTION_NO_USB);
      sendBroadcast(intent);
    }
  }
Пример #27
0
  @SuppressWarnings("unchecked")
  private boolean compareAttributes(Iterator attributes1, Iterator attributes2) {
    /*
     * Compare attributes in no order
     */

    /*
     * Put the attributes1 into a map by qname
     * For each element in attributes2 isEqual against the set and remove
     * If there are any left in the set then non-equal otherwise equal
     */

    HashMap<QName, Attribute> set = new HashMap<QName, Attribute>();
    while (attributes1.hasNext()) {
      Attribute attr = (Attribute) attributes1.next();

      set.put(attr.getName(), attr);
    }
    while (attributes2.hasNext()) {
      Attribute attr2 = (Attribute) attributes2.next();
      Attribute attr1 = set.remove(attr2.getName());
      if (attr1 == null) return false;
      if (!isEqual(attr1, attr2)) return false;
    }

    return set.isEmpty();
  }
Пример #28
0
 public static String restoreJsStateInitializer(String sessionId, String uniqueId) {
   if (!jsStateInitializersBySessionId.containsKey(sessionId)) {
     return "";
   }
   HashMap<String, String> h = jsStateInitializersBySessionId.get(sessionId);
   if (h.isEmpty()) {
     return "";
   }
   StringBuffer sb = new StringBuffer();
   for (Map.Entry<String, String> entry : h.entrySet()) {
     final String jsVarName = entry.getKey();
     final String jsStateInitializer = entry.getValue();
     sb.append(jsStateInitializer).append('\n');
     log.fine(
         "Restoring JavaScript state for session "
             + sessionId
             + "/"
             + uniqueId
             + ": key="
             + jsVarName
             + ": "
             + jsStateInitializer);
   }
   return sb.toString();
 }
 @Override
 public HashMap<String, String> loadKey(String username) {
   logger.info("loading password for username {}", username);
   HashMap<String, String> ret = new HashMap<>();
   String riverIndexName = getRiverIndexName();
   refreshSearchIndex(riverIndexName);
   GetResponse resp =
       client.prepareGet(riverIndexName, riverName().name(), "_pwd").execute().actionGet();
   if (resp.isExists()) {
     if (logger.isDebugEnabled()) {
       logger.debug("Password document: {}", resp.getSourceAsString());
     }
     Map<String, Object> newset = resp.getSource();
     Set<String> keys = newset.keySet();
     for (String s : keys) {
       logger.info(
           "Added key {} with a value of {}",
           s,
           XContentMapValues.nodeStringValue(newset.get(s), null));
       ret.put(s, XContentMapValues.nodeStringValue(newset.get(s), null));
     }
   }
   if (ret.isEmpty()) {
     return null;
   }
   return ret;
 }
Пример #30
0
  public static DnsResource create(Set<String> flags, HashMap<String, String> params, URI uri) {
    if (!("dns".equals(uri.getScheme())
        && (flags == null || flags.isEmpty())
        && (params == null || params.isEmpty()))) {
      return null;
    }

    //
    String spec = uri.getSchemeSpecificPart();
    // If there are // at the beginning, this includes an authority - we don't support those!
    if (spec.startsWith("//")) {
      return null;
    }

    String[] pieces = spec.split("\\?", 2);
    // In either case, part before a ? is the fqdn
    String fqdn = pieces[0];
    // There may be a query part
    /*
    if (pieces.length > 1) {
        // parse CLASS and TYPE query paramters
    }
    */

    CLASS clazz = CLASS.IN;
    TYPE type = TYPE.TXT;

    return new DnsResource(flags, params, uri, fqdn, clazz, type);
  }