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);
 }
  /**
   * 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);
  }
  /** 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;
  }
  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);
    }
  }
 /** 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);
   }
 }
  // Opens the file with specified access and option, and returns a file handle.
  // If failure, sets errorRC_ and returns UNINITIALIZED.
  int createFileHandle(int access, int openOption) // @D1C @B8c
      throws IOException, AS400SecurityException {
    int returnCode = IFSReturnCodeRep.FILE_NOT_FOUND;
    int fileHandle = UNINITIALIZED;
    errorRC_ = 0;

    // Try to open the file for the specified type of access.
    try {
      // Process an open file request.
      // For 3rd parm (file data CCSID), specify 0 since we don't care about CCSID.
      IFSOpenReq req =
          new IFSOpenReq(
              getPathnameAsBytes(),
              preferredServerCCSID_,
              0,
              access,
              IFSOpenReq.DENY_NONE,
              IFSOpenReq.NO_CONVERSION,
              openOption,
              serverDatastreamLevel_); // @D1C
      ClientAccessDataStream ds = (ClientAccessDataStream) server_.sendAndReceive(req);
      if (ds instanceof IFSOpenRep) {
        // The open was successful.  Close the file if appropriate.
        returnCode = IFSReturnCodeRep.SUCCESS;
        fileHandle = ((IFSOpenRep) ds).getFileHandle(); // @B8a
      } else if (ds instanceof IFSReturnCodeRep) {
        returnCode = ((IFSReturnCodeRep) ds).getReturnCode();
        throwSecurityExceptionIfAccessDenied(path_, returnCode); // check for "access denied"
      } 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);
      }
    } catch (ConnectionDroppedException e) {
      Trace.log(Trace.ERROR, "Byte stream server connection lost", e);
      connectionDropped(e);
    } catch (InterruptedException e) {
      Trace.log(Trace.ERROR, "Interrupted", e);
      throw new InterruptedIOException(e.getMessage());
    }

    if (returnCode != IFSReturnCodeRep.SUCCESS) {
      if (Trace.isTraceOn() && Trace.isTraceDiagnosticOn()) {
        Trace.log(
            Trace.DIAGNOSTIC,
            "Unable to open file " + path_ + ": " + "IFSReturnCodeRep return code",
            descriptionForReturnCode(returnCode));
      }
      errorRC_ = returnCode;
      return UNINITIALIZED;
    }

    return fileHandle;
  }
  // @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;
  }
 // 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);
 }
  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;
  }
 final byte[] stringToByteArray(char[] src, int offset, int length) {
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Converting string to byte array for ccsid: " + ccsid_,
         ConvTable.dumpCharArray(src, offset, length));
   byte[] dest = new byte[length * 2];
   for (int destPos = 0, srcPos = offset; srcPos < length; ++srcPos) {
     dest[destPos++] = (byte) (src[srcPos] >>> 8);
     dest[destPos++] = (byte) src[srcPos];
   }
   if (Trace.traceOn_)
     Trace.log(Trace.CONVERSION, "Destination byte array for ccsid: " + ccsid_, dest);
   return dest;
 }
Exemple #12
0
  /**
   * Returns the value of the "list status indicator" field returned by QGY* API's.
   *
   * @param listInformation The "list information" structure returned by a QGY* API (that requested
   *     the building of a list).
   * @return The converted value of the "list status information" field. Possible values are '0',
   *     '1', '2', '3', '4', or '5'.
   * @throws ErrorCompletingRequestException if the List Status Information is other than
   *     "complete", "being built", or "pending"; or if the Information Complete Indicator is
   *     "interrupted".
   */
  private static char checkListStatus(byte[] listInformation)
      throws ErrorCompletingRequestException {
    char infoCompleteIndicator, listStatusIndicator;
    try {
      // Convert the two CHAR(1) fields from EBCDIC to Unicode.
      byte[] arry = {listInformation[16]}; // ICI is at offset 16
      infoCompleteIndicator = new CharConverter(37).byteArrayToString(arry, 0, 1).charAt(0);
      arry[0] = listInformation[30]; // LSI is at offset 30
      listStatusIndicator = new CharConverter(37).byteArrayToString(arry, 0, 1).charAt(0);
    } catch (java.io.UnsupportedEncodingException e) { // will never happen
      throw new InternalErrorException(InternalErrorException.UNEXPECTED_EXCEPTION, e.getMessage());
    }

    switch (listStatusIndicator) {
      case LIST_COMPLETE:
        break; // This is the indicator that we normally expect.

      case LIST_BEING_BUILT:
      case LIST_PENDING:
        // These status values are unusual, but aren't necessarily error conditions
        // (even if we indicated we wanted the list built synchronously).
        if (Trace.traceOn_)
          Trace.log(Trace.DIAGNOSTIC, "List status indicator:", listStatusIndicator);
        break;

      default: // any other status
        StringBuffer msg = new StringBuffer("Unable to synchronously build object list on server.");

        try {
          msg.append("\n  List status indicator: " + listStatusIndicator);
          msg.append("\n  Info complete indicator: " + infoCompleteIndicator);
          msg.append("\n  Total records:    " + BinaryConverter.byteArrayToInt(listInformation, 0));
          msg.append("\n  Records returned: " + BinaryConverter.byteArrayToInt(listInformation, 4));
        } catch (Throwable t) {
        } // will never happen
        finally {
          Trace.log(Trace.ERROR, msg.toString());
        }
        throw new ErrorCompletingRequestException(ErrorCompletingRequestException.AS400_ERROR);
    }

    if (infoCompleteIndicator == INFORMATION_INTERRUPTED) {
      Trace.log(Trace.ERROR, "Info complete indicator: " + infoCompleteIndicator);
      throw new ErrorCompletingRequestException(ErrorCompletingRequestException.AS400_ERROR);
    }

    return listStatusIndicator;
  }
 // Constructor.
 ConvTableDoubleMap(int ccsid, char[] toUnicode, char[] fromUnicode) {
   super(ccsid);
   toUnicode_ = decompress(toUnicode);
   fromUnicode_ = decompress(fromUnicode);
   if (Trace.traceOn_)
     Trace.log(Trace.CONVERSION, "Successfully loaded double-byte map for ccsid: " + ccsid_);
 }
 // $A1
 public void sync() throws IOException {
   if (parent_ == null) {
     Trace.log(Trace.ERROR, "IFSFileDescriptor.sync() was called when parent is null.");
   }
   // Note: UserSpaceImplRemote creates an IFSFileDescriptorImplRemote directly.
   else if (parent_ instanceof IFSRandomAccessFileImplRemote) {
     ((IFSRandomAccessFileImplRemote) parent_).flush();
   } else if (parent_ instanceof IFSFileOutputStreamImplRemote) {
     ((IFSFileOutputStreamImplRemote) parent_).flush();
   } else {
     Trace.log(
         Trace.WARNING,
         "IFSFileDescriptor.sync() was called "
             + "when parent is neither an IFSRandomAccessFile nor an IFSFileOutputStream.");
   }
 }
  static {
    try {
      EventSetDescriptor propertyChange =
          new EventSetDescriptor(
              BEAN_CLASS, "propertyChange", PropertyChangeListener.class, "propertyChange");
      propertyChange.setDisplayName(ResourceBundleLoader.getText("EVT_NAME_PROPERTY_CHANGE"));
      propertyChange.setShortDescription(ResourceBundleLoader.getText("EVT_DESC_PROPERTY_CHANGE"));

      eventSetDescriptors_ = new EventSetDescriptor[] {propertyChange};

      PropertyDescriptor path = new PropertyDescriptor("path", BEAN_CLASS);
      path.setBound(true);
      path.setConstrained(false);
      path.setDisplayName(ResourceBundleLoader.getText("PROP_NAME_PATH"));
      path.setShortDescription(ResourceBundleLoader.getText("PROP_DESC_PATH"));

      PropertyDescriptor system = new PropertyDescriptor("system", BEAN_CLASS);
      system.setBound(true);
      system.setConstrained(false);
      system.setDisplayName(ResourceBundleLoader.getText("PROP_NAME_SYSTEM"));
      system.setShortDescription(ResourceBundleLoader.getText("PROP_DESC_SYSTEM"));

      propertyDescriptors_ = new PropertyDescriptor[] {path, system};
    } catch (IntrospectionException e) {
      Trace.log(Trace.ERROR, "Unexpected IntrospectionException:", e);
      throw new InternalErrorException(InternalErrorException.UNEXPECTED_EXCEPTION);
    }
  }
 // Perform a Unicode to AS/400 CCSID conversion.
 final byte[] stringToByteArray(String source, BidiConversionProperties properties) {
   char[] src = source.toCharArray();
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Converting string to byte array for ccsid: " + ccsid_,
         ConvTable.dumpCharArray(src));
   byte[] dest = new byte[src.length * 2];
   for (int i = 0; i < src.length; ++i) {
     dest[i * 2] = (byte) (fromUnicode_[src[i]] >>> 8);
     dest[i * 2 + 1] = (byte) (0x00FF & fromUnicode_[src[i]]);
   }
   if (Trace.traceOn_)
     Trace.log(Trace.CONVERSION, "Destination byte array for ccsid: " + ccsid_, dest);
   return dest;
 }
 public void close() {
   try {
     close0();
   } catch (IOException e) {
     Trace.log(Trace.ERROR, "Error while closing file " + path_, e);
   }
 }
 // Cast an IFSFileDescriptorImpl object into an IFSFileDescriptorImplRemote.
 // Used by various IFS*ImplRemote classes.
 static IFSFileDescriptorImplRemote castImplToImplRemote(IFSFileDescriptorImpl fd) {
   try {
     return (IFSFileDescriptorImplRemote) fd;
   } catch (ClassCastException e) {
     Trace.log(Trace.ERROR, "Argument is not an instance of IFSFileDescriptorImplRemote", e);
     throw new InternalErrorException(InternalErrorException.UNEXPECTED_EXCEPTION);
   }
 }
 final String byteArrayToString(byte[] buf, int offset, int length) {
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Converting byte array to string for ccsid: " + ccsid_,
         buf,
         offset,
         length);
   char[] dest = new char[length / 2];
   for (int destPos = 0, bufPos = offset; destPos < dest.length; ++destPos) {
     dest[destPos] = (char) (((buf[bufPos++] & 0xFF) << 8) + (buf[bufPos++] & 0xFF));
   }
   if (Trace.traceOn_)
     Trace.log(
         Trace.CONVERSION,
         "Destination string for ccsid: " + ccsid_,
         ConvTable.dumpCharArray(dest));
   return String.copyValueOf(dest);
 }
  /**
   * Undoes a lock on this file.
   *
   * @param key The key for the lock.
   * @exception IOException If an error occurs while communicating with the server.
   * @see IFSKey
   * @see #lock
   */
  void unlock(IFSKey key) // @B2A - code relocated from IFSFileOutputStreamImplRemote,etc.
      throws IOException, AS400SecurityException {
    // Assume the argument has been validated by the caller.

    // Verify that this key is compatible with this file.
    if (key.fileHandle_ != fileHandle_) {
      Trace.log(Trace.ERROR, "Attempt to use IFSKey on different file stream.");
      throw new ExtendedIllegalArgumentException(
          "key", ExtendedIllegalArgumentException.PARAMETER_VALUE_NOT_VALID);
    }

    // Attempt to unlock the file.
    ClientAccessDataStream ds = null;
    // Issue an unlock bytes request.
    IFSUnlockBytesReq req =
        new IFSUnlockBytesReq(
            key.fileHandle_, key.offset_, key.length_, key.isMandatory_, serverDatastreamLevel_);
    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 the reply.
    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);
    }
  }
  // Helper method used to decompress conversion tables when they are initialized.
  char[] decompress(char[] arr) {
    if (Trace.traceOn_)
      Trace.log(
          Trace.CONVERSION,
          "Decompressing double-byte conversion table for ccsid: " + ccsid_,
          arr.length);
    char[] buf = new char[65536];
    int c = 0;
    for (int i = 0; i < arr.length; ++i) {
      if (arr[i] == cic_) {
        if (arr[i + 1] == pad_) {
          buf[c++] = arr[i++];
        } else {
          long max = (0xFFFF & arr[i + 1]) + (0xFFFF & c);
          char ch = arr[i + 2];
          while (c < max) {
            buf[c++] = ch;
          }
          i += 2;
        }
      } else if (arr[i] == ric_) {
        if (arr[i + 1] == pad_) {
          buf[c++] = arr[i++];
        } else {
          int start = (0xFFFF & arr[i + 2]);
          int num = (0xFFFF & arr[i + 1]);
          for (int j = start; j < (num + start); ++j) {
            buf[c++] = (char) j;
          }
          i += 2;
        }
      } else if (arr[i] == hbic_) {
        if (arr[i + 1] == pad_) {
          buf[c++] = arr[i++];
        } else {
          int hbNum = (0x0000FFFF & arr[++i]);
          char firstChar = arr[++i];
          char highByteMask = (char) (0xFF00 & firstChar);
          buf[c++] = firstChar;
          ++i;
          for (int j = 0; j < hbNum; ++j) {
            char both = arr[i + j];
            buf[c++] = (char) (highByteMask + ((0xFF00 & both) >>> 8));
            buf[c++] = (char) (highByteMask + (0x00FF & both));
          }
          i = i + hbNum - 1;
        }
      } else { // Regular character.
        buf[c++] = arr[i];
      }
    }

    return buf;
  }
 /**
  * Returns the DDS description for the field. This is a string containing the description of the
  * field as it would be specified in a DDS source file. This method is used by
  * AS400File.createDDSSourceFile (called by the AS400File.create methods) to specify the field in
  * the DDS source file which is used to create the file for the user who has passed in a
  * RecordFormat object.
  *
  * @return The DDS description of this field properly formatted for entry into a DDS source file.
  */
 String[] getDDSDescription() {
   Vector v = new Vector();
   // Name columns (10)
   StringBuffer desc = new StringBuffer(ddsName_);
   // Blank pad the ddsName to 10 characters.
   while (desc.length() < 10) {
     desc.append(" ");
   }
   // Reference column (1)
   if (!refFld_.equals("")) {
     desc.append("R");
   } else {
     desc.append(" ");
   }
   // Get length as 5 digit string, right justified
   // Length columns (5)
   desc.append("     "); // No length can be specified for a date field
   // Type column (1)
   desc.append("L");
   // Decimal positions columns (2)
   desc.append("  ");
   // Not used columns (7)
   desc.append("       ");
   // Add fixed portion of DDS description to Vector
   v.addElement(desc.toString());
   // Add the field level keywords
   String[] keywords = super.getFieldFunctions();
   if (keywords != null) {
     for (int i = 0; i < keywords.length; ++i) {
       v.addElement(keywords[i]);
     }
   }
   if (dateFormat_ != null) {
     v.addElement("DATFMT(" + dateFormat_ + ") ");
   }
   if (dateSeparator_ != null) {
     if (!formatHasFixedSeparator(dateFormat_)) {
       v.addElement("DATSEP('" + dateSeparator_ + "') ");
     } else {
       if (Trace.traceOn_)
         Trace.log(Trace.DIAGNOSTIC, "DDS date format " + dateFormat_ + " has a fixed separator.");
     }
   }
   if (defaultValue_ != null) {
     v.addElement("DFT('" + defaultValue_.toString() + "') ");
   }
   // @B0A
   else if (isDFTNull_) {
     v.addElement("DFT(*NULL) ");
   }
   String[] s = new String[v.size()];
   v.copyInto(s);
   return s;
 }
