예제 #1
0
 private static int safelyConnect(String uri, HttpURLConnection connection) throws IOException {
   try {
     connection.connect();
   } catch (NullPointerException npe) {
     // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(npe.toString());
   } catch (IllegalArgumentException iae) {
     // Also seen this in the wild, not sure what to make of it. Probably a bad URL
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(iae.toString());
   } catch (SecurityException se) {
     // due to bad VPN settings?
     Log.w(TAG, "Restricted URI? " + uri);
     throw new IOException(se.toString());
   } catch (IndexOutOfBoundsException ioobe) {
     // Another Android problem?
     // https://groups.google.com/forum/?fromgroups#!topic/google-admob-ads-sdk/U-WfmYa9or0
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(ioobe.toString());
   }
   try {
     return connection.getResponseCode();
   } catch (NullPointerException npe) {
     // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
     Log.w(TAG, "Bad URI? " + uri);
     throw new IOException(npe.toString());
   } catch (IllegalArgumentException iae) {
     // Again seen this in the wild for bad header fields in the server response! or bad reads
     Log.w(TAG, "Bad server status? " + uri);
     throw new IOException(iae.toString());
   }
 }
예제 #2
0
  /**
   * @param data the data to store into the buffer
   * @param glBindType where OpenGL binds the buffer
   * @param glDrawType the way OpenGL draws the buffer
   */
  public GLBuffer(ArrayList<N> data, int glBindType, int glDrawType) {
    // First call super constructor
    this(data);

    String bindErr = "BIND";
    String drawErr = "DRAW";
    try {
      // Set fields
      this.glDrawType = GLDrawType.getType(glDrawType);
      this.glBindType = GLBindType.getType(glBindType);

      if (this.glBindType == null || this.glDrawType == null) {
        // Creates a string that indicates which values are null
        throw new NullPointerException(
            (this.glBindType == null ? bindErr : "") + (this.glDrawType == null ? drawErr : ""));
      }
    } catch (NullPointerException ex) {
      System.out.println("Could not match input to enumeration, setting necessary default values.");

      // Set to default whichever field was not configured correctly
      String errorStr = ex.toString();
      // Bind getType
      if (errorStr.contains(bindErr)) {
        System.err.println("glBindType does not match an enumerated type");
        this.glBindType = DEFAULT_BIND;

        // Draw getType
      } else if (errorStr.contains(drawErr)) {
        System.err.println("glDrawType does not match an enumerated type");
        this.glDrawType = DEFAULT_DRAW;
      }
    }
  }
 @Test
 public void testNotFoundExceptionCause() {
   final NullPointerException npe = new NullPointerException("Embedded");
   final NotFoundException ex = new NotFoundException(npe);
   assertEquals(npe, ex.getCause());
   assertEquals(npe.toString(), ex.getMessage());
 }
  public void setCertificate(String KeyStore, String KeyPass, String TrustStore, String TrustPass) {
    this.keyStore = KeyStore;
    this.keyPass = KeyPass;
    this.trustStore = TrustStore;
    this.trustPass = TrustPass;

    try {
      ClassLoader loader = getClass().getClassLoader();
      String certificate = "";
      URL kURL = loader.getResource("certificate/" + KeyStore);
      certificate = kURL.toString().replace("file:/", "");
      System.setProperty("javax.net.ssl.keyStore", certificate);
      System.setProperty("javax.net.ssl.keyStorePassword", KeyPass);
      System.setProperty("javax.net.ssl.keyStoreType", "JKS");

      URL tURL = loader.getResource("certificate/" + TrustStore);
      certificate = tURL.toString().replace("file:/", "");
      System.setProperty("javax.net.ssl.trustStore", certificate);
      System.setProperty("javax.net.ssl.trustStorePassword", TrustPass);
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    } catch (NullPointerException e) {
      e.printStackTrace();
      logger.error(e.toString());
    }
  }
예제 #5
0
  /** Processes requests made to the server and forwards them to the appropriate event listener. */
  public void run() {
    try {

      boolean done = false;
      while (!done && !mClosed) {
        int requestType = mInput.read();
        switch (requestType) {
          case ObexHelper.OBEX_OPCODE_CONNECT:
            handleConnectRequest();
            break;

          case ObexHelper.OBEX_OPCODE_DISCONNECT:
            handleDisconnectRequest();
            done = true;
            break;

          case ObexHelper.OBEX_OPCODE_GET:
          case ObexHelper.OBEX_OPCODE_GET_FINAL:
            handleGetRequest(requestType);
            break;

          case ObexHelper.OBEX_OPCODE_PUT:
          case ObexHelper.OBEX_OPCODE_PUT_FINAL:
            handlePutRequest(requestType);
            break;

          case ObexHelper.OBEX_OPCODE_SETPATH:
            handleSetPathRequest();
            break;
          case ObexHelper.OBEX_OPCODE_ABORT:
            handleAbortRequest();
            break;

          case -1:
            done = true;
            break;

          default:

            /*
             * Received a request type that is not recognized so I am
             * just going to read the packet and send a not implemented
             * to the client
             */
            int length = mInput.read();
            length = (length << 8) + mInput.read();
            for (int i = 3; i < length; i++) {
              mInput.read();
            }
            sendResponse(ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED, null);
        }
      }

    } catch (NullPointerException e) {
      Log.d(TAG, e.toString());
    } catch (Exception e) {
      Log.d(TAG, e.toString());
    }
    close();
  }
예제 #6
0
 public synchronized float getOptionChoicePrice(String opsetName) {
   float optionChoicePrice = 0.0f;
   try {
     optionChoicePrice = opsetList.get(opsetName).getOptionChoice().getPrice();
   } catch (NullPointerException e) {
     System.out.println(e.toString());
   }
   return optionChoicePrice;
 }
