@Override
 @SuppressWarnings("unchecked")
 public synchronized void write(ArchivePacket packet) throws IOException {
   if (!isOpen()) {
     throw new IOException("not open");
   }
   if (out == null) {
     throw new IOException("no output stream found");
   }
   if (packet == null || packet.payload() == null) {
     throw new IOException("no payload to write for entry");
   }
   byte[] buf = packet.payload().toString().getBytes();
   String name = ArchiveUtils.encodeArchiveEntryName(packet);
   ArchiveEntry entry = out.newArchiveEntry();
   entry.setName(name);
   entry.setLastModified(new Date());
   entry.setEntrySize(buf.length);
   out.putArchiveEntry(entry);
   out.write(buf);
   out.closeArchiveEntry();
   packetCounter++;
   if (watcher.getBytesToTransfer() != 0
       && watcher.getBytesTransferred() > watcher.getBytesToTransfer()) {
     logger.debug(
         "bytes watcher: transferred = {}, rate {}",
         watcher.getBytesTransferred(),
         watcher.getRecentByteRatePerSecond());
     switchToNextArchive();
     watcher.resetWatcher();
   }
 }
Esempio n. 2
0
 /**
  * Maps the OSG request type to the Walrus type, including BaseMessage handling for 'regarding'
  * and correlationId mapping
  *
  * @param outputClass
  * @param request
  * @return
  */
 public <O extends WalrusRequestType, I extends ObjectStorageRequestType> O proxyWalrusRequest(
     Class<O> outputClass, I request) {
   O outputRequest = (O) Classes.newInstance(outputClass);
   outputRequest = (O) (MessageProxy.mapExcludeNulls(request, outputRequest));
   outputRequest.regardingUserRequest(request);
   return outputRequest;
 }
  @Override
  public O serve(ServiceRequestContext ctx, I req) throws Exception {
    final TraceData traceData = getTraceData(ctx, req);
    final String method = req instanceof RpcRequest ? ((RpcRequest) req).method() : ctx.method();
    final ServerRequestAdapter requestAdapter = new InternalServerRequestAdapter(method, traceData);

    final ServerSpan serverSpan = serverInterceptor.openSpan(requestAdapter);
    final boolean sampled;
    if (serverSpan != null) {
      ctx.onEnter(() -> serverInterceptor.setSpan(serverSpan));
      ctx.onExit(serverInterceptor::clearSpan);
      sampled = serverSpan.getSample();
    } else {
      sampled = false;
    }

    try {
      final O res = delegate().serve(ctx, req);
      if (sampled) {
        ctx.requestLogFuture()
            .thenAcceptBoth(
                res.closeFuture(), (log, unused) -> closeSpan(ctx, serverSpan, log, res))
            .exceptionally(CompletionActions::log);
      }
      return res;
    } finally {
      serverInterceptor.clearSpan();
    }
  }
 @SuppressWarnings("unchecked")
 private O createArchiveOutputStream(boolean overwrite) throws IOException {
   O archiveOut;
   FileOutputStream out;
   if (!file.exists() || file.length() == 0 || overwrite) {
     out = new FileOutputStream(file);
   } else {
     throw new FileNotFoundException(
         "can't open for output, check existence or access rights: " + file.getAbsolutePath());
   }
   String pathStr = path.toString();
   Set<String> streamCodecs = CompressCodecService.getCodecs();
   for (String codec : streamCodecs) {
     if (pathStr.endsWith("." + codec)) {
       archiveOut =
           (O)
               archiveService
                   .getCodec(getName())
                   .createArchiveOutputStream(codecService.getCodec(codec).encode(out));
       archiveOut.setWatcher(watcher);
       return archiveOut;
     }
   }
   archiveOut = (O) archiveService.getCodec(getName()).createArchiveOutputStream(out);
   archiveOut.setWatcher(watcher);
   return archiveOut;
 }
 /**
  * A utility function that duplicates a set of objects.
  *
  * @param objects The set of object to be duplicated
  * @return The set of duplicated objects
  */
 @SuppressWarnings("unchecked")
 private <O extends OWLObject> Set<O> duplicateSet(Set<O> objects) {
   Set<O> dup = new HashSet<O>();
   for (O o : objects) {
     o.accept(this);
     dup.add((O) obj);
   }
   return dup;
 }
