Пример #1
0
 final void stringToByteArray(String source, byte[] buf, int offset)
     throws CharConversionException {
   char[] src = source.toCharArray();
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Converting string to byte array for ccsid: " + ccsid_,
         ConvTable.dumpCharArray(src));
   try {
     for (int bufPos = offset, srcPos = 0; srcPos < src.length; ++srcPos) {
       buf[bufPos++] = (byte) (src[srcPos] >>> 8);
       buf[bufPos++] = (byte) src[srcPos];
     }
   } catch (ArrayIndexOutOfBoundsException e) {
     Trace.log(
         Trace.ERROR,
         "Source length: "
             + src.length
             + "; Source offset: 0; Destination length: "
             + buf.length
             + "; Destination offset: "
             + offset
             + ";",
         e);
     throw new CharConversionException();
   }
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Destination byte array for ccsid: " + ccsid_,
         buf,
         offset,
         src.length * 2);
 }
Пример #2
0
  /**
   * Sets the integrated file system pathname of the AFP resource.
   *
   * @param path The integrated file system name of the AFP resource. The format of the resource
   *     string must be in the format of "/QSYS.LIB/libname.LIB/resourcename.type". Valid values for
   *     <i>type</i> include FNTRSC, FORMDF, OVL, PAGSEG, and PAGDFN.
   * @exception PropertyVetoException If the change is vetoed.
   */
  public void setPath(String path) throws PropertyVetoException {
    if (path == null) {
      Trace.log(Trace.ERROR, "Parameter 'path' is null");
      throw new NullPointerException(PATH);
    }

    // check for connection...
    if (impl_ != null) {
      Trace.log(Trace.ERROR, "Cannot set property 'path' after connect.");
      throw new ExtendedIllegalStateException(
          PATH, ExtendedIllegalStateException.PROPERTY_NOT_CHANGED);
    }

    String oldPath = getPath();

    // Tell any vetoers about the change. If anyone objects
    // we let the PropertyVetoException propagate back to
    // our caller.
    vetos.fireVetoableChange(PATH, oldPath, path);

    // no one vetoed, make the change
    setIDCodePoint(buildIDCodePoint(path));

    // Notify any property change listeners
    changes.firePropertyChange(PATH, oldPath, path);
  }
Пример #3
0
 @SuppressWarnings("incomplete-switch")
 private void restart() {
   switch (state.get()) {
     case STARTING:
       Trace.debug(
           "Returning early from restart.  Already starting for project {0} and kind {1}",
           project.getName(), kind);
     case DISCONNECTED:
       Trace.debug(
           "Endpoint disconnected and skipping restart for project {0} and kind {1}",
           project.getName(), kind);
       return;
   }
   try {
     // TODO enhance fix to only check project once
     conn.refresh(project);
     Trace.debug(
         "WatchManager Rescheduling watch job for project {0} and kind {1}",
         project.getName(), kind);
     startWatch(project, backoff, lastConnect, this);
   } catch (Exception e) {
     Trace.debug(
         "WatchManager Unable to rescheduling watch job for project {0} and kind {1}",
         e, project.getName(), kind);
     stopWatch(project, conn);
   }
 }
 private void deleteUserIncludeTrace(final Trace trace) {
   if (isDebug) {
     logger.debug("Delete user include trace={}, sampled={}", trace, trace.canSampled());
   }
   traceContext.removeTraceObject();
   trace.close();
 }
Пример #5
0
  private void runVerification(int numberOfRequests, int jobsPerRequest) {
    // verify control info
    CountInfo countInfo = new CountInfo(numberOfRequests, jobsPerRequest);
    ConcurrentHashMap<Long, ConcurrentLinkedDeque<TraceContext.Info>> testInfoMap =
        TraceContext.getTestInfoMap();

    // LOGGER.info("Thread {}: {}", key, testInfoMap.get(key).toString().replace(",", "\n"));
    for (ConcurrentLinkedDeque<TraceContext.Info> queue : testInfoMap.values()) {
      mixedInvariants(queue, countInfo);
    }

    countInfo.verify();

    // verify trace info
    for (long rqId = 0; rqId < numberOfRequests; rqId++) {
      ConcurrentLinkedDeque<Trace> traceQueue = TraceContext.getAllTraceInfoMap().get(rqId);
      assertEquals(traceQueue.size(), jobsPerRequest + 1);
      Set<Integer> jobIdSet = new HashSet<Integer>();
      for (Trace trace : traceQueue) {
        // one trace is used for request handler, it has no info recorded
        if (trace.getValue().size() > 0) {
          Object obj = trace.getValue().get(0); // we have recorded one entry per job in tests
          String[] tmp = ((String) obj).split(SEP);
          long reqId = Long.parseLong(tmp[0].trim());
          assertEquals(rqId, reqId);
          int jobId = Integer.parseInt(tmp[1].trim());
          jobIdSet.add(jobId);
        }
      }
      assertEquals(jobIdSet.size(), jobsPerRequest);
      // show trace
      LOGGER.info("Trace Tree: {}", TraceContext.getTraceInfoOfRequestId(rqId));
    }
  }