예제 #7
0
 public synchronized String getOptionChoice(String opsetName) {
   String optionChoice = null;
   try {
     optionChoice = opsetList.get(opsetName).getOptionChoice().getName();
   } catch (NullPointerException e) {
     System.out.println(e.toString());
   }
   return optionChoice;
 }
 @Test
 public void testDontThrowNPEInShfill() throws IOException {
   PDDocument pdf_document = PDDocument.load("src/test/resources/technology/tabula/labor.pdf");
   ObjectExtractor oe = new ObjectExtractor(pdf_document);
   PageIterator pi = oe.extract();
   try {
     Page p = pi.next();
   } catch (NullPointerException e) {
     fail("NPE in ObjectExtractor " + e.toString());
   }
 }
예제 #9
0
 private static HttpURLConnection safelyOpenConnection(URL url) throws IOException {
   URLConnection conn;
   try {
     conn = url.openConnection();
   } catch (NullPointerException npe) {
     // Another strange bug in Android?
     Log.w(TAG, "Bad URI? " + url);
     throw new IOException(npe.toString());
   }
   if (!(conn instanceof HttpURLConnection)) {
     throw new IOException();
   }
   return (HttpURLConnection) conn;
 }
예제 #10
0
  /**
   * Deletes a record from the Database Server using the provided delete request.
   *
   * @param request The delete request.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public Result delete(DeleteRequest request) throws ErrorResultException {
    Result r;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final RDN rDN = DN.rdn();
      final String filterAttributeName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
      final String filterAttributeValue = rDN.getFirstAVA().getAttributeValue().toString();
      final RDN OU = DN.parent(1).rdn();
      final String OUName = OU.getFirstAVA().getAttributeValue().toString();
      final String baseDN = DN.parent(2).toString();

      // Search mapping for the corresponding table and column names.
      final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

      if (tableName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching table name for OU: '"
                + OUName
                + "' in DN: '"
                + baseDN
                + "'. Please check if mapping was succesful.");
      final String columnName =
          jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

      if (columnName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching column name for attribute: '"
                + filterAttributeName
                + "'. Please check if mapping was succesful.");

      // Build the SQL query.
      final Statement st = connection.createStatement();
      final String sql =
          "DELETE FROM " + tableName + " WHERE " + columnName + "='" + filterAttributeValue + "'";
      st.executeUpdate(sql);
      r = Responses.newResult(ResultCode.SUCCESS);
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      r = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    }
    return r;
  }
예제 #11
0
  public static void generate_preview_for_torrent(TOTorrent created, File file)
      throws TOTorrentException {

    logger.finer("generating preview..2.");
    try {
      File largestFile = null;
      long largest = 0;
      for (TOTorrentFile f : created.getFiles()) {
        if (f == null) {
          continue;
        }

        if (InOrderType.getType(f.getRelativePath()) == null) {
          continue;
        }
        if (f.getLength() > largest) {
          largest = f.getLength();
          if (file.isDirectory() == false) {
            largestFile = new File(file.getParent(), f.getRelativePath());
          } else {
            largestFile = new File(file, f.getRelativePath());
          }
        }
      }

      if (largestFile != null) {
        logger.finer("largest is: " + largestFile.getAbsolutePath());
      }

      try {
        FFMpegAsyncOperationManager.getInstance()
            .getPreviewImage(created.getHash(), largestFile, 10, TimeUnit.SECONDS);
      } catch (TorrentException e) {
        // this should never happen...
        e.printStackTrace();
      } catch (DataNotAvailableException e) {
        logger.finest("unable to create preview for file: " + largest);
      }
    } catch (NullPointerException e) {
      logger.warning("Preview generation null pointer: " + e.toString());
      e.printStackTrace();
    }
  }
예제 #12
0
    public CommandResult runWaitFor(final String s) {
      final Process process = run(s);
      Integer exit_value = null;
      String stdout = null;
      String stderr = null;
      if (process != null) {
        try {
          exit_value = process.waitFor();

          stdout = getStreamLines(process.getInputStream());
          stderr = getStreamLines(process.getErrorStream());

        } catch (final InterruptedException e) {
          Log.e(TAG, "runWaitFor " + e.toString());
        } catch (final NullPointerException e) {
          Log.e(TAG, "runWaitFor " + e.toString());
        }
      }
      return new CommandResult(exit_value, stdout, stderr);
    }
예제 #13
0
  public void onTrackStyleChanged(int color, int width, int colorshadow, double shadowradius) {
    final JSONObject json = new JSONObject();
    try {
      json.put(Track.COLOR, color);
      json.put(Track.COLORSHADOW, colorshadow);
      json.put(Track.WIDTH, width);
      json.put(Track.SHADOWRADIUS, shadowradius);
    } catch (JSONException e) {
      Ut.e(e.toString(), e);
    }

    if (isPersistent()) {
      persistString(json.toString());
    }
    mValue = json.toString();
    setPreviewColor(color, width, colorshadow, shadowradius);
    try {
      getOnPreferenceChangeListener().onPreferenceChange(this, color);
    } catch (NullPointerException e) {
      Ut.e(e.toString(), e);
    }
  }
예제 #14
0
  // Currently binary message only
  public MessageInfo(XWalkExternalExtension extension, int instanceId, byte[] message) {
    mExtension = extension;
    mInstanceId = instanceId;
    mCmd = "invokeNative";
    try {
      mArgs = null;
      ByteBuffer buf = ByteBuffer.wrap(message);
      if (buf.order() != ByteOrder.LITTLE_ENDIAN) {
        buf.order(ByteOrder.LITTLE_ENDIAN);
      }

      int byteOffset = buf.position();
      int byteCountOfInt = Integer.SIZE / Byte.SIZE;
      int funcNameLen = buf.getInt(byteOffset);
      int alignedFuncNameLen = AlignedWith4Bytes(funcNameLen);
      byteOffset += byteCountOfInt;
      mJsName = new String(message, byteOffset, funcNameLen);

      byteOffset += alignedFuncNameLen;
      mCallbackId = Integer.toString(buf.getInt(byteOffset));

      byteOffset += byteCountOfInt;
      int objectIdLen = buf.getInt(byteOffset);
      int alignedObjectIdLen = AlignedWith4Bytes(objectIdLen);
      byteOffset += byteCountOfInt;
      mObjectId = new String(message, byteOffset, objectIdLen);

      byteOffset += alignedObjectIdLen;
      int len = message.length - byteOffset;
      mBinaryArgs = ByteBuffer.wrap(message, byteOffset, len);
    } catch (IndexOutOfBoundsException e) {
      Log.e(TAG, e.toString());
    } catch (NullPointerException e) {
      Log.e(TAG, e.toString());
    }
  }
예제 #15
0
  /**
   * Compares a record in the Database Server using the provided compare request.
   *
   * @param request The compare request.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public CompareResult compare(final CompareRequest request) throws ErrorResultException {
    CompareResult cr;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final RDN rDN = DN.rdn();
      final String filterAttributeName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
      final String filterAttributeValue = rDN.getFirstAVA().getAttributeValue().toString();
      final RDN OU = DN.parent(1).rdn();
      final String OUName = OU.getFirstAVA().getAttributeValue().toString();
      final String baseDN = DN.parent(2).toString();

      // Search mapping for the corresponding table and column names.
      final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

      if (tableName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching table name for OU: '"
                + OUName
                + "' in DN: '"
                + baseDN
                + "'. Please check if mapping was succesful.");
      final String columnName =
          jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

      if (columnName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching column name for attribute: '"
                + filterAttributeName
                + "'. Please check if mapping was succesful.");

      // Search mapping for the corresponding column name for the comparing attribute.
      final String compareAttributeName = request.getAttributeDescription().toString();
      final String compareAttributeValue = request.getAssertionValueAsString();
      final String compareColumnName =
          jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, compareAttributeName);

      if (compareColumnName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching column name for attribute: '"
                + compareAttributeName
                + "'. Please check if mapping was succesful.");

      // Build the SQL query.
      final Statement st = connection.createStatement();
      final String sql =
          "SELECT * FROM "
              + tableName
              + " WHERE "
              + columnName
              + "='"
              + filterAttributeValue
              + "' AND "
              + compareColumnName
              + "='"
              + compareAttributeValue
              + "'";
      final ResultSet rs = st.executeQuery(sql);
      if (rs.first()) cr = Responses.newCompareResult(ResultCode.COMPARE_TRUE);
      else cr = Responses.newCompareResult(ResultCode.COMPARE_FALSE);
    } catch (SQLException e) {
      System.out.println(e.toString());
      cr = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      cr.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      cr = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      cr.setCause(e);
    }
    return cr;
  }
예제 #16
0
  /**
   * Adds a record to the Database Server using the provided add request.
   *
   * @param request The add request.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public Result add(final AddRequest request) throws ErrorResultException {
    Result r;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final RDN rDN = DN.rdn();
      final String rDNName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
      final String rDNValue = rDN.getFirstAVA().getAttributeValue().toString();
      final RDN OU = DN.parent().rdn();
      final String organizationalUnitName = OU.getFirstAVA().getAttributeValue().toString();
      final String baseDN = DN.parent(2).toString();

      // Search mapping for the corresponding table and column names.
      final String tableName = jdbcm.getTableNameFromMapping(baseDN, organizationalUnitName);

      if (tableName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching table name for OU: '"
                + organizationalUnitName
                + "' in DN: '"
                + baseDN
                + "'. Please check if mapping was succesful.");
      final String rDNColumnName =
          jdbcm.getColumnNameFromMapping(tableName, baseDN, organizationalUnitName, rDNName);

      if (rDNColumnName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching column name for attribute: '"
                + rDNName
                + "'. Please check if mapping was succesful.");
      final Map<String, Object> columnValuesMap = new HashMap<String, Object>();
      final Iterable<Attribute> attributesCollection = request.getAllAttributes();
      final Iterator<Attribute> attributeIter = attributesCollection.iterator();

      // Search mapping for the corresponding column name for each attribute.
      while (attributeIter.hasNext()) {
        final Attribute att = attributeIter.next();
        final Iterator<ByteString> valueIter = att.iterator();
        final String attributeName = att.getAttributeDescriptionAsString();

        if (attributeName == "objectClass") continue;
        final String columnName =
            jdbcm.getColumnNameFromMapping(
                tableName, baseDN, organizationalUnitName, attributeName);

        if (columnName == null)
          throw new NullPointerException(
              "JDBC Error: Could not find matching column name for attribute: '"
                  + attributeName
                  + "'. Please check if mapping was succesful.");
        String columnValue = "";

        while (valueIter.hasNext()) {
          columnValue = columnValue.concat(valueIter.next().toString());
        }
        columnValuesMap.put(columnName, columnValue);
      }

      // Build the SQL values String.
      final ArrayList<String> columnList = jdbcm.getTableColumns(tableName);
      String columnNamesString = " (" + rDNColumnName;
      String columnValuesString = " ('" + rDNValue + "'";

      for (int i = 0; i < columnList.size(); i++) {
        final String columnName = columnList.get(i);

        if (columnNamesString.contains(columnName)) continue;
        final Object columnDataType = jdbcm.getTableColumnDataType(tableName, columnName);
        Object columnValue = columnValuesMap.get(columnName);

        if (columnValue == null) {
          boolean columnNullable = jdbcm.getTableColumnNullable(tableName, columnName);

          if (columnNullable) continue;

          if (columnDataType.equals(Integer.class)) columnValue = "0";
          else columnValue = "Default Value";
        }

        if (columnDataType.equals(Integer.class))
          columnValue = Integer.parseInt(columnValue.toString());
        columnNamesString = columnNamesString.concat(", " + columnName);
        columnValuesString = columnValuesString.concat(", '" + columnValue + "'");
      }
      columnNamesString = columnNamesString.concat(")");
      columnValuesString = columnValuesString.concat(")");

      // Build the SQL query.
      final Statement st = connection.createStatement();
      final String sql =
          "INSERT INTO " + tableName + columnNamesString + " VALUES" + columnValuesString;
      st.executeUpdate(sql);
      r = Responses.newResult(ResultCode.SUCCESS);
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    }
    return r;
  }
예제 #17
0
  /**
   * Search the Database Server using the provided search request.
   *
   * @param request The search request.
   * @param handler A search result handler which can be used to asynchronously process the search
   *     result entries and references as they are received, may be null.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public Result search(SearchRequest request, SearchResultHandler handler)
      throws ErrorResultException {
    Result r;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final int DNSize = DN.size();
      final String baseDN = DN.parent(DNSize - 2).toString();
      RDN OU = null;
      RDN rDN = null;
      String OUName = "";
      String rDNAttributeName = "";
      String rDNAttributeValue = "";

      if (DNSize > 3) {
        OU = DN.parent(1).rdn();
        OUName = OU.getFirstAVA().getAttributeValue().toString();
        rDN = DN.parent(0).rdn();
        rDNAttributeName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
        rDNAttributeValue = rDN.getFirstAVA().getAttributeValue().toString();
      } else if (DNSize > 2) {
        OU = DN.parent(0).rdn();
        OUName = OU.getFirstAVA().getAttributeValue().toString();
      }
      List<String> returnAttributeNames = request.getAttributes();
      final List<String> removeAttributesList = new ArrayList<String>();

      // Get all column names to be returned to return full records.
      if (returnAttributeNames == null) {
        if (OU != null) {
          returnAttributeNames = jdbcm.getOrganizationalUnitAttributes(baseDN, OUName);

          if (returnAttributeNames == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching attributes in OU: '" + OUName + "'.");
          final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

          for (Iterator<String> iterAttributes = returnAttributeNames.iterator();
              iterAttributes.hasNext(); ) {
            String returnAttributeName = iterAttributes.next();
            final String returnColumnName =
                jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

            if (returnColumnName == null) removeAttributesList.add(returnAttributeName);
          }
          returnAttributeNames.removeAll(removeAttributesList);
        } else {
          final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

          if (OUList == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching organizational units in DN: '"
                    + baseDN
                    + "'.");

          for (Iterator<String> iterOU = OUList.iterator(); iterOU.hasNext(); ) {
            OUName = iterOU.next();
            final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);
            returnAttributeNames = jdbcm.getOrganizationalUnitAttributes(baseDN, OUName);

            for (Iterator<String> iterAttributes = returnAttributeNames.iterator();
                iterAttributes.hasNext(); ) {
              String returnAttributeName = iterAttributes.next();
              final String returnColumnName =
                  jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

              if (returnColumnName == null) removeAttributesList.add(returnAttributeName);
            }
            returnAttributeNames.removeAll(removeAttributesList);
          }
        }
      }
      // Convert the search filter.
      final Filter searchFilter = request.getFilter();
      final String convertedFilterString = convertSearchFilter(searchFilter, baseDN, OUName);

      if (convertedFilterString.startsWith("Err:")) {
        String[] errorStringSplitter = convertedFilterString.split("Err:");
        throw new NullPointerException(errorStringSplitter[1]);
      }
      final List<String> returnColumnNames = new ArrayList<String>();

      // Search mapping for the corresponding column name for each return attribute.
      for (Iterator<String> iter = returnAttributeNames.iterator(); iter.hasNext(); ) {

        if (OU == null) {
          final String returnAttributeName = iter.next();
          final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

          if (OUList == null)
            throw new NullPointerException(
                "JDBC Error: Could not find any matching organizational units in DN: '"
                    + baseDN
                    + "'.");

          for (Iterator<String> iterOU = OUList.iterator(); iterOU.hasNext(); ) {
            OUName = iterOU.next();
            final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);
            final String returnColumnName =
                jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

            if (returnColumnName == null) continue;
            else returnColumnNames.add(returnColumnName);
            break;
          }
        } else {
          final String returnAttributeName = iter.next();
          final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

          if (tableName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching table name for OU: '"
                    + OUName
                    + "' in DN: '"
                    + baseDN
                    + "'. Please check if mapping was succesful.");
          final String returnColumnName =
              jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, returnAttributeName);

          if (returnColumnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + returnAttributeName
                    + "'. Please check if mapping was succesful.");
          returnColumnNames.add(returnColumnName);
        }
      }

      String selectString = "";
      String fromString = "";
      String whereString = convertedFilterString;

      if (returnAttributeNames.isEmpty()) selectString = "*";

      // Build the SQL SELECT string.
      if (OU == null) {
        final List<String> OUList = jdbcm.getOrganizationalUnits(baseDN);

        if (OUList == null)
          throw new NullPointerException(
              "JDBC Error: Could not find any matching organizational units in DN: '"
                  + baseDN
                  + "'.");

        for (int i = 0; i < OUList.size(); i++) {
          final String currentOU = OUList.get(i);
          final String currentTable = jdbcm.getTableNameFromMapping(baseDN, currentOU);

          if (currentTable == null) continue;
          final List<String> currentTableColumnNames = jdbcm.getTableColumns(currentTable);

          if (!fromString.isEmpty()) fromString = fromString.concat(",");
          fromString = fromString.concat(currentTable);

          for (int j = 0; j < returnColumnNames.size(); j++) {
            final String returnColumnName = returnColumnNames.get(j);

            if (currentTableColumnNames.contains(returnColumnName)) {

              if (!selectString.isEmpty()) selectString = selectString.concat(",");
              selectString = selectString.concat(currentTable + "." + returnColumnName);
            }
          }
        }
      } else {
        final String selectTable = jdbcm.getTableNameFromMapping(baseDN, OUName);
        if (selectTable == null)
          throw new NullPointerException(
              "JDBC Error: Could not find matching table name for OU: '"
                  + OUName
                  + "' in DN: '"
                  + baseDN
                  + "'. Please check if mapping was succesful.");

        fromString = fromString.concat(selectTable);

        for (int j = 0; j < returnColumnNames.size(); j++) {
          final String returnColumnName = returnColumnNames.get(j);

          if (returnColumnName == null) continue;

          if (!selectString.isEmpty()) selectString = selectString.concat(",");
          selectString = selectString.concat(returnColumnName);
        }

        if (rDN != null) {
          final String columnName =
              jdbcm.getColumnNameFromMapping(selectTable, baseDN, OUName, rDNAttributeName);

          if (columnName == null)
            throw new NullPointerException(
                "JDBC Error: Could not find matching column name for attribute: '"
                    + rDNAttributeName
                    + "'. Please check if mapping was succesful.");
          whereString = columnName + "='" + rDNAttributeValue + "'";
        }
      }

      // Build the SQL query.
      final Statement st = connection.createStatement();
      String sql = "SELECT " + selectString + " FROM " + fromString;

      if (!whereString.isEmpty()) sql = sql.concat(" WHERE " + whereString);
      ResultSet rs = st.executeQuery(sql);
      ResultSetMetaData rsmd = rs.getMetaData();

      // Fill the entries result for this query.
      searchEntries.clear();
      while (rs.next()) {
        Entry e = new LinkedHashMapEntry();

        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
          e.addAttribute(rsmd.getTableName(i) + "_" + rsmd.getColumnName(i), rs.getObject(i));
        }
        searchEntries.add(e);
      }
      r = Responses.newResult(ResultCode.SUCCESS);
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      r = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    }
    return r;
  }
예제 #18
0
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // IPPからコメント読み込むメソッド
  public void showCommentList(int target_year, int target_month, long until, int near) {

    // オンラインなら外部DBから他人のデータ読み出し//
    try {
      waitBar.setVisibility(View.VISIBLE);
      listView.setVisibility(View.GONE);
    } catch (NullPointerException e) {
      Log.d(TAG, e.toString());
    }

    if (NetworkManager.isConnected(getActivity().getApplicationContext())) {
      adapter.clear();

      // 読みだすデータの日時の範囲を指定
      int year = 0;
      int month = 0;
      long mUntil = 0;
      this.until = until;

      if (target_month == 0 && target_year == 0) {
        // 今月1日のUNIXタイムスタンプ(ミリ秒)を取得
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        calendar.set(year, month, 1, 0, 0, 0);

        since = calendar.getTimeInMillis(); // 今月頭から

        if (until == 0) {
          mUntil = System.currentTimeMillis(); // 現在まで

        } else {
          mUntil = until;
        }

      } else { // 月と日を指定されたら

        year = target_year;
        calendar.set(year, target_month, 1, 0, 0, 0); // 指定月の1日から
        since = calendar.getTimeInMillis();

        if (until == 0) {
          calendar.add(Calendar.MONTH, 1);
          mUntil = calendar.getTimeInMillis(); // 次の月の1日まで
          calendar.add(Calendar.MONTH, -1); // 戻しとく

        } else {
          mUntil = until;
        }
      }

      IPPGeoResourceClient client =
          new IPPGeoResourceClient(getSherlockActivity().getApplicationContext());
      client.setAuthKey(ipp_auth_key);

      jp.innovationplus.ipp.client.IPPGeoResourceClient.QueryCondition condition =
          new jp.innovationplus.ipp.client.IPPGeoResourceClient.QueryCondition();

      condition.setSince(since);
      condition.setUntil(mUntil);
      condition.setCount(10);
      condition.eq("pair_common_id", pair_common_id);

      if (near == 1) {
        condition.setBoundByRadiusSquare(
            mNowLocation.getLatitude(), mNowLocation.getLongitude(), radiusSquare);
      }

      condition.build();
      client.query(CommentGeoResource.class, condition, new CommentGeoGetCallback());

    } else {
      Toast.makeText(
              getSherlockActivity(),
              res.getString(R.string.message_network_disabled),
              Toast.LENGTH_SHORT)
          .show();
    }
  }
  @TargetApi(10)
  void connect(Context context) {

    try {

      MetaWatchService.fakeWatch = false;
      if (Preferences.watchMacAddress.equals("DIGITAL")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.DIGITAL;
      }
      if (Preferences.watchMacAddress.equals("ANALOG")) {
        MetaWatchService.fakeWatch = true;
        MetaWatchService.watchType = MetaWatchService.WatchType.ANALOG;
      }

      if (Preferences.logging)
        Log.d(MetaWatch.TAG, "Remote device address: " + Preferences.watchMacAddress);
      if (!Preferences.loaded) loadPreferences(context);

      if (!MetaWatchService.fakeWatch) {

        if (bluetoothAdapter == null) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_supported));
          return;
        } else if (!bluetoothAdapter.isEnabled()) {
          sendToast(getResources().getString(R.string.error_bluetooth_not_enabled));
          return;
        }

        wakeLock.acquire(5000);

        BluetoothDevice bluetoothDevice =
            bluetoothAdapter.getRemoteDevice(Preferences.watchMacAddress);

        if (Preferences.skipSDP) {
          Method method =
              bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
          bluetoothSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);
        } else {
          UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

          int currentapiVersion = android.os.Build.VERSION.SDK_INT;

          if (Preferences.insecureBtSocket
              && currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
            bluetoothSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
          } else {
            bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
          }
        }

        bluetoothAdapter.cancelDiscovery();
        bluetoothSocket.connect();

        inputStream = bluetoothSocket.getInputStream();
        outputStream = bluetoothSocket.getOutputStream();
      }

      connectionState = ConnectionState.CONNECTED;
      updateNotification();

      Protocol.startProtocolSender();

      // RM: This is disabled for now, as it seems to confuse the watch fw (3.1.0S tested)
      // and get it into a state where it won't accept any date/time format updates :-S

      // if( Preferences.autoClockFormat )
      //	Protocol.setTimeDateFormat(this);

      Protocol.getRealTimeClock();
      Protocol.getDeviceType();

      Notification.startNotificationSender(this);

      Idle.updateIdle(this, true);

    } catch (IOException ioexception) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, ioexception.toString());
    } catch (SecurityException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NoSuchMethodException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalArgumentException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (IllegalAccessException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (InvocationTargetException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } catch (NullPointerException e) {
      if (Preferences.logging) Log.d(MetaWatch.TAG, e.toString());
    } finally {
      if (wakeLock != null && wakeLock.isHeld()) {
        wakeLock.release();
      }
    }

    return;
  }
예제 #20
0
  /**
   * Modifies a record in the Database Server using the provided modify request.
   *
   * @param request The modify request.
   * @return The result of the operation.
   * @throws ErrorResultException If the result code indicates that the request failed for some
   *     reason.
   * @throws SQLException If the SQL query has an invalid format.
   * @throws NullPointerException If {@code request} was {@code null}, or if a corresponding mapping
   *     value could not be found in the mapping component.
   */
  @Override
  public Result modify(final ModifyRequest request) {
    Result r;
    try {
      // Split up the DN the of the request.
      final DN DN = request.getName();
      final RDN rDN = DN.rdn();
      final String filterAttributeName = rDN.getFirstAVA().getAttributeType().getNameOrOID();
      final String filterAttributeValue = rDN.getFirstAVA().getAttributeValue().toString();
      final RDN OU = DN.parent(1).rdn();
      final String OUName = OU.getFirstAVA().getAttributeValue().toString();
      final String baseDN = DN.parent(2).toString();

      // Search mapping for the corresponding table and column names.
      final String tableName = jdbcm.getTableNameFromMapping(baseDN, OUName);

      if (tableName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching table name for OU: '"
                + OUName
                + "' in DN: '"
                + baseDN
                + "'. Please check if mapping was succesful.");
      final String columnName =
          jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, filterAttributeName);

      if (columnName == null)
        throw new NullPointerException(
            "JDBC Error: Could not find matching column name for attribute: '"
                + filterAttributeName
                + "'. Please check if mapping was succesful.");

      // Get attribute and modificationtype for each modification.
      // Search mapping for the corresponding column name for the modification attribute.
      final List<Modification> modificationList = request.getModifications();
      final ListIterator<Modification> listIter = modificationList.listIterator();
      String modificationString = "";

      while (listIter.hasNext()) {
        final Modification modification = listIter.next();
        final ModificationType modificationType = modification.getModificationType();
        final Attribute modificationAttribute = modification.getAttribute();
        final String modificationAttributeName =
            modificationAttribute.getAttributeDescription().toString();
        final String modificationColumnName =
            jdbcm.getColumnNameFromMapping(tableName, baseDN, OUName, modificationAttributeName);

        if (modificationColumnName == null)
          throw new NullPointerException(
              "JDBC Error: Could not find matching column name for attribute: '"
                  + modificationAttributeName
                  + "'. Please check if mapping was succesful.");
        String modificationAttributeValue = "";

        if (modificationType == ModificationType.ADD) {
          final Iterator<ByteString> iter = modificationAttribute.iterator();

          int counter = 0;
          while (iter.hasNext()) {
            if (counter > 0) modificationAttributeValue = modificationAttributeValue.concat(", ");
            modificationAttributeValue = modificationAttributeValue.concat(iter.next().toString());
            counter++;
          }
          final Object classType = jdbcm.getTableColumnDataType(tableName, modificationColumnName);

          if (classType == Integer.class)
            modificationAttributeValue =
                "(CASE WHEN ("
                    + modificationColumnName
                    + " = 0) THEN ' "
                    + modificationAttributeValue
                    + "' ELSE concat("
                    + modificationColumnName
                    + ", ', "
                    + modificationAttributeValue
                    + "') END)";
          else
            modificationAttributeValue =
                "(CASE WHEN ("
                    + modificationColumnName
                    + " = 'Default Value') THEN ' "
                    + modificationAttributeValue
                    + "' ELSE concat("
                    + modificationColumnName
                    + ", ', "
                    + modificationAttributeValue
                    + "') END)";
        } else if (modificationType == ModificationType.REPLACE) {
          final Iterator<ByteString> iter = modificationAttribute.iterator();

          while (iter.hasNext()) {
            modificationAttributeValue = "'" + iter.next().toString() + "'";
          }
        } else {
          final boolean nullable = jdbcm.getTableColumnNullable(tableName, modificationColumnName);

          if (nullable == false)
            throw new SQLException("Cannot delete data from not-nullable column.");
          final Object classType = jdbcm.getTableColumnDataType(tableName, modificationColumnName);

          if (classType == Integer.class)
            modificationAttributeValue = "'" + Integer.toString(0) + "'";
          else modificationAttributeValue = "'Default Value'";
        }
        modificationString =
            modificationString.concat(
                modificationColumnName + "=" + modificationAttributeValue + ", ");
      }
      modificationString = modificationString.substring(0, modificationString.length() - 2);

      // Build the SQL query.
      final Statement st = connection.createStatement();
      final String sql =
          "UPDATE "
              + tableName
              + " SET "
              + modificationString
              + " WHERE "
              + columnName
              + "='"
              + filterAttributeValue
              + "'";
      st.executeUpdate(sql);
      r = Responses.newResult(ResultCode.SUCCESS);
    } catch (SQLException e) {
      System.out.println(e.toString());
      r = Responses.newResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    } catch (NullPointerException e) {
      System.out.println(e.toString());
      r = Responses.newCompareResult(ResultCode.OPERATIONS_ERROR);
      r.setCause(e);
    }
    return r;
  }