Esempio n. 6
0
 @Override
 public O compute(I x, O output) {
   if (constant == 0) {
     output.setReal(dbzVal);
   } else { // not dividing by zero
     double value = x.getRealDouble() / constant;
     output.setReal(value);
   }
   return output;
 }
Esempio n. 7
0
 /**
  * toString methode: creates a String representation of the object
  *
  * @return the String representation
  * @author info.vancauwenberge.tostring plugin
  */
 public String toString() {
   StringBuffer buffer = new StringBuffer();
   ArrayList keys = new ArrayList(hashtable.keySet());
   Collections.sort(keys);
   for (K key : (List<K>) keys) {
     ArrayList<O> vals = get(key);
     buffer.append(key.toString()).append("(").append(vals.size()).append(")").append(":\n");
     for (O val : vals) {
       buffer.append("\t").append(val.toString()).append("\n");
     }
   }
   return buffer.toString();
 }
 @Override
 public void addConnection(O connection, int direction) {
   if (this.connections[direction] != connection) {
     if (this.connections[direction] == null && this.canConnect(connection)) {
       this.connections[direction] = connection;
       connection.addConnection(this, ForgeDirection.OPPOSITES[direction]);
       if (this.worldObj.isRemote) {
         this.markDirty();
         return;
       }
       if (connection.getNetwork() == null && this.network == null) {
         this.makeNewNetwork();
         this.network.addNode(connection);
       } else {
         if (connection.getNetwork() == null) {
           this.network.addNode(connection);
         } else if (this.network == null) {
           connection.getNetwork().addNode(this);
         }
       }
     } else this.verifyConnections();
     this.markDirty();
   }
   /*int index = direction.getIndex();
   if(this.connections[index] != connection){
   	if(this.connections[index] == null && this.canConnect(connection)) {
   		this.connections[index] = connection;
   		connection.addConnection(this, direction.getOpposite());
   		if(this.worldObj.isRemote) {
   			this.markDirty();
   			return;
   		}
   		if (connection.getNetwork() == null && this.network == null){
   			this.makeNewNetwork();
   			this.network.addNode(connection);
   		}
   		else{
   			if(connection.getNetwork() == null) {
   				this.network.addNode(connection);
   			}
   			else if (this.network == null){
   				connection.getNetwork().addNode(this);
   			}
   		}
   	}
   	else
   		this.verifyConnections();
   	this.markDirty();
   }
   */
 }
Esempio n. 9
0
 @Override
 public void stop() {
   try {
     O killer = createO();
     Pilot pilot = new Pilot();
     pilot.setExtinguisher(true);
     killer.setPilot(pilot);
     for (Link<O> exit : exits) {
       exit.getQueue().putFirst(killer);
     }
   } catch (Exception e) {
     logger.log(Level.SEVERE, "Impossible to instanciate O", e);
   }
   this.stop = true;
 }