Пример #6
0
  /** Load the generator images. */
  private static void loadGeneratorImages(IConfigurationElement[] cf) {
    int size = cf.length;
    for (int i = 0; i < size; i++) {
      try {
        String name = cf[i].getDeclaringExtension().getContributor().getName();
        String iconPath = cf[i].getAttribute("icon");
        ImageDescriptor imageDescriptor =
            AbstractUIPlugin.imageDescriptorFromPlugin(name, iconPath);
        if (imageDescriptor == null && iconPath != null && iconPath.length() > 0)
          imageDescriptor = ImageDescriptor.getMissingImageDescriptor();

        if (imageDescriptor != null) {
          String[] typeIds = StringUtils.tokenize(cf[i].getAttribute("typeIds"), ",");
          int size2 = typeIds.length;
          for (int j = 0; j < size2; j++) {
            imageRegistry.put(typeIds[j], imageDescriptor);
            imageDescriptors.put(typeIds[j], imageDescriptor);
          }
        }
        Trace.trace(Trace.CONFIG, "  Loaded generatorImage: " + cf[i].getAttribute("id"));
      } catch (Throwable t) {
        Trace.trace(
            Trace.SEVERE, "  Could not load generatorImage: " + cf[i].getAttribute("id"), t);
      }
    }
  }
Пример #7
0
 // Delete the entire item.
 protected boolean deleteItem(int id, String key) {
   Trace.info("RM::deleteItem(" + id + ", " + key + ") called.");
   synchronized (syncLock) {
     ReservableItem curObj = (ReservableItem) readData(id, key);
     // Check if there is such an item in the storage.
     if (curObj == null) {
       Trace.warn("RM::deleteItem(" + id + ", " + key + ") failed: " + " item doesn't exist.");
       return false;
     } else {
       if (curObj.getReserved() == 0) {
         removeData(id, curObj.getKey());
         Trace.info("RM::deleteItem(" + id + ", " + key + ") OK.");
         return true;
       } else {
         Trace.info(
             "RM::deleteItem("
                 + id
                 + ", "
                 + key
                 + ") failed: "
                 + "some customers have reserved it.");
         return false;
       }
     }
   }
 }
Пример #8
0
  // deletes the entire item
  protected boolean deleteItem(int id, String key) {
    Trace.info("RM::deleteItem(" + id + ", " + key + ") called");
    ReservableItem curObj = (ReservableItem) readData(id, key);
    Flight tempItem =
        new Flight(Integer.parseInt(curObj.getLocation()), curObj.getCount(), curObj.getPrice());
    tempItem.setReserved(curObj.getReserved());
    // Check if there is such an item in the storage
    if (curObj == null) {
      Trace.warn("RM::deleteItem(" + id + ", " + key + ") failed--item doesn't exist");
      return false;
    } else {
      if (curObj.getReserved() == 0) {

        tempItem.setType(0);
        writeDataToLog(id, curObj.getKey(), tempItem);
        removeData(id, curObj.getKey());
        Trace.info("RM::deleteItem(" + id + ", " + key + ") item deleted");
        return true;
      } else {
        Trace.info(
            "RM::deleteItem("
                + id
                + ", "
                + key
                + ") item can't be deleted because some customers reserved it");
        return false;
      }
    } // if
  }
  @Override
  public void before(Object target, Object[] args) {
    if (isDebug) {
      logger.beforeInterceptor(target, args);
    }

    Trace trace = traceContext.currentRawTraceObject();
    if (trace == null) {
      // create user include trace for standalone entry point.
      trace = createUserIncludeTrace();
      if (trace == null) {
        return;
      }
    }

    // check user include trace.
    if (!isUserIncludeTrace(trace)) {
      return;
    }

    // entry scope(default & disable trace).
    entryUserIncludeTraceScope(trace);

    // check sampled.
    if (!trace.canSampled()) {
      // skip
      return;
    }

    trace.traceBlockBegin();
  }