예제 #21
0
  public void fetchAllProperties() {
    // getMethods key is a property Class object
    // getMethods value is the Method that returns the instance of the Property
    Hashtable getMethods = new Hashtable();
    Class thisClass = asset.getClass();
    Field fields[] = null;
    Vector fieldVector = new Vector(2);
    Method methods[] = null;
    Object result = null;

    // retrieve all public methods of this class and its ancestor classes
    // retrieve all attributes of this class and ancestors
    try {
      methods = thisClass.getMethods();
      Class ancestorClass = thisClass;
      while (Asset.class.isAssignableFrom(ancestorClass)) {
        fields = ancestorClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
          fieldVector.addElement(fields[i]);
        }
        ancestorClass = ancestorClass.getSuperclass();
      }
    } catch (SecurityException se) {
      System.out.println("In Asset.fetchAllProperties: " + se.toString());
    }

    // Build a Hashtable of the methods with the right signature, where
    // "right signature" means the method returns a subtype of Property
    // and requires no arguments.
    for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
      Class returntype = methods[methodIndex].getReturnType();
      if (returntype != null
          && PropertyGroup.class.isAssignableFrom(returntype)
          && methods[methodIndex].getParameterTypes().length == 0) {
        getMethods.put(methods[methodIndex].getReturnType(), methods[methodIndex]);
      }
    }

    // Walk through the list of fields looking for subtypes of Property.
    // If the field's Class is in the Hashtable, do introspection
    // this section is a bit complex because we want to introspect
    // on the DECLARED return property CLASS to determine what
    // attributes to fetch, but we want to fetch
    // the attributes by invoking methods on the actual property object
    Enumeration fieldEnum = fieldVector.elements();
    while (fieldEnum.hasMoreElements()) {
      Field currentField = (Field) fieldEnum.nextElement();
      Method currentMethod = (Method) getMethods.get(currentField.getType());
      if (currentMethod != null) {
        try {
          // invoke the get property method on the asset
          Object returnedObject = currentMethod.invoke(asset, null);
          if (returnedObject != null) {
            Class returnType = currentMethod.getReturnType();
            // introspect on property class to get attributes
            // throws Introspection exception
            // System.out.println("Introspecting on: " + returnType +
            // " for " + asset.toString());
            BeanInfo info = Introspector.getBeanInfo(returnType);
            PropertyDescriptor[] pds = info.getPropertyDescriptors();
            // invoke read methods to get attributes of property
            for (int j = 0; j < pds.length; j++) {
              Method readMethod = pds[j].getReadMethod();
              if (readMethod != null) {
                try {
                  // System.out.println("Invoking: " + readMethod.getName() +
                  // " on " + returnedObject);
                  result = readMethod.invoke(returnedObject, null);

                  String s =
                      prettyName(returnType.toString()) + ": " + pds[j].getName() + ": " + result;
                  insert(new UIStringNode(s), treeIndex++);
                } catch (NullPointerException e) {
                  System.out.println("In Asset.fetchAllProperties: " + e.toString());
                  e.printStackTrace();
                } catch (InvocationTargetException e) {
                  System.out.println(
                      "Invocation target error; method: "
                          + currentMethod.getName()
                          + " exception: "
                          + e.toString());
                  e.printStackTrace();
                }
              }
            }
          }
        } catch (Exception e) {
          System.out.println(
              "Exception caught; method: "
                  + currentMethod.getName()
                  + " exception: "
                  + e.toString());
          e.printStackTrace();
        }
      }
    }

    // now handle the dynamically added properties
    Method readAttributeMethod = null;
    Enumeration dynamic = asset.getOtherProperties();
    while (dynamic.hasMoreElements()) {
      Object o = dynamic.nextElement();
      try {
        PropertyGroup p = (PropertyGroup) o;
        Class interfaceToUse = p.getPrimaryClass();
        //	System.out.println("Introspecting on: " + interfaceToUse);
        // System.out.println("Introspecting on: " + interfaceToUse +
        // " for " + asset.toString());
        BeanInfo propertyBeanInfo = Introspector.getBeanInfo(interfaceToUse);
        PropertyDescriptor[] attributePds = propertyBeanInfo.getPropertyDescriptors();
        for (int k = 0; k < attributePds.length; k++) {
          readAttributeMethod = attributePds[k].getReadMethod();
          if (readAttributeMethod != null) {
            //	    System.out.println("From other properties, Invoking: " +
            // readAttributeMethod.getName() +
            //			       " on " + o);
            result = readAttributeMethod.invoke(o, null);
            String s =
                prettyName(interfaceToUse.toString())
                    + ": "
                    + attributePds[k].getName()
                    + ": "
                    + result;
            insert(new UIStringNode(s), treeIndex++);
          }
        }
      } catch (Exception e) {
        String n = "(null method)";
        if (readAttributeMethod != null) n = readAttributeMethod.getName();
        System.out.println(
            "Exception introspecting on other properties: "
                + e.toString()
                + " while invoking "
                + n
                + " on "
                + o.getClass());
      }
    }
  }