Esempio n. 10
0
 @Override
 public O compute(I x, O output) {
   double xt = x.getRealDouble();
   double value = 0.5 * Math.log((1 + xt) / (1 - xt));
   output.setReal(value);
   return output;
 }
  @Override
  public O compute(I1 z1, I2 z2, O output) {
    /*
      optimized version (fewer multiplies) : from mathworld.com
        seems to exhibit some rounding differences from textbook algorithm

    double a = z1.getRealDouble();
    double b = z1.getImaginaryDouble();
    double c = z2.getRealDouble();
    double d = z2.getImaginaryDouble();

    double ac = a*c;
    double bd = b*d;

    double x = ac - bd;
    double y = (a + b)*(c + d) - ac - bd;
    */

    // textbook version : works
    double x =
        z1.getRealDouble() * z2.getRealDouble() - z1.getImaginaryDouble() * z2.getImaginaryDouble();
    double y =
        z1.getImaginaryDouble() * z2.getRealDouble() + z1.getRealDouble() * z2.getImaginaryDouble();

    output.setComplexNumber(x, y);
    return output;
  }
  /**
   * Attaches the current local operation to the global operation so that operation runner can
   * execute local operation post response later on.
   *
   * @param <O> subtype of Operation
   * @param <L> subtype of LocalBackendOperation
   * @param globalOperation the global operation to which local operation should be attached to
   * @param currentLocalOperation the local operation to attach to the global operation
   */
  @SuppressWarnings("unchecked")
  public static <O extends Operation, L> void attachLocalOperation(
      O globalOperation, L currentLocalOperation) {
    List<?> existingAttachment =
        (List<?>) globalOperation.getAttachment(Operation.LOCALBACKENDOPERATIONS);

    List<L> newAttachment = new ArrayList<L>();

    if (existingAttachment != null) {
      // This line raises an unchecked conversion warning.
      // There is nothing we can do to prevent this warning
      // so let's get rid of it since we know the cast is safe.
      newAttachment.addAll((List<L>) existingAttachment);
    }
    newAttachment.add(currentLocalOperation);
    globalOperation.setAttachment(Operation.LOCALBACKENDOPERATIONS, newAttachment);
  }
 /**
  * Get the verified id value for an object
  *
  * @param object for which to fetch the id
  * @return the id
  * @throws IllegalStateException if the id value could not be extracted
  */
 protected final String getIdValueForObject(O object) {
   String idValue = getIdValue(object);
   if (idValue == null) {
     throw new IllegalStateException(
         "A call to idValue(Object) returned an illegal value: null for object: "
             + object.toString());
   }
   return idValue;
 }
Esempio n. 14
0
 /*@ ensures \result != "";*/
 public String toString() {
   return leftNode.toString(Node.Placement.RIGHT)
       + "("
       + key.toString()
       + ","
       + obj.toString()
       + ")"
       + rightNode.toString(Node.Placement.LEFT);
 }
Esempio n. 15
0
 @SuppressWarnings("unchecked")
 <O, R> R convert(O input, Class<R> type) {
   Class<O> inputType = (Class<O>) input.getClass();
   if (inputType == type) {
     return (R) input;
   }
   ETransformer<O, R> transformer = transformerManager.getTransformerSafe(inputType, type);
   return transformer.from(input);
 }
 @Override
 public void removeConnection(O connection) {
   for (int i = 0; i < this.connections.length; i++) {
     if (this.connections[i] == connection) {
       this.connections[i] = null;
       connection.removeConnection(this);
     }
   }
   this.markDirty();
 }
Esempio n. 17
0
  @Override
  public O compute(I input, O output) {
    double x = input.getRealDouble();
    double value;
    if (x == 0) value = 1;
    else value = Math.sin(x) / x;
    output.setReal(value);

    return output;
  }
Esempio n. 18
0
  @SuppressWarnings("unchecked")
  <O, R> List<R> convert(Iterable<O> inputs, Class<R> type) {
    Iterator<O> iterator = inputs.iterator();
    if (!iterator.hasNext()) {
      return Collections.emptyList();
    }

    List<R> results = new ArrayList<R>();
    ETransformer<O, R> transformer = null;
    for (O t : inputs) {
      if (transformer == null) {
        Class<O> inputType = (Class<O>) t.getClass();
        transformer = transformerManager.getTransformerSafe(inputType, type);
      }
      results.add(transformer.from(t));
    }

    return results;
  }
Esempio n. 19
0
  private static <I extends StreamSourceChannel, O extends StreamSinkChannel> void done(
      I source,
      O sink,
      ChannelListener<? super I> sourceListener,
      ChannelListener<? super O> sinkListener) {
    Channels.setReadListener(source, sourceListener);
    if (sourceListener == null) {
      source.suspendReads();
    } else {
      source.wakeupReads();
    }

    Channels.setWriteListener(sink, sinkListener);
    if (sinkListener == null) {
      sink.suspendWrites();
    } else {
      sink.wakeupWrites();
    }
  }
  /**
   * Get and check proper text value
   *
   * @param object object for which to get the text value
   * @return return the verified text value
   * @throws IllegalStateException if the text value could not be extracted
   */
  protected final String getTextValueForObject(O object) {
    String textValue = getTextValue(object);

    textValue = textValue.replaceAll("\\\"", "&quot;");
    if (textValue == null) {
      throw new IllegalStateException(
          "A call to textValue(Object) returned an illegal value: null for object: "
              + object.toString());
    }
    return textValue;
  }