Exemple #23
0
  /**
   * Calls QGYGTLE (repeatedly if necessary) until the specified list is completely built. For use
   * following calls to APIs that return an "Open list information format" structure.
   *
   * @param system The system where the list is being built.
   * @param listHandle The list handle for the list.
   * @param listInformation The "list information" structure returned by a QGY* API (that requested
   *     the building of a list).
   * @return The final "list information" structure.
   */
  static byte[] waitForListToComplete(AS400 system, byte[] listHandle, byte[] listInformation)
      throws AS400SecurityException, ErrorCompletingRequestException, InterruptedException,
          IOException, ObjectDoesNotExistException {
    ProgramCall pgmCall = null; // for calling QGYGTLE
    final int waitSecondsPerIteration = 1; // wait 1 second between retries
    int accumulatedWaitSeconds = 0; // accumulated total wait time
    int maxWaitSeconds = getMaxWaitTime();

    char listStatus = checkListStatus(listInformation);

    while (listStatus != LIST_COMPLETE && accumulatedWaitSeconds < maxWaitSeconds) {
      try {
        Thread.sleep(waitSecondsPerIteration * 1000); // wait for 1 second
        accumulatedWaitSeconds += waitSecondsPerIteration;
      } catch (InterruptedException ie) {
      } // ignore

      if (Trace.traceOn_)
        Trace.log(Trace.DIAGNOSTIC, "Calling QGYGTLE.PGM to wait for list to be completely built.");

      // See if the building of the list (on the server) has completed yet.

      // Note: Even when we specify '-1' for the "number of records" parameter on the QGYOxxx
      // request (to build the list synchronously), we can encounter a "list being built" status, if
      // the request is building a massively large list of objects.

      if (pgmCall == null) pgmCall = new ProgramCall(system);
      listInformation = refreshListInformation(listHandle, pgmCall);
      listStatus = checkListStatus(listInformation);
    }

    if (listStatus != LIST_COMPLETE) {
      Trace.log(
          Trace.ERROR,
          "The building of the list did not complete within the specified time limit of "
              + maxWaitSeconds
              + " seconds.");
      throw new ErrorCompletingRequestException(ErrorCompletingRequestException.AS400_ERROR);
    }
    return listInformation;
  }
 private static final void throwSecurityExceptionIfAccessDenied(String path, int returnCode)
     throws AS400SecurityException {
   if (returnCode == IFSReturnCodeRep.ACCESS_DENIED_TO_DIR_ENTRY
       || returnCode == IFSReturnCodeRep.ACCESS_DENIED_TO_REQUEST) {
     if (Trace.traceOn_)
       Trace.log(
           Trace.DIAGNOSTIC,
           "Access denied to file " + path + ". " + "IFSReturnCodeRep return code",
           returnCode);
     throw new AS400SecurityException(path, AS400SecurityException.DIRECTORY_ENTRY_ACCESS_DENIED);
   }
 }
 // Ignores fileHandle if state==false.
 void setOpen(boolean state, int fileHandle) {
   if (state == true) {
     if (fileHandle == UNINITIALIZED) {
       Trace.log(Trace.ERROR, "Called setOpen with invalid file handle: " + fileHandle);
       throw new InternalErrorException(InternalErrorException.UNEXPECTED_EXCEPTION);
     } else {
       if (fileHandle != fileHandle_) close(); // close currently-open handle if different
       fileHandle_ = fileHandle;
     }
   }
   isOpen_ = state;
 }
 /**
  * Disconnects from the byte stream server.
  *
  * @exception ConnectionDroppedException If the connection is dropped unexpectedly.
  */
 void connectionDropped(
     ConnectionDroppedException e) // @B2A - code relocated from IFSFileOutputStreamImplRemote,etc.
     throws ConnectionDroppedException {
   if (server_ != null) {
     system_.disconnectServer(server_);
     server_ = null;
     try {
       close();
     } catch (Exception exc) {
     } // Note: Not relevant for IFSFileImplRemote.
   }
   Trace.log(Trace.ERROR, "Byte stream connection lost.");
   throw e;
 }