예제 #22
0
  /**
   * Creates a new URL to the specified resource {@code spec}. This URL is relative to the given
   * {@code context}. The {@code handler} will be used to parse the URL string representation. If
   * this argument is {@code null} the default {@code URLStreamHandler} will be used. If the
   * protocol of the parsed URL does not match with the protocol of the context URL, then the newly
   * created URL is absolute and bases only on the given URL represented by {@code spec}. Otherwise
   * the protocol is defined by the context URL.
   *
   * @param context the URL which is used as the context.
   * @param spec the URL string representation which has to be parsed.
   * @param handler the specific stream handler to be used by this URL.
   * @throws IOException if the given string {@code spec} could not be parsed as a URL or an invalid
   *     protocol has been found.
   */
  public URL(URL context, String spec) throws MalformedURLException {

    if (spec == null) {
      throw new MalformedURLException();
    }
    spec = spec.trim();

    this.spec = spec;

    // The spec includes a protocol if it includes a colon character
    // before the first occurrence of a slash character. Note that,
    // "protocol" is the field which holds this URLs protocol.
    int index;
    try {
      index = spec.indexOf(':');
    } catch (NullPointerException e) {
      throw new MalformedURLException(e.toString());
    }
    int startIPv6Addr = spec.indexOf('[');
    if (index >= 0) {
      if ((startIPv6Addr == -1) || (index < startIPv6Addr)) {
        protocol = spec.substring(0, index);
        // According to RFC 2396 scheme part should match
        // the following expression:
        // alpha *( alpha | digit | "+" | "-" | "." )
        char c = protocol.charAt(0);
        boolean valid = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
        for (int i = 1; valid && (i < protocol.length()); i++) {
          c = protocol.charAt(i);
          valid =
              ('a' <= c && c <= 'z')
                  || ('A' <= c && c <= 'Z')
                  || ('0' <= c && c <= '9')
                  || (c == '+')
                  || (c == '-')
                  || (c == '.');
        }
        if (!valid) {
          protocol = null;
          index = -1;
        } else {
          // Ignore case in protocol names.
          // Scheme is defined by ASCII characters.
          protocol = protocol.toLowerCase();
        }
      }
    }

    if (protocol != null) {
      // If the context was specified, and it had the same protocol
      // as the spec, then fill in the receiver's slots from the values
      // in the context but still allow them to be over-ridden later
      // by the values in the spec.
      if (context != null && protocol.equals(context.getProtocol())) {
        String cPath = context.getPath();
        if (cPath != null && cPath.startsWith("/")) {
          set(
              protocol,
              context.getHost(),
              context.getPort(),
              context.getAuthority(),
              context.getUserInfo(),
              cPath,
              context.getQuery(),
              null);
        }
      }
    } else {
      // If the spec did not include a protocol, then the context
      // *must* be specified. Fill in the receiver's slots from the
      // values in the context, but still allow them to be over-ridden
      // by the values in the ("relative") spec.
      if (context == null) {
        throw new MalformedURLException("Protocol not found: " + spec);
      }
      set(
          context.getProtocol(),
          context.getHost(),
          context.getPort(),
          context.getAuthority(),
          context.getUserInfo(),
          context.getPath(),
          context.getQuery(),
          null);
    }

    if (port < -1) {
      throw new MalformedURLException("Port out of range: " + port);
    }
  }