Esempio n. 21
0
  public void addOperation(O operation) {
    operations.add(operation);

    // put it in our properties so it gets stored properly in inventory
    final String opsPropName = "operations";
    List<Map<String, Object>> ops = (List<Map<String, Object>>) getProperties().get(opsPropName);
    if (ops == null) {
      ops = new ArrayList<>();
      addProperty(opsPropName, ops);
    }
    ops.add(operation.getProperties());
  }
Esempio n. 22
0
 public final void save(File target) {
   if (target == null) {
     throw new IllegalArgumentException("A reflected cannot be saved without a valid file!");
   }
   O os = null;
   try {
     os = getCodec().newOutput(target);
     this.save(os);
     this.onSaved(target);
   } catch (IOException e) {
     throw new InvalidReflectedObjectException("File to save into cannot be accessed!", e);
   } finally {
     if (os != null) {
       try {
         os.close();
       } catch (IOException e) {
         Reflector.LOGGER.log(WARNING, "Failed to close the output stream", e);
       }
     }
   }
 }
  /**
   * Begin traversing the graph.
   *
   * @param visitor Visitor this walker is being used by.
   * @throws VisitorException if an error is encountered while walking.
   */
  @SuppressWarnings("unchecked")
  public void walk(PlanVisitor<O, P> visitor) throws VisitorException {
    // This is highly inefficient, but our graphs are small so it should be okay.
    // The algorithm works by starting at any node in the graph, finding it's
    // predecessors and calling itself for each of those predecessors.  When it
    // finds a node that has no unfinished predecessors it puts that node in the
    // list.  It then unwinds itself putting each of the other nodes in the list.
    // It keeps track of what nodes it's seen as it goes so it doesn't put any
    // nodes in the graph twice.

    List<O> fifo = new ArrayList<O>();
    Set<O> seen = new HashSet<O>();
    List<O> leaves = mPlan.getLeaves();
    if (leaves == null) return;
    for (O op : leaves) {
      doAllPredecessors(op, seen, fifo);
    }
    for (O op : fifo) {
      op.visit(visitor);
    }
  }
  public CrossReference toCrossReference(O cvObject) {
    if (cvObject == null) {
      throw new IllegalArgumentException("CvObject must not be null. ");
    }

    // name of the cv is the fullname
    String text =
        cvObject.getFullName() != null ? cvObject.getFullName() : cvObject.getShortLabel();
    String identity = cvObject.getIdentifier();

    if (identity == null) {
      throw new NullPointerException(
          cvObject.getClass().getSimpleName() + "(" + text + ") didn't have an identity");
    }

    final CvObjectXref idXref =
        findMatchingIdentityXref(
            cvObject.getXrefs(),
            identity); // XrefUtils.getIdentityXref(cvObject, CvDatabase.PSI_MI_MI_REF);

    if (idXref != null) {
      try {
        CrossReference ref = crossRefConverter.createCrossReference(idXref, false);
        ref.setText(text);
        return ref;
      } catch (Exception e) {
        throw new RuntimeException("An exception occured while building a cv object : " + text, e);
      }
    } else {
      CrossReference ref =
          new CrossReferenceImpl(CrossReferenceConverter.DATABASE_UNKNOWN, identity, text);
      return ref;
    }
  }
  @SuppressWarnings({
    "unchecked",
    "rawtypes"
  }) // OK, because type.isEnum() is checked before casting to Enum
  private static <O> void applySetters(
      final O instance, final Map<String, Method> methodMap, final Map<String, String> attributes) {

    for (Map.Entry<String, String> attribute : attributes.entrySet()) {
      final String methodName = attribute.getKey().toLowerCase();
      final Method method = methodMap.get(methodName);
      if (null == method) {
        throw new MetafactureException(
            "Method '"
                + methodName
                + "' does not exist in '"
                + instance.getClass().getSimpleName()
                + "'!");
      }
      final Class<?> type = method.getParameterTypes()[0];

      try {
        if (type == boolean.class) {
          method.invoke(instance, Boolean.valueOf(attribute.getValue()));
        } else if (type == int.class) {
          method.invoke(instance, Integer.valueOf(attribute.getValue()));
        } else if (type.isEnum()) {
          method.invoke(
              instance, Enum.valueOf((Class<Enum>) type, attribute.getValue().toUpperCase()));
        } else {
          method.invoke(instance, attribute.getValue());
        }
      } catch (IllegalArgumentException e) {
        setMethodError(methodName, instance.getClass().getSimpleName(), e);
      } catch (IllegalAccessException e) {
        setMethodError(methodName, instance.getClass().getSimpleName(), e);
      } catch (InvocationTargetException e) {
        setMethodError(methodName, instance.getClass().getSimpleName(), e);
      }
    }
  }
 @Override
 public synchronized void close() throws IOException {
   if (!isOpen) {
     return;
   }
   if (out != null) {
     out.close();
   }
   if (in != null) {
     in.close();
   }
   this.isOpen = false;
 }