Exemple #27
0
 // Returns the maximum number of seconds to wait for a list to be built.
 private static int getMaxWaitTime() {
   int listWaitTimeout = DEFAULT_MAX_WAIT_TIME;
   String propVal = SystemProperties.getProperty(SystemProperties.LIST_WAIT_TIMEOUT);
   if (propVal != null) {
     try {
       listWaitTimeout = Integer.parseInt(propVal);
       if (listWaitTimeout == 0) listWaitTimeout = Integer.MAX_VALUE; // '0' means "no limit"
     } catch (Exception e) {
       if (Trace.traceOn_)
         Trace.log(Trace.WARNING, "Error retrieving listWaitTimeout property value:", e);
     }
   }
   return listWaitTimeout;
 }
  /** Chooses the appropriate implementation. */
  void chooseImpl() throws IOException, AS400SecurityException {
    // We need to get the system to connect to...
    AS400 system = getSystem();
    if (system == null) {
      Trace.log(Trace.ERROR, "Attempt to use AFPResource before setting system.");
      throw new ExtendedIllegalStateException(
          "system", ExtendedIllegalStateException.PROPERTY_NOT_SET);
    }

    impl_ =
        (PrintObjectImpl)
            system.loadImpl2(
                "com.ibm.as400.access.AFPResourceImplRemote",
                "com.ibm.as400.access.AFPResourceImplProxy");
    super.setImpl();
  }
  // Sets the values of the fields relating to file size.
  private final void setFileSizeFields(long fileSize, int datastreamLevel) {
    if (datastreamLevel < 16) { // Just set the old field.
      if (fileSize > (long) Integer.MAX_VALUE) {
        if (Trace.traceOn_)
          Trace.log(
              Trace.WARNING,
              "Specified fileSize value ("
                  + fileSize
                  + ") exceeds maximum file length supported by system.");
        fileSize = (long) Integer.MAX_VALUE; // set to maximum possible 'int' value
      }
      set32bit((int) fileSize, FILE_SIZE_OFFSET);
    } else {
      // The old field must be zero.
      set32bit(0, FILE_SIZE_OFFSET);

      // Also set the new "large" field.
      set64bit(fileSize, LARGE_FILE_SIZE_OFFSET);
    }
  }
 // Note: We call this "finalize0" because a "finalize" method would need to be protected; and we
 // want other classes to call this method.
 void finalize0() // @B2A
     throws Throwable {
   try {
     if (fileHandle_ != UNINITIALIZED) // @B8c
     {
       // Close the file.  Send a close request to the server.
       IFSCloseReq req = new IFSCloseReq(fileHandle_);
       try {
         server_.sendAndDiscardReply(req);
       } finally {
         // Reset isOpen_ and fileHandle_ to reflect that it is closed @A3A
         isOpen_ = false; // @A3A
         fileHandle_ = UNINITIALIZED; // @A3A
         // close0();                                                 //@A3D
       }
     }
   } catch (Throwable e) {
     Trace.log(Trace.ERROR, "Error during finalization.", e);
   } finally {
     super.finalize();
   }
 }