예제 #23
0
  /* (non-Javadoc)
   * @see com.github.catageek.ByteCart.Signs.Triggable#trigger()
   */
  @Override
  public void trigger() throws ClassNotFoundException, IOException {

    CollisionAvoiderBuilder builder = new RouterCollisionAvoiderBuilder(this, center.getLocation());

    try {

      BlockFace direction, to;
      Router router =
          ByteCart.myPlugin.getCollisionAvoiderManager().<Router>getCollisionAvoider(builder);
      boolean isTrain = AbstractTriggeredSign.isTrain(destination);

      // Here begins the triggered action

      // is this an wanderer who needs special routing ? no then routing normally
      if (selectWanderer()) {

        // if this is a cart in a train
        if (this.wasTrain(this.getLocation())) {

          // leave a message to next cart that it is a train
          ByteCart.myPlugin.getIsTrainManager().getMap().reset(getLocation());
          // tell to router not to change position
          ByteCart.myPlugin
              .getCollisionAvoiderManager()
              .<Router>getCollisionAvoider(builder)
              .Book(isTrain);
          return;
        }

        if (destination != null) {
          // Time-to-live management

          // loading TTl of cart
          int ttl = destination.getTTL();

          // if ttl did not reach end of life ( = 0)
          if (ttl != 0) {

            destination.updateTTL(ttl - 1);
          }

          // if ttl was 1 (now 0), we try to return the cart to source station

          if (ttl == 1 && tryReturnCart())
            destination = AddressFactory.getAddress(this.getInventory());

          if (ByteCart.debug) ByteCart.log.info("ByteCart : TTL is " + destination.getTTL());

          // if this is the first car of a train
          // we keep it during 2 s
          if (isTrain) {
            this.setWasTrain(this.getLocation(), true);
          }

          destination.finalizeAddress();
        }

        direction = this.SelectRoute(destination, Sign, RoutingTable);

        // trigger event
        BlockFace bdest = router.WishToGo(From, direction, isTrain);
        int ring = this.getRoutingTable().getDirectlyConnected(new DirectionRegistry(bdest));
        SignPostRouteEvent event = new SignPostRouteEvent(this, ring);
        Bukkit.getServer().getPluginManager().callEvent(event);

        return;
      }

      // it's a wanderer, so let it choosing direction
      Wanderer wanderer = getWanderer();

      // routing normally
      to = router.WishToGo(From, wanderer.giveRouterDirection(), isTrain);

      if (WandererContentFactory.isWanderer(getInventory(), "Updater")) {
        int nextring = this.getRoutingTable().getDirectlyConnected(new DirectionRegistry(to));
        UpdaterPassRouterEvent event = new UpdaterPassRouterEvent(wanderer, to, nextring);
        Bukkit.getServer().getPluginManager().callEvent(event);
      }

      // here we perform routes update
      wanderer.doAction(to);

    } catch (ClassCastException e) {
      if (ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString());
      e.printStackTrace();

      // Not the good blocks to build the signs
      return;
    } catch (NullPointerException e) {
      if (ByteCart.debug) ByteCart.log.info("ByteCart : " + e.toString());

      e.printStackTrace();

      // there was no inventory in the cart
      return;
    }
  }