Пример #10
0
  public void run() {
    try {
      ObjectOutputStream outputStream = new ObjectOutputStream(_clientSocket.getOutputStream());
      outputStream.flush();

      DataInputStream inputStream = new DataInputStream(_clientSocket.getInputStream());

      while (true) {
        String request = inputStream.readUTF();

        Trace.info("Received request: " + request);

        RMResult response = processIfComposite(request);
        if (response == null) {
          response = processIfCIDRequired(request);
          if (response == null) {
            response = processAtomicRequest(request);
          }
        }

        outputStream.writeObject(response);
        outputStream.flush();
      }
    } catch (EOFException eof) {
      Trace.info("A client closed a connection.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #11
0
  // Reserve an item.
  @Override
  public boolean reserveCustomer(int id, int customerId, String key, String location, int price) {
    synchronized (syncLock) {
      Customer cust = (Customer) readData(id, Customer.getKey(customerId));
      if (cust == null) {
        Trace.warn(
            "RM::reserveItem("
                + id
                + ", "
                + customerId
                + ", "
                + key
                + ", "
                + location
                + ") failed: customer doesn't exist.");
        return false;
      } else {
        // Do reservation.
        cust.reserve(key, location, price);
        writeData(id, cust.getKey(), cust);

        Trace.warn(
            "RM::reserveItem(" + id + ", " + customerId + ", " + key + ", " + location + ") OK.");
        return true;
      }
    }
  }
  /** Forces any buffered output bytes to be written. */
  void flush() // @B2A - code relocated from IFSFileOutputStreamImplRemote,etc.
      throws IOException, AS400SecurityException {
    // Request that changes be committed to disk.
    IFSCommitReq req = new IFSCommitReq(fileHandle_);
    ClientAccessDataStream ds = null;
    try {
      ds = (ClientAccessDataStream) server_.sendAndReceive(req);
    } catch (ConnectionDroppedException e) {
      Trace.log(Trace.ERROR, "Byte stream server connection lost");
      connectionDropped(e);
    } catch (InterruptedException e) {
      Trace.log(Trace.ERROR, "Interrupted", e);
      throw new InterruptedIOException(e.getMessage());
    }

    // Verify that the request was successful.
    if (ds instanceof IFSReturnCodeRep) {
      int rc = ((IFSReturnCodeRep) ds).getReturnCode();
      if (rc != IFSReturnCodeRep.SUCCESS) {
        throwSecurityExceptionIfAccessDenied(path_, rc); // check for "access denied"
        Trace.log(Trace.ERROR, "IFSReturnCodeRep return code", descriptionForReturnCode(rc));
        throw new ExtendedIOException(path_, rc);
      }
    } else {
      // Unknown data stream.
      Trace.log(Trace.ERROR, "Unknown reply data stream", ds.data_);
      throw new InternalErrorException(
          Integer.toHexString(ds.getReqRepID()), InternalErrorException.DATA_STREAM_UNKNOWN);
    }
  }
  // Open a single file, list the file attributes, and close the file.
  // Returns null if the file doesn't exist or is a directory.
  private IFSListAttrsRep listObjAttrs(int attrsType, int flags1, int flags2)
      throws IOException, AS400SecurityException {
    // Assume connect() has already been done.

    IFSListAttrsRep reply = null;
    int fileHandle = UNINITIALIZED;

    // Design note: In order to get an OA* structure back in the "List File Attributes" reply, we
    // must specify the file by handle rather than by name.

    boolean usedGlobalHandle = false; // @KKBA
    try {
      // Open the file, and obtain a file handle.
      if (fileHandle_ != UNINITIALIZED) // @KKBA
      { // @KKBA
        fileHandle = fileHandle_; // @KKBA
        usedGlobalHandle = true; // @KKBA
      } // @KKBA
      else {
        fileHandle = createFileHandle(); // @KKBC
        if (fileHandle == UNINITIALIZED) {
          if (Trace.traceOn_)
            Trace.log(
                Trace.ERROR,
                "Unable to create handle to file " + path_ + ". IFSReturnCodeRep return code",
                errorRC_);
          return null;
        }
      }

      // Send a 'list attributes' request, specifying the file handle we just created,
      // and indicating that we want an OA2 structure in the reply.

      IFSListAttrsReq req1 = new IFSListAttrsReq(fileHandle, attrsType, flags1, flags2);
      req1.setPatternMatching(patternMatching_);

      Vector replys = listAttributes(req1);

      // Verify that we got exactly one reply.
      if (replys == null) {
        if (Trace.traceOn_)
          Trace.log(Trace.WARNING, "Received null from listAttributes(fileHandle).");
      } else if (replys.size() == 0) {
        if (Trace.traceOn_)
          Trace.log(Trace.WARNING, "Received no replies from listAttributes(fileHandle).");
      } else if (replys.size() > 1) {
        if (Trace.traceOn_)
          Trace.log(
              Trace.WARNING,
              "Received multiple replies from listAttributes(fileHandle) (" + replys.size() + ")");
      } else {
        reply = (IFSListAttrsRep) replys.elementAt(0);
      }
    } finally {
      if (!usedGlobalHandle && fileHandle != UNINITIALIZED) // @KKBA
      close(fileHandle);
    }

    return reply;
  }
 /** Copies a file or directory to another file or directory. */
 boolean copyTo(String destinationPath, boolean replace)
     throws AS400SecurityException, IOException {
   ClientAccessDataStream ds = null;
   IFSCopyReq req = new IFSCopyReq(path_, destinationPath, replace);
   try {
     ds = (ClientAccessDataStream) server_.sendAndReceive(req);
   } catch (ConnectionDroppedException e) {
     Trace.log(Trace.ERROR, "Byte stream connection lost during copy", e);
     connectionDropped(e);
   } catch (InterruptedException e) {
     Trace.log(Trace.ERROR, "Interrupted", e);
     throw new InterruptedIOException(e.getMessage());
   }
   if (ds instanceof IFSReturnCodeRep) {
     int rc = ((IFSReturnCodeRep) ds).getReturnCode();
     if (rc != IFSReturnCodeRep.SUCCESS) {
       String path = (rc == IFSReturnCodeRep.DUPLICATE_DIR_ENTRY_NAME ? destinationPath : path_);
       throwSecurityExceptionIfAccessDenied(path, rc); // check for "access denied"
       Trace.log(Trace.ERROR, "IFSReturnCodeRep return code", descriptionForReturnCode(rc));
       throw new ExtendedIOException(path, rc);
     }
     return true;
   } else {
     Trace.log(Trace.ERROR, "Unknown reply data stream", ds.data_);
     throw new InternalErrorException(
         Integer.toHexString(ds.getReqRepID()), InternalErrorException.DATA_STREAM_UNKNOWN);
   }
 }
  void close(int fileHandle) throws IOException {
    if (fileHandle == UNINITIALIZED) return; // @B8c

    // Close the file.  Send a close request to the server.
    ClientAccessDataStream ds = null;
    IFSCloseReq req = new IFSCloseReq(fileHandle);
    try {
      ds = (ClientAccessDataStream) server_.sendAndReceive(req);
    } catch (ConnectionDroppedException e) {
      Trace.log(Trace.ERROR, "Byte stream connection lost during close", e);
      connectionDropped(e);
    } catch (InterruptedException e) {
      Trace.log(Trace.ERROR, "Interrupted", e);
      throw new InterruptedIOException(e.getMessage());
    }

    // Validate the reply.
    if (ds instanceof IFSCloseRep) {
      int rc = ((IFSCloseRep) ds).getReturnCode();
      if (rc != 0) {
        Trace.log(Trace.ERROR, "IFSCloseRep return code", rc);
        throw new ExtendedIOException(path_, rc);
      }
    } else if (ds instanceof IFSReturnCodeRep) {
      int rc = ((IFSReturnCodeRep) ds).getReturnCode();
      if (rc != IFSReturnCodeRep.SUCCESS) {
        Trace.log(Trace.ERROR, "IFSReturnCodeRep return code", descriptionForReturnCode(rc));
        throw new ExtendedIOException(path_, rc);
      }
    } else {
      Trace.log(Trace.ERROR, "Unknown reply data stream", ds.data_);
      throw new InternalErrorException(
          Integer.toHexString(ds.getReqRepID()), InternalErrorException.DATA_STREAM_UNKNOWN);
    }
  }
Пример #16
0
  public void testCategories() throws InterruptedException {
    Trace.setEnabled(true);
    Trace.getDataManager().setTraceLogFile(new File("c:\\temp\\trace.log"));
    Trace.getDataManager().setLogTraceAboveThreshold(true);
    Trace.getDataManager().setLogThreshold(100);
    Trace.getDataManager().setTraceLevel(TraceLevel.BASIC);
    Trace.startTrace();

    ITraceOperation txOp1 = Trace.getTraceContext().startOperation("dao", "test-1");

    Thread.sleep(300);

    txOp1.finished();
    //		assertNear(txOp1.getDuration(), 300, 15);

    ITraceOperation txOp2 = Trace.getTraceContext().startOperation("dao");
    Thread.sleep(200);
    txOp2.setInfo("This is a fancy op.");
    txOp2.finished();
    //		assertNear(txOp2.getDuration(), 200, 5);

    ITraceContext tx = Trace.endTrace();
    System.out.println("Total Duration: " + tx.getDuration());
    //		assertNear(tx.getDuration(), 500, 5);

    ITraceCategory category = tx.getTraceCategory("dao");
    System.out.println("Count: " + category.getCount());
    System.out.println("Cat-Duration: " + category.getTotalDuration());

    Trace.getDataManager().handleTraceResult(tx);
  }
Пример #17
0
 /** Load the generator images. */
 private static void loadGeneratorImages() {
   Trace.trace(Trace.CONFIG, "->- Loading .generatorImages extension point ->-");
   IExtensionRegistry registry = Platform.getExtensionRegistry();
   loadGeneratorImages(
       registry.getConfigurationElementsFor(JM2TUI.PLUGIN_ID, JM2TUI.EXTENSION_GENERATOR_IMAGES));
   JM2TUI.addRegistryListener();
   Trace.trace(Trace.CONFIG, "-<- Done loading .generatorImages extension point -<-");
 }
Пример #18
0
  // Create a new flight, or add seats to existing flight
  //  NOTE: if flightPrice <= 0 and the flight already exists, it maintains its current price
  public boolean addFlight(int id, int flightNum, int flightSeats, int flightPrice)
      throws RemoteException, InvalidTransactionException, TransactionAbortedException {
    Trace.info(
        "RM::addFlight("
            + id
            + ", "
            + flightNum
            + ", $"
            + flightPrice
            + ", "
            + flightSeats
            + ") called");
    Flight curObj = (Flight) readData(id, Flight.getKey(flightNum));
    if (curObj == null) {
      // doesn't exist...add it
      Flight newObj = new Flight(flightNum, flightSeats, flightPrice);

      writeData(id, newObj.getKey(), newObj);
      String key = newObj.getKey();
      if (readDataFromLog(id, key, id) == null) {
        Flight logObj = (Flight) newObj.clone();
        logObj.setCount(-1);
        logObj.type = 0;
        writeDataToLog(id, key, logObj);
      }
      Trace.info(
          "RM::addFlight("
              + id
              + ") created new flight "
              + flightNum
              + ", seats="
              + flightSeats
              + ", price=$"
              + flightPrice);
    } else {
      // add seats to existing flight and update the price...
      Flight logObj = (Flight) curObj.clone();
      if (readDataFromLog(id, curObj.getKey(), id) == null)
        writeDataToLog(id, curObj.getKey(), logObj);

      curObj.setCount(curObj.getCount() + flightSeats);
      if (flightPrice > 0) {
        curObj.setPrice(flightPrice);
      } // if
      writeData(id, curObj.getKey(), curObj);
      Trace.info(
          "RM::addFlight("
              + id
              + ") modified existing flight "
              + flightNum
              + ", seats="
              + curObj.getCount()
              + ", price=$"
              + flightPrice);
    } // else
    return (true);
  }
Пример #19
0
  // Deletes customer from the database.
  public boolean deleteCustomer(int id, int customerID) throws RemoteException {
    Trace.info("RM::deleteCustomer(" + id + ", " + customerID + ") called");
    Customer cust = (Customer) readData(id, Customer.getKey(customerID));

    if (cust == null) {
      Trace.warn(
          "RM::deleteCustomer(" + id + ", " + customerID + ") failed--customer doesn't exist");
      return false;
    } else {
      Customer temp = cust.clone();
      // Increase the reserved numbers of all reservable items which the customer reserved.
      RMHashtable reservationHT = cust.getReservations();
      for (Enumeration e = reservationHT.keys(); e.hasMoreElements(); ) {
        String reservedkey = (String) (e.nextElement());
        ReservedItem reserveditem = cust.getReservedItem(reservedkey);
        Trace.info(
            "RM::deleteCustomer("
                + id
                + ", "
                + customerID
                + ") has reserved "
                + reserveditem.getKey()
                + " "
                + reserveditem.getCount()
                + " times");
        ReservableItem item = (ReservableItem) readData(id, reserveditem.getKey());
        Trace.info(
            "RM::deleteCustomer("
                + id
                + ", "
                + customerID
                + ") has reserved "
                + reserveditem.getKey()
                + "which is reserved"
                + item.getReserved()
                + " times and is still available "
                + item.getCount()
                + " times");
        Flight tempItem =
            new Flight(Integer.parseInt(item.getLocation()), item.getCount(), item.getPrice());
        tempItem.setReserved(item.getReserved());
        tempItem.setType(0);
        item.setReserved(item.getReserved() - reserveditem.getCount());
        item.setCount(item.getCount() + reserveditem.getCount());
        if (readDataFromLog(id, item.getKey(), id) == null)
          writeDataToLog(id, item.getKey(), tempItem);
      }

      // remove the customer from the storage
      temp.setType(1);
      if (readDataFromLog(id, cust.getKey(), id) == null) writeDataToLog(id, cust.getKey(), temp);
      removeData(id, cust.getKey());

      Trace.info("RM::deleteCustomer(" + id + ", " + customerID + ") succeeded");
      return true;
    } // if
  }
Пример #20
0
 // Delete customer from the database.
 @Override
 public boolean deleteCustomer(int id, int customerId) {
   Trace.info("RM::deleteCustomer(" + id + ", " + customerId + ") called.");
   synchronized (syncLock) {
     Customer cust = (Customer) readData(id, Customer.getKey(customerId));
     removeData(id, cust.getKey());
     Trace.info("RM::deleteCustomer(" + id + ", " + customerId + ") OK.");
     return true;
   }
 }
Пример #21
0
 // query the price of an item
 protected int queryPrice(int id, String key) {
   Trace.info("RM::queryCarsPrice(" + id + ", " + key + ") called");
   ReservableItem curObj = (ReservableItem) readData(id, key);
   int value = 0;
   if (curObj != null) {
     value = curObj.getPrice();
   } // else
   Trace.info("RM::queryCarsPrice(" + id + ", " + key + ") returns cost=$" + value);
   return value;
 }
  // @B8a
  boolean setLength(long length) throws IOException, AS400SecurityException {
    // Assume that we are connected to the server.

    // Prepare to issue a 'change attributes' request.
    ClientAccessDataStream ds = null;

    int fileHandle = UNINITIALIZED;

    try {
      // Open the file for read/write, get a file handle, and call 'change attributes'.
      fileHandle = createFileHandle(IFSOpenReq.WRITE_ACCESS, IFSOpenReq.OPEN_OPTION_FAIL_OPEN);
      if (fileHandle == UNINITIALIZED) {
        if (Trace.traceOn_)
          Trace.log(
              Trace.ERROR,
              "Unable to create handle to file " + path_ + ". IFSReturnCodeRep return code",
              errorRC_);
        return false;
      }
      IFSChangeAttrsReq req = new IFSChangeAttrsReq(fileHandle, length, serverDatastreamLevel_);
      ds = (ClientAccessDataStream) server_.sendAndReceive(req);
    } catch (ConnectionDroppedException e) {
      Trace.log(Trace.ERROR, "Byte stream server connection lost.");
      connectionDropped(e);
    } catch (InterruptedException e) {
      Trace.log(Trace.ERROR, "Interrupted");
      throw new InterruptedIOException(e.getMessage());
    } finally {
      close(fileHandle); // we don't need this handle anymore
    }

    // Verify the reply.
    boolean success = false;
    if (ds instanceof IFSReturnCodeRep) {
      int rc = ((IFSReturnCodeRep) ds).getReturnCode();
      if (rc == IFSReturnCodeRep.SUCCESS) success = true;
      else {
        throwSecurityExceptionIfAccessDenied(path_, rc); // check for "access denied"
        Trace.log(
            Trace.ERROR, path_ + ": IFSReturnCodeRep return code", descriptionForReturnCode(rc));
      }
    } else {
      // Unknown data stream.
      Trace.log(Trace.ERROR, "Unknown reply data stream", ds.data_);
      throw new InternalErrorException(
          Integer.toHexString(ds.getReqRepID()), InternalErrorException.DATA_STREAM_UNKNOWN);
    }

    // Back off the file pointer if needed.
    if (fileOffset_ > length) {
      fileOffset_ = length;
    }

    return success;
  }
 private Trace createTrace(String traceClass) {
   Trace trace;
   try {
     final Class clazz = Class.forName(traceClass);
     trace = (Trace) clazz.newInstance();
     trace.setPipelineContext(this);
   } catch (final Exception e) {
     throw new OXFException(e);
   }
   return trace;
 }
Пример #24
0
 // Perform an OS/400 CCSID to Unicode conversion.
 final String byteArrayToString(
     byte[] buf, int offset, int length, BidiConversionProperties properties) {
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Converting byte array to string for ccsid: " + ccsid_,
         buf,
         offset,
         length);
   // Length could be twice as long because of surrogates
   char[] dest = new char[length];
   int to = 0;
   for (int i = 0; i < length / 2; ++i) {
     try {
       int fromIndex =
           ((0x00FF & buf[(i * 2) + offset]) << 8) + (0x00FF & buf[(i * 2) + 1 + offset]);
       dest[to] = toUnicode_[fromIndex];
       // Check if surrogate lookup needed.
       if (dest[to] == 0xD800) {
         if (toUnicodeSurrogate_ != null) {
           char[] surrogates = toUnicodeSurrogate_[fromIndex];
           if (surrogates != null) {
             dest[to] = surrogates[0];
             to++;
             dest[to] = surrogates[1];
             to++;
           } else {
             // surrogate not defined, replace with sub
             dest[to] = dbSubUnic_;
             to++;
           }
         } else {
           // Not handling surrogates, replace with sub
           dest[to] = dbSubUnic_;
           to++;
         }
       } else {
         // Single character.  Increment counter;
         to++;
       }
     } catch (ArrayIndexOutOfBoundsException aioobe) {
       // Swallow this if we are doing fault-tolerant conversion.
       if (!CharConverter.isFaultTolerantConversion()) {
         throw aioobe;
       }
     }
   }
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Destination string for ccsid: " + ccsid_,
         ConvTable.dumpCharArray(dest));
   return String.copyValueOf(dest, 0, to);
 }
Пример #25
0
 /**
  * Synchronize tern script paths with JSDT "Include Path"
  *
  * @param jsProject
  * @param ternProject
  */
 private void synchTernScriptPaths(IJavaScriptProject jsProject, IIDETernProject ternProject) {
   try {
     ternProject.removeExternalScriptPaths(JSDT_EXTERNAL_LABEL);
     IIncludePathEntry[] entries = jsProject.getRawIncludepath();
     for (int i = 0; i < entries.length; i++) {
       IIncludePathEntry entry = entries[i];
       switch (entry.getEntryKind()) {
         case IIncludePathEntry.CPE_LIBRARY:
           // TODO : manage JSDT library
           // JSDT Source file => Tern script path file.
           /*IFolder libFolder = ResourcesPlugin.getWorkspace().getRoot()
           		.getFolder(entry.getPath());
           try {
           	ternProject.addExternalScriptPath(libFolder,
           			ScriptPathsType.FOLDER, JSDT_EXTERNAL_LABEL);
           } catch (IOException e) {
           	Trace.trace(Trace.SEVERE,
           			"Error while adding external tern script path for project "
           					+ ternProject.getProject().getName(), e);
           }*/
           break;
         case IIncludePathEntry.CPE_SOURCE:
           if (entry.getPath().segmentCount() == 1) {
             // It's a project
             synchTernProjectScriptPaths(ternProject, entry);
           } else {
             // It's a folder
             // JSDT Source folder => Tern script path folder.
             IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(entry.getPath());
             try {
               ternProject.addExternalScriptPath(
                   folder, ScriptPathsType.FOLDER, JSDT_EXTERNAL_LABEL);
             } catch (IOException e) {
               Trace.trace(
                   Trace.SEVERE,
                   "Error while adding external tern script path for project "
                       + ternProject.getProject().getName(),
                   e);
             }
           }
           break;
         case IIncludePathEntry.CPE_PROJECT:
           // JS file?
           synchTernProjectScriptPaths(ternProject, entry);
           break;
       }
     }
   } catch (JavaScriptModelException e) {
     Trace.trace(
         Trace.SEVERE,
         "Error while getting JSDT ClassPath for project " + ternProject.getProject().getName(),
         e);
   }
 }
Пример #26
0
 // Query the price of an item.
 protected int queryPrice(int id, String key) {
   Trace.info("RM::queryPrice(" + id + ", " + key + ") called.");
   synchronized (syncLock) {
     ReservableItem curObj = (ReservableItem) readData(id, key);
     int value = 0;
     if (curObj != null) {
       value = curObj.getPrice();
     }
     Trace.info("RM::queryPrice(" + id + ", " + key + ") OK: $" + value);
     return value;
   }
 }
Пример #27
0
 // Create a new flight, or add seats to existing flight.
 // Note: if flightPrice <= 0 and the flight already exists, it maintains
 // its current price.
 @Override
 public boolean addFlight(int id, int flightNumber, int numSeats, int flightPrice) {
   Trace.info(
       "RM::addFlight("
           + id
           + ", "
           + flightNumber
           + ", $"
           + flightPrice
           + ", "
           + numSeats
           + ") called.");
   Flight curObj = (Flight) readData(id, Flight.getKey(flightNumber));
   synchronized (syncLock) {
     if (curObj == null) {
       // Doesn't exist; add it.
       Flight newObj = new Flight(flightNumber, numSeats, flightPrice);
       writeData(id, newObj.getKey(), newObj);
       Trace.info(
           "RM::addFlight("
               + id
               + ", "
               + flightNumber
               + ", $"
               + flightPrice
               + ", "
               + numSeats
               + ") OK.");
     } else {
       // Add seats to existing flight and update the price.
       curObj.setCount(curObj.getCount() + numSeats);
       if (flightPrice > 0) {
         curObj.setPrice(flightPrice);
       }
       writeData(id, curObj.getKey(), curObj);
       Trace.info(
           "RM::addFlight("
               + id
               + ", "
               + flightNumber
               + ", $"
               + flightPrice
               + ", "
               + numSeats
               + ") OK: "
               + "seats = "
               + curObj.getCount()
               + ", price = $"
               + flightPrice);
     }
     return (true);
   }
 }
Пример #28
0
 public void start(int backoff, long lastConnect) {
   if (state.getAndSet(State.STARTING) == State.STARTING) {
     Trace.debug("In the process of starting watch already.  Returning early");
     return;
   }
   this.backoff = backoff;
   this.lastConnect = lastConnect;
   Trace.info("Starting watch on project {0} for kind {1}", project.getName(), kind);
   IClient client = getClientFor(project);
   if (client != null) {
     new RestartWatchJob(client).schedule();
   }
 }
Пример #29
0
  private ComputedPlan generatePlan(GridDomain map, GridCell start, GridCell goal) {

    mapinfo = new MapInfo(map);

    // initialize open set with start node
    mapinfo.add(start, 0f, map.hCost(start, goal));

    // repeat while states are left in open set
    while (mapinfo.isOpenEmpty() == false) {
      GridCell current = mapinfo.closeCheapestOpen();

      // timer.getCurrentNanotime();
      // timer.getCurrentNanotime();
      // timer.getCurrentNanotime();

      Trace.print(current);

      // if goal has been reached, return path
      if (current == goal) {
        Trace.print("found goal!");
        return mapinfo.computePlan(goal);
      }

      // iterate through neighboring nodes
      for (State neighbor : map.getSuccessors(current)) {
        //				threadMX.getCurrentThreadCpuTime();
        //				threadMX.getCurrentThreadCpuTime();
        //				threadMX.getCurrentThreadCpuTime();
        // consider node if it can be entered and is not in closed list
        if (map.isBlocked(neighbor) == false && mapinfo.isClosed((GridCell) neighbor) == false) {

          // get g cost of neighbor
          float gCost = mapinfo.getGCost(current) + map.cost(current, neighbor);

          if (mapinfo.isOpen((GridCell) neighbor) == false) {
            // node not previously encountered, add it to the open set
            mapinfo.add((GridCell) neighbor, gCost, map.hCost(neighbor, goal), current);
          } else if (gCost < mapinfo.getGCost((GridCell) neighbor)) {
            // more direct route to node found, update it
            // NOTE: this can never happen with an admissible heuristic!
            // System.out.println("failing now..." + gCost + " < " + mapinfo.getGCost((GridCell)
            // neighbor));
            // mapInfo.setGCost(neighbor, gCost);
            // mapInfo.setParent(neighbor, current);
          }
        }
      }
    }
    // no goal found
    return null;
  }
  IFSKey lock(
      long offset, // @B2A - code relocated from IFSFileOutputStreamImplRemote,etc.
      long length)
      throws IOException, AS400SecurityException {
    // Assume the arguments have been validated by the caller.

    // Attempt to lock the file.
    ClientAccessDataStream ds = null;
    try {
      // Issue a mandatory, exclusive lock bytes request.  Mandatory
      // means that the file system enforces the lock by causing any
      // operation which conflicts with the lock to fail.  Exclusive
      // means that only the owner of the lock can read or write the
      // locked area.
      IFSLockBytesReq req =
          new IFSLockBytesReq(fileHandle_, true, false, offset, length, serverDatastreamLevel_);
      ds = (ClientAccessDataStream) server_.sendAndReceive(req);
    } catch (ConnectionDroppedException e) {
      Trace.log(Trace.ERROR, "Byte stream server connection lost");
      connectionDropped(e);
    } catch (InterruptedException e) {
      Trace.log(Trace.ERROR, "Interrupted", e);
      throw new InterruptedIOException(e.getMessage());
    }

    // Verify the reply.
    if (ds instanceof IFSLockBytesRep) {
      int rc = ((IFSLockBytesRep) ds).getReturnCode();
      if (rc != 0) {
        Trace.log(Trace.ERROR, "IFSLockBytesRep return code", rc);
        throw new ExtendedIOException(path_, rc);
      }
    } else if (ds instanceof IFSReturnCodeRep) {
      int rc = ((IFSReturnCodeRep) ds).getReturnCode();
      if (rc != IFSReturnCodeRep.SUCCESS) {
        throwSecurityExceptionIfAccessDenied(path_, rc); // check for "access denied"
        Trace.log(Trace.ERROR, "IFSReturnCodeRep return code", descriptionForReturnCode(rc));
        throw new ExtendedIOException(path_, rc);
      }
    } else {
      // Unknown data stream.
      Trace.log(Trace.ERROR, "Unknown reply data stream", ds.data_);
      throw new InternalErrorException(
          Integer.toHexString(ds.getReqRepID()), InternalErrorException.DATA_STREAM_UNKNOWN);
    }

    // Generate the key for this lock.
    IFSKey key = new IFSKey(fileHandle_, offset, length, true);

    return key;
  }