Esempio n. 27
0
 public Pair(O anOWLObject, O anotherOWLObject) {
   if (anOWLObject == null) {
     throw new NullPointerException("The first memebr of this pair cannot be null");
   }
   if (anotherOWLObject == null) {
     throw new NullPointerException("The second memebr of this pair cannot be null");
   }
   if (anotherOWLObject.equals(anOWLObject)) {
     throw new IllegalArgumentException("The pair is meant to be made of two distic entities");
   }
   this.members.add(anOWLObject);
   this.members.add(anotherOWLObject);
 }
Esempio n. 28
0
  /**
   * Pass one turn. This invokes the tick() method for all Organisms, and invokes general death and
   * replication rules.
   */
  public void tick() {
    this.time++;

    // Make time pass for Organisms
    for (O o : this.getPopulation()) o.tick(this);

    // Kill dying Organisms
    for (SelectionRule<O> rule : this.settings.getDeathRules())
      for (O o : rule.select(this)) this.new Kill(o);

    // Split splitting Organisms
    for (SelectionRule<O> rule : this.settings.getSplittingRules())
      for (O o : rule.select(this)) this.new Split(o);

    // Reproduce sexy Organisms
    for (PairSelectionRule<O> rule : this.settings.getSexyRules())
      for (Pair<O, O> p : rule.select(this)) this.new Hump(p.left, p.right);

    // Execute Actions
    for (Action a : this.actions) a.execute();
    this.actions.clear();
  }
Esempio n. 29
0
  @Override
  public void compute1(final IterableInterval<I> input, final O output) {

    double moment10 = 0;

    final Cursor<I> cur = input.localizingCursor();
    while (cur.hasNext()) {
      cur.fwd();
      double x = cur.getDoublePosition(0);
      double val = cur.get().getRealDouble();
      moment10 += x * val;
    }

    output.setReal(moment10);
  }
Esempio n. 30
0
 /**
  * Append the given object to the given array, returning a new array consisting of the input array
  * contents plus the given object.
  *
  * @param array the array to append to (can be {@code null})
  * @param obj the object to append
  * @return the new array (of the same component type; never {@code null})
  */
 public static <A, O extends A> A[] addObjectToArray(A[] array, O obj) {
   Class<?> compType = Object.class;
   if (array != null) {
     compType = array.getClass().getComponentType();
   } else if (obj != null) {
     compType = obj.getClass();
   }
   int newArrLength = (array != null ? array.length + 1 : 1);
   @SuppressWarnings("unchecked")
   A[] newArr = (A[]) Array.newInstance(compType, newArrLength);
   if (array != null) {
     System.arraycopy(array, 0, newArr, 0, array.length);
   }
   newArr[newArr.length - 1] = obj;
   return newArr;
 }