Example #1
0
 private List<QName> toPids(Collection<QName> processTypes, long version) {
   ArrayList<QName> result = new ArrayList<QName>();
   for (QName pqName : processTypes) {
     result.add(toPid(pqName, version));
   }
   return result;
 }
Example #2
0
  public void getSavedLocations() {
    // System.out.println("inside getSavedLocations");				//CONSOLE * * * * * * * * * * * * *
    loc.clear(); // clear locations.  helps refresh the list when reprinting all the locations
    BufferedWriter f = null; // just in case file has not been created yet
    BufferedReader br = null;
    try {
      // attempt to open the locations file if it doesn't exist, create it
      f =
          new BufferedWriter(
              new FileWriter("savedLocations.txt", true)); // evaluated true if file does not exist
      br = new BufferedReader(new FileReader("savedLocations.txt"));

      String line; // each line is one index of the list
      loc.add("Saved Locations");
      // loop and read a line from the file as long as we don't get null
      while ((line = br.readLine()) != null)
        // add the read word to the wordList
        loc.add(line);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        // attempt the close the file

        br.close(); // close bufferedwriter
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Example #3
0
  /**
   * Load a deployment unit record stored in the db into memory.
   *
   * @param dudao
   */
  protected List<ProcessConfImpl> load(DeploymentUnitDAO dudao) {
    __log.debug("Loading deployment unit record from db: " + dudao.getName());

    File dudir = findDeployDir(dudao);

    if (dudir == null || !dudir.exists())
      throw new ContextException(
          "Deployed directory " + (dudir == null ? "(unknown)" : dudir) + " no longer there!");
    DeploymentUnitDir dud = new DeploymentUnitDir(dudir);
    // set the name with the one from database
    dud.setName(dudao.getName());
    dud.scan();

    ArrayList<ProcessConfImpl> loaded = new ArrayList<ProcessConfImpl>();

    _rw.writeLock().lock();
    try {
      _deploymentUnits.put(dud.getName(), dud);

      long version = 0;
      for (ProcessConfDAO p : dudao.getProcesses()) {
        TDeployment.Process pinfo = dud.getProcessDeployInfo(p.getType());
        if (pinfo == null) {
          __log.warn("Cannot load " + p.getPID() + "; cannot find descriptor.");
          continue;
        }

        Map<QName, Node> props = calcInitialProperties(dud.getProperties(), pinfo);
        // TODO: update the props based on the values in the DB.

        ProcessConfImpl pconf =
            new ProcessConfImpl(
                p.getPID(),
                p.getType(),
                p.getVersion(),
                dud,
                pinfo,
                dudao.getDeployDate(),
                props,
                p.getState(),
                eprContext,
                _configDir,
                generateProcessEventsAll);
        version = p.getVersion();

        _processes.put(pconf.getProcessId(), pconf);
        loaded.add(pconf);
      }

      // All processes and the DU have the same version
      dud.setVersion(version);
    } finally {
      _rw.writeLock().unlock();
    }

    return loaded;
  }
Example #4
0
  @Test
  public void fromIterable() {
    ArrayList<String> items = new ArrayList<>();
    items.add("one");
    items.add("two");
    items.add("three");

    assertEquals((Long) 3L, Observable.fromIterable(items).count().toBlocking().single());
    assertEquals("two", Observable.fromIterable(items).skip(1).take(1).toBlocking().single());
    assertEquals("three", Observable.fromIterable(items).takeLast(1).toBlocking().single());
  }
 /** Values.toArray contains all values */
 public void testDescendingValuesToArray() {
   ConcurrentNavigableMap map = dmap5();
   Collection v = map.values();
   Object[] ar = v.toArray();
   ArrayList s = new ArrayList(Arrays.asList(ar));
   assertEquals(5, ar.length);
   assertTrue(s.contains("A"));
   assertTrue(s.contains("B"));
   assertTrue(s.contains("C"));
   assertTrue(s.contains("D"));
   assertTrue(s.contains("E"));
 }
Example #6
0
 /*public int numTickGroups()
 {
 	return ticks.size();
 }*/
 public String[][] threadInfo() {
   ArrayList<String[]> V = new ArrayList();
   for (Iterator<CMLibrary> e = CMLib.libraries(); e.hasNext(); ) {
     CMLibrary lib = e.next();
     SupportThread thread = lib.getSupportThread();
     if (thread != null) {
       String[] S = new String[3];
       S[0] = thread.getName();
       S[1] = CMLib.english().returnTime(thread.milliTotal, thread.tickTotal);
       S[2] = thread.status;
       V.add(S);
     }
   }
   return V.toArray(new String[V.size()][]);
 }
Example #7
0
  private ComponentItemImpl loadComponent(ComponentItemConfig config)
      throws ComponentCreationException {
    final ComponentItemImpl component = ComponentItemImpl.newInstance(this, config);
    try {
      component.setBehavior(
          componentRegistry.loadBehavior(config.getType(), component.getContext()));
      componentList.addItem(
          component,
          new Runnable() {
            @Override
            public void run() {
              component.addEventListener(BaseEvent.class, componentListener);
              if (counterSupport instanceof AggregatedCounterSupport)
                ((AggregatedCounterSupport) counterSupport).addChild(component);
            }
          });
    } catch (ComponentCreationException e) {
      log.error("Unable to load component: " + component, e);
      badComponents.add(config);
      component.release();
      throw e;
    }

    return component;
  }
 private static void readCaptchaFile(String fileName) {
   try {
     BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
     String line;
     while ((line = reader.readLine()) != null) captchaList.add(line);
     reader.close();
   } catch (Exception exception) {
     throw new RuntimeException(exception);
   }
 }
  /*
   * public synchronized ArrayList<Request> getWorkloadsList() {
   * ArrayList<Request> workloads = new ArrayList<Request>();
   *
   * LOG.debug("Reading " + parentZnode +
   * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS);
   *
   * try { List<String> children = getChildren(parentZnode +
   * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS, null);
   *
   * if (!children.isEmpty()) { for (String child : children) { Request
   * request = new Request(); String workloadZnode = parentZnode +
   * Constants.DEFAULT_ZOOKEEPER_ZNODE_WORKLOADS + "/" + child; Stat stat =
   * zkc.exists(workloadZnode, false); if (stat != null) { byte[] bytes =
   * zkc.getData(workloadZnode, false, stat); try {
   * deserializer.deserialize(request, bytes); workloads.add(request); } catch
   * (TException e) { e.printStackTrace(); } } } } } catch (Exception e) {
   * e.printStackTrace(); }
   *
   * return workloads; }
   */
  public synchronized ArrayList<String> getClientsList() {
    ArrayList<String> clients = new ArrayList<String>();

    LOG.debug("Reading " + parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_CLIENTS);

    try {
      List<String> children =
          getChildren(parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_CLIENTS, null);
      if (!children.isEmpty()) {
        for (String child : children) {
          clients.add(child);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return clients;
  }
  private synchronized void getZkRunning() throws Exception {
    LOG.debug("Reading " + parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING);
    List<String> children =
        getChildren(
            parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING, new RunningWatcher());

    if (!children.isEmpty()) {
      for (String child : children) {
        // If stop-wms.sh is executed and WMS_MANAGES_ZK then zookeeper
        // is stopped abruptly.
        // Second scenario is when ZooKeeper fails for some reason
        // regardless of whether WMS
        // manages it. When either happens the WmsServer running znodes
        // still exist in ZooKeeper
        // and we see them at next startup. When they eventually timeout
        // we get node deleted events for a server that no longer
        // exists. So, only recognize
        // WmsServer running znodes that have timestamps after last
        // WmsMaster startup.
        Scanner scn = new Scanner(child);
        scn.useDelimiter(":");
        String hostName = scn.next();
        String instance = scn.next();
        int infoPort = Integer.parseInt(scn.next());
        long serverStartTimestamp = Long.parseLong(scn.next());
        scn.close();

        if (serverStartTimestamp < startupTimestamp) continue;

        if (!runningServers.contains(child)) {
          LOG.debug("Watching running [" + child + "]");
          zkc.exists(
              parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING + "/" + child,
              new RunningWatcher());
          runningServers.add(child);
        }
      }
      metrics.setTotalRunning(runningServers.size());
    } else {
      metrics.setTotalRunning(0);
    }
  }
    /**
     * Removes receiver and sender feedback from RTCP packets.
     *
     * @param inPacket the <tt>RTCPCompoundPacket</tt> to filter.
     * @return the filtered <tt>RawPacket</tt>.
     */
    public RawPacket gateway(RTCPCompoundPacket inPacket) {
      if (inPacket == null || inPacket.packets == null || inPacket.packets.length == 0) {
        logger.info("Ignoring empty RTCP packet.");
        return null;
      }

      ArrayList<RTCPPacket> outPackets = new ArrayList<RTCPPacket>(inPacket.packets.length);

      for (RTCPPacket p : inPacket.packets) {
        switch (p.type) {
          case RTCPPacket.RR:
          case RTCPPacket.SR:
          case RTCPPacket.SDES:
            // We generate our own RR/SR/SDES packets. We only want
            // to forward NACKs/PLIs/etc.
            break;
          case RTCPFBPacket.PSFB:
            RTCPFBPacket psfb = (RTCPFBPacket) p;
            switch (psfb.fmt) {
              case RTCPREMBPacket.FMT:
                // We generate its own REMB packets.
                break;
              default:
                // We let through everything else, like NACK
                // packets.
                outPackets.add(psfb);
                break;
            }
            break;
          default:
            // We let through everything else, like BYE and APP
            // packets.
            outPackets.add(p);
            break;
        }
      }

      if (outPackets.size() == 0) {
        return null;
      }

      // We have feedback messages to send. Pack them in a compound
      // RR and send them. TODO Use RFC5506 Reduced-Size RTCP, if the
      // receiver supports it.
      Collection<RTCPRRPacket> rrPackets = makeRTCPRRPackets(System.currentTimeMillis());

      if (rrPackets != null && rrPackets.size() != 0) {
        outPackets.addAll(0, rrPackets);
      } else {
        logger.warn("We might be sending invalid RTCPs.");
      }

      RTCPPacket[] pkts = outPackets.toArray(new RTCPPacket[outPackets.size()]);
      RTCPCompoundPacket outPacket = new RTCPCompoundPacket(pkts);

      return generator.apply(outPacket);
    }
Example #12
0
  @Test
  public void testOfTypeWithPolymorphism() {
    ArrayList<Integer> l1 = new ArrayList<>();
    l1.add(1);
    LinkedList<Integer> l2 = new LinkedList<>();
    l2.add(2);

    @SuppressWarnings("rawtypes")
    Observable<List> observable = Observable.<Object>just(l1, l2, "123").ofType(List.class);

    Subscriber<Object> observer = TestHelper.mockSubscriber();

    observable.subscribe(observer);

    verify(observer, times(1)).onNext(l1);
    verify(observer, times(1)).onNext(l2);
    verify(observer, never()).onNext("123");
    verify(observer, never()).onError(org.mockito.Matchers.any(Throwable.class));
    verify(observer, times(1)).onComplete();
  }
  private void getServersFile() throws Exception {
    InputStream is = this.getClass().getResourceAsStream("/servers");
    if (is == null) throw new IOException("Cannot find servers file");

    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    configuredServers.clear();
    String line;
    while ((line = br.readLine()) != null) {
      configuredServers.add(line);
    }

    Collections.sort(configuredServers);

    if (configuredServers.size() < 1) throw new IOException("No entries found in servers file");

    int lnum = 1;
    for (int i = 0; i < configuredServers.size(); i++) {
      LOG.debug("servers file line " + lnum + " [" + configuredServers.get(i) + "]");
      lnum++;
    }
  }
Example #14
0
  void turnOnFadeLog() throws IOException {
    Global.log("Connecting to fade log...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.fadeLogPort() + "...");
      try {
        fadeLog = new ClientByteStream(ip, Global.fadeLogPort(), 12);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                String s = null;
                byte[] data = null;
                try {
                  data = fadeLog.read();
                  if (data == null) return;
                  s = fadeLog.readLine();
                } catch (IOException ex) {
                  System.err.println("Error reading from fade log: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (s == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                float x = bb.getFloat();
                float y = bb.getFloat();
                Color color = Global.IntToColor(bb.getInt());

                // if fade color is same as ship color, play power-up sound

                if (color.equals(getPlayerShip().fill)) Sounds.powerUp.play();

                fadeLog(s, x, y, color);
              }
            }));
  }
  private synchronized void restartServer(String znodePath) throws Exception {
    String child =
        znodePath.replace(
            parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING + "/", "");
    Scanner scn = new Scanner(child);
    scn.useDelimiter(":");
    String hostName = scn.next();
    String instance = scn.next();
    int infoPort = Integer.parseInt(scn.next());
    long serverStartTimestamp = Long.parseLong(scn.next());
    scn.close();

    LOG.error("WmsServer [" + hostName + ":" + instance + "] failed.");

    if (runningServers.contains(child)) {
      LOG.debug("Found [" + child + "], deleting from running servers list");
      runningServers.remove(child);
      metrics.setTotalRunning(runningServers.size());
    }

    RestartHandler handler = new RestartHandler(child);
    restartQueue.add(handler);
  }
Example #16
0
  void turnOnBulletReceiver() throws IOException {
    Global.log("Turning on bullet receiver...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + (Global.bulletPort()) + "...");
      try {
        bulletStream = new ClientByteStream(ip, Global.bulletPort(), Bullet.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return true;
              }

              public float FPS() {
                return Global.ReceiveFPS * 20;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = bulletStream.read();
                } catch (IOException ex) {
                  System.err.println("Bullet receiver error: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                Bullet toSpawn = Bullet.fromBytes(data);
                Ship find = cShip.get(toSpawn.getFill());
                if (find == null) {
                  for (Ship s : turrets) {
                    if (s.fill.equals(toSpawn.getFill())) {
                      find = s;
                      break;
                    }
                  }
                }
                if (find == null) return;
                find.getBulletSet().add(toSpawn);
              }
            }));
  }
Example #17
0
    @VisibleForTesting
    List<String> processMessage(String message) {
      // Split leaves a trailing empty line if there's a terminating newline.
      ArrayList<String> split = Lists.newArrayList(message.split("\r?\n", -1));
      Preconditions.checkArgument(split.size() > 0);

      synchronized (this) {
        buffer.append(split.get(0));
        if (split.size() == 1) // no newlines.
        return ImmutableList.of();
        split.set(0, buffer.toString());
        buffer = new StringBuilder().append(split.remove(split.size() - 1));
      }
      return split;
    }
Example #18
0
 private void createConnections() {
   for (ConnectionConfig connectionConfig : getConfig().getConnectionList()) {
     try {
       Connection connection = new ConnectionImpl(connectionConfig);
       connection
           .getOutputTerminal()
           .addEventListener(TerminalConnectionEvent.class, connectionListener);
       connectionList.addItem(connection);
     } catch (Exception e) {
       badConnections.add(connectionConfig);
       log.error(
           "Unable to create connection between terminals "
               + connectionConfig.getInputTerminalId()
               + " and "
               + connectionConfig.getOutputTerminalId(),
           e);
     }
   }
 }
Example #19
0
  void turnOnTurretReceiver() throws IOException {
    Global.log("Turning on turret receiver...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.turretPort() + "...");
      try {
        turretStream = new ClientByteStream(ip, Global.turretPort(), Ship.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                String name = null;
                try {
                  data = turretStream.read();
                  name = turretStream.readLine();
                } catch (IOException ex) {
                  System.err.println("Cannot read info from turret stream");
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                Ship s = new Ship(name, Global.transparent);
                s.setDesign(new Design.Turret(s));
                s.fromBytes(data, false);
                addShip(s);
              }
            }));
  }
Example #20
0
  void turnOnServerTime() throws IOException {
    Global.log("Turning on server time...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.serverTimePort() + "...");
      try {
        serverTime = new ClientByteStream(ip, Global.serverTimePort(), 2);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = serverTime.read();
                } catch (IOException ex) {
                  System.err.println("Error reading from server time: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                short time = bb.getShort();
                Game.activeGame().getHud().setTime(time);
              }
            }));
  }
Example #21
0
  void turnOnChatLog() throws IOException {
    Global.log("Connecting to chat log...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.chatLogPort() + "...");
      try {
        chatLog = new ClientByteStream(ip, Global.chatLogPort(), 1);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                String s = null;
                try {
                  s = chatLog.readLine();
                } catch (IOException ex) {
                  System.err.println("Error reading from chat log: " + ex);
                  Global.onException();
                  stop();
                  return;
                }
                if (s == null) return;
                log(s);
              }
            }));
  }
Example #22
0
 public void closeNetworking() {
   for (FixedTimer timer : timers) timer.stop();
   timers.clear();
   if (Global.connectingSocket != null) {
     try {
       Global.connectingSocket.close();
     } catch (IOException ex) {
     }
   }
   closeClient(mainServer);
   closeClient(bulletStream);
   closeClient(powerStream);
   closeClient(turretStream);
   closeClient(powerRemover);
   closeClient(chatLog);
   closeClient(fadeLog);
   closeClient(serverTime);
   if (playerByteStreams != null) {
     for (int i = 0; i < playerByteStreams.length; ++i) {
       closeClient(playerByteStreams[i]);
     }
   }
 }
Example #23
0
  String[] getPluginDirectories() {

    ArrayList<String> directories = new ArrayList<String>();
    PackageManager pm = this.mAppContext.getPackageManager();
    List<ResolveInfo> plugins =
        pm.queryIntentServices(
            new Intent(PLUGIN_ACTION), PackageManager.GET_SERVICES | PackageManager.GET_META_DATA);

    synchronized (mPackageInfoCache) {

      // clear the list of existing packageInfo objects
      mPackageInfoCache.clear();

      for (ResolveInfo info : plugins) {

        // retrieve the plugin's service information
        ServiceInfo serviceInfo = info.serviceInfo;
        if (serviceInfo == null) {
          Log.w(LOGTAG, "Ignore bad plugin");
          continue;
        }

        Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName);

        // retrieve information from the plugin's manifest
        PackageInfo pkgInfo;
        try {
          pkgInfo =
              pm.getPackageInfo(
                  serviceInfo.packageName,
                  PackageManager.GET_PERMISSIONS | PackageManager.GET_SIGNATURES);
        } catch (Exception e) {
          Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
          continue;
        }
        if (pkgInfo == null) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Could not load package information.");
          continue;
        }

        /*
         * find the location of the plugin's shared library. The default
         * is to assume the app is either a user installed app or an
         * updated system app. In both of these cases the library is
         * stored in the app's data directory.
         */
        String directory = pkgInfo.applicationInfo.dataDir + "/lib";
        final int appFlags = pkgInfo.applicationInfo.flags;
        final int updatedSystemFlags =
            ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
        // preloaded system app with no user updates
        if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) {
          directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName;
        }

        // check if the plugin has the required permissions
        String permissions[] = pkgInfo.requestedPermissions;
        if (permissions == null) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Does not have required permission.");
          continue;
        }
        boolean permissionOk = false;
        for (String permit : permissions) {
          if (PLUGIN_PERMISSION.equals(permit)) {
            permissionOk = true;
            break;
          }
        }
        if (!permissionOk) {
          Log.w(
              LOGTAG,
              "Loading plugin: "
                  + serviceInfo.packageName
                  + ". Does not have required permission (2).");
          continue;
        }

        // check to ensure the plugin is properly signed
        Signature signatures[] = pkgInfo.signatures;
        if (signatures == null) {
          Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed.");
          continue;
        }

        // determine the type of plugin from the manifest
        if (serviceInfo.metaData == null) {
          Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined");
          continue;
        }

        String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE);
        if (!TYPE_NATIVE.equals(pluginType)) {
          Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType);
          continue;
        }

        try {
          Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name);

          // TODO implement any requirements of the plugin class here!
          boolean classFound = true;

          if (!classFound) {
            Log.e(
                LOGTAG,
                "The plugin's class' "
                    + serviceInfo.name
                    + "' does not extend the appropriate class.");
            continue;
          }

        } catch (NameNotFoundException e) {
          Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
          continue;
        } catch (ClassNotFoundException e) {
          Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name);
          continue;
        }

        // if all checks have passed then make the plugin available
        mPackageInfoCache.add(pkgInfo);
        directories.add(directory);
      }
    }

    return directories.toArray(new String[directories.size()]);
  }
  public static void main(String[] args) throws Throwable {
    final int itrs = Integer.getInteger("iterations", 100000);
    // final int itrs = Integer.getInteger("iterations", 12);
    final int size = Integer.getInteger("size", 2048);
    final int subsize = Integer.getInteger("subsize", 128);
    final int maxchar = Integer.getInteger("maxchar", 128);
    final String regex = System.getProperty("filter");
    final Pattern filter = (regex == null) ? null : Pattern.compile(regex);
    final boolean useSecurityManager = Boolean.getBoolean("SecurityManager");
    if (useSecurityManager) System.setSecurityManager(new PermissiveSecurityManger());
    final Random rnd = new Random();

    String[] csns =
        new String[] {
          "Big5",
          "Johab",
          "EUC_CN",
          "EUC_KR",
          "MS932",
          "MS936",
          "MS949",
          "MS950",
          "GBK",
          "Big5_HKSCS",
          "Big5_HKSCS_2001",
          "Big5_Solaris",
          "MS950_HKSCS",
          "MS950_HKSCS_XP",
          "IBM1364",
          "IBM1381",
          "IBM1383",
          "IBM930",
          "IBM933",
          "IBM935",
          "IBM937",
          "IBM939",
          "IBM942",
          "IBM943",
          "IBM948",
          "IBM949",
          "IBM950",
          "IBM970",
        };

    ArrayList<long[]> sum = new ArrayList<>();

    for (final String csn : csns) {
      final Charset cs = Charset.forName(csn);
      List<Integer> cps = new ArrayList<>(0x4000);
      int off = 0;
      int cp = 0;
      int n = 0;
      CharsetEncoder enc = cs.newEncoder();
      while (cp < 0x10000 && n < cps.size()) {
        if (enc.canEncode((char) cp)) {
          cps.add(cp);
          n++;
        }
        cp++;
      }
      Collections.shuffle(cps);
      char[] ca = new char[cps.size()];
      for (int i = 0; i < cps.size(); i++) ca[i] = (char) (int) cps.get(i);

      System.out.printf("%n--------%s---------%n", csn);
      for (int sz = 8; sz <= 2048; sz *= 2) {
        System.out.printf("   [len=%d]%n", sz);

        final char[] chars = Arrays.copyOf(ca, sz);
        final String str = new String(chars);
        final byte[] bs = str.getBytes(cs);

        Job[] jobs = {
          new Job("String decode: csn") {
            public void work() throws Throwable {
              for (int i = 0; i < itrs; i++) new String(bs, csn);
            }
          },
          new Job("String decode: cs") {
            public void work() throws Throwable {
              for (int i = 0; i < itrs; i++) new String(bs, cs);
            }
          },
          new Job("String encode: csn") {
            public void work() throws Throwable {
              for (int i = 0; i < itrs; i++) str.getBytes(csn);
            }
          },
          new Job("String encode: cs") {
            public void work() throws Throwable {
              for (int i = 0; i < itrs; i++) str.getBytes(cs);
            }
          },
        };
        sum.add(time(jobs));
      }
    }
  }
  public void deinit(Appendable out, boolean force) throws Exception {
    Settings settings = new Settings(platform.getConfigFile());

    if (!force) {
      Justif justify = new Justif(80, 40);
      StringBuilder sb = new StringBuilder();
      Formatter f = new Formatter(sb);

      try {
        String list = listFiles(platform.getGlobal());
        if (list != null) {
          f.format("In global default environment:%n");
          f.format(list);
        }

        list = listFiles(platform.getLocal());
        if (list != null) {
          f.format("In local default environment:%n");
          f.format(list);
        }

        if (settings.containsKey(JPM_CACHE_GLOBAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL)));
          if (list != null) {
            f.format("In global configured environment:%n");
            f.format(list);
          }
        }

        if (settings.containsKey(JPM_CACHE_LOCAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL)));
          if (list != null) {
            f.format("In local configured environment:%n");
            f.format(list);
          }
        }

        list = listSupportFiles();
        if (list != null) {
          f.format("jpm support files:%n");
          f.format(list);
        }

        f.format("%n%n");

        f.format(
            "All files listed above will be deleted if deinit is run with the force flag set"
                + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n");
        f.flush();

        justify.wrap(sb);
        out.append(sb.toString());
      } finally {
        f.close();
      }
    } else { // i.e. if(force)
      int count = 0;
      File[] caches = {platform.getGlobal(), platform.getLocal(), null, null};
      if (settings.containsKey(JPM_CACHE_LOCAL)) {
        caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL));
      }
      if (settings.containsKey(JPM_CACHE_GLOBAL)) {
        caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL));
      }
      ArrayList<File> toDelete = new ArrayList<File>();

      for (File cache : caches) {
        if (cache == null || !cache.exists()) {
          continue;
        }
        listFiles(cache, toDelete);
        if (toDelete.size() > count) {
          count = toDelete.size();
          if (!cache.canWrite()) {
            reporter.error(PERMISSION_ERROR + " (" + cache + ")");
            return;
          }
          toDelete.add(cache);
        }
      }
      listSupportFiles(toDelete);

      for (File f : toDelete) {
        if (f.exists() && !f.canWrite()) {
          reporter.error(PERMISSION_ERROR + " (" + f + ")");
        }
      }
      if (reporter.getErrors().size() > 0) {
        return;
      }

      for (File f : toDelete) {
        if (f.exists()) {
          IO.deleteWithException(f);
        }
      }
    }
  }
Example #26
0
  void createShips() {

    Global.log("Creating ships...");
    int n = numPlayers();

    for (int i = 0; i < n; ++i) {

      Global.log("Creating ship for Player " + (i + 1) + " [" + playerNames[i] + "]...");

      final int I = i;

      if (i == playerID) {
        final PlayerShip ship = new PlayerShip(name, nextColor(), this, new Controls());
        ship.getControls().enabled = false;
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.SendFPS;
                  }

                  public void run() {
                    try {
                      sendMessage(ship.getControlBytes());
                    } catch (IOException ex) {
                      System.err.println(
                          "An exception occured via the ship of Player "
                              + (I + 1)
                              + " ["
                              + playerNames[I]
                              + "]: "
                              + ex.toString());
                      Global.onException();
                      stop();
                    }
                  }
                }));
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.ReceiveFPS;
                  }

                  public void run() {
                    byte[] data = null;
                    try {
                      data = playerByteStreams[I].read();
                    } catch (IOException ex) {
                      System.err.println("Error reading ship from server: " + ex);
                      Global.onException();
                      stop();
                      return;
                    }
                    if (data == null) return;
                    ship.fromBytes(data);
                  }
                }));
        addShip(ship);
      } else {
        final Ship ship = new Ship(playerNames[i], nextColor());
        timers.add(
            new FixedTimer(
                new FixedTask() {
                  public boolean fixedRate() {
                    return true;
                  }

                  public float FPS() {
                    return Global.ReceiveFPS;
                  }

                  public void run() {
                    byte[] data = null;
                    try {
                      data = playerByteStreams[I].read();
                    } catch (IOException ex) {
                      System.err.println("Error reading ship from server: " + ex);
                      Global.onException();
                      stop();
                      return;
                    }
                    if (data == null) return;
                    ship.fromBytes(data);
                  }
                }));
        addShip(ship);
      }

      Global.log("Done!");
    }

    Global.log("Done creating ships!");
  }
Example #27
0
  void turnOnPowerReceiver() throws IOException {
    Global.log("Turning on power receiver...");
    while (true) {

      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + (Global.powerPort()) + "...");
      try {
        powerStream = new ClientByteStream(ip, Global.powerPort(), Power.bufferSize());
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = powerStream.read();
                } catch (IOException ex) {
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                addPower(Power.fromBytes(data));
              }
            }));
    Global.log("Turning on power remover...");
    while (true) {
      if (isDisposed()) throw new IOException("Client game disposed");
      Global.log("Connecting to port " + Global.powerRemoverPort() + "...");
      try {
        powerRemover = new ClientByteStream(ip, Global.powerRemoverPort(), 2);
        break;
      } catch (IOException ex) {
      }
    }
    Global.log("Connected!");
    timers.add(
        new FixedTimer(
            new FixedTask() {
              public boolean fixedRate() {
                return false;
              }

              public float FPS() {
                return Global.ReceiveFPS;
              }

              public void run() {
                byte[] data = null;
                try {
                  data = powerRemover.read();
                } catch (IOException ex) {
                  System.err.println("Cannot read info from power remover");
                  Global.onException();
                  stop();
                  return;
                }
                if (data == null) return;
                ByteBuffer bb = ByteBuffer.wrap(data);
                short id = bb.getShort();
                for (Power power : powers) {
                  if (power.ID == id) {
                    removePower(power);
                    break;
                  }
                }
              }
            }));
  }
Example #28
0
  private void initComponents() {
    // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    dialogPane = new JPanel();
    contentPanel = new JPanel();
    panel1 = new JPanel();
    label2 = new JLabel();
    ttfSizeW = new JTextField();
    label4 = new JLabel();
    ttfLongi = new JTextField();
    btnGetMap = new JButton();
    label3 = new JLabel();
    ttfSizeH = new JTextField();
    label5 = new JLabel();
    ttfLati = new JTextField();
    btnQuit = new JButton();
    label1 = new JLabel();
    ttfLicense = new JTextField();
    label6 = new JLabel();
    ttfZoom = new JTextField();
    // ComboBox for Saved Locations
    ttfSave = new JComboBox();
    scrollPane1 = new JScrollPane();
    ttaStatus = new JTextArea();
    panel2 = new JPanel();
    panel3 = new JPanel();
    checkboxRecvStatus = new JCheckBox();
    checkboxSendStatus = new JCheckBox();
    ttfProgressMsg = new JTextField();
    progressBar = new JProgressBar();
    lblProgressStatus = new JLabel();

    // ======== this ========
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setTitle("Google Static Maps");
    setIconImage(null);
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());

    // ======== dialogPane ========
    {
      dialogPane.setBorder(new EmptyBorder(12, 12, 12, 12));
      dialogPane.setOpaque(false);
      dialogPane.setLayout(new BorderLayout());

      // ======== contentPanel ========
      {
        contentPanel.setOpaque(false);
        contentPanel.setLayout(
            new TableLayout(
                new double[][] {
                  {TableLayout.FILL},
                  {TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}
                }));
        ((TableLayout) contentPanel.getLayout()).setHGap(5);
        ((TableLayout) contentPanel.getLayout()).setVGap(5);

        // ======== panel1 ========
        {
          panel1.setOpaque(false);
          panel1.setBorder(
              new CompoundBorder(
                  new TitledBorder("Configure the inputs to Google Static Maps"),
                  Borders.DLU2_BORDER));
          panel1.setLayout(
              new TableLayout(
                  new double[][] {
                    {0.17, 0.17, 0.17, 0.17, 0.05, TableLayout.FILL},
                    {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED}
                  }));
          ((TableLayout) panel1.getLayout()).setHGap(5);
          ((TableLayout) panel1.getLayout()).setVGap(5);

          // ---- label2 ----
          label2.setText("Size Width");
          label2.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label2,
              new TableLayoutConstraints(
                  0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSizeW ----
          ttfSizeW.setText("512");
          panel1.add(
              ttfSizeW,
              new TableLayoutConstraints(
                  1, 0, 1, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label4 ----
          label4.setText("Latitude");
          label4.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label4,
              new TableLayoutConstraints(
                  2, 0, 2, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLongi ----
          ttfLongi.setText("38.931099");
          panel1.add(
              ttfLongi,
              new TableLayoutConstraints(
                  3, 0, 3, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- btnGetMap ----
          btnGetMap.setText("Get Map");
          btnGetMap.setHorizontalAlignment(SwingConstants.LEFT);
          btnGetMap.setMnemonic('G');
          btnGetMap.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  startTaskAction();
                  if (Integer.parseInt(ttfZoom.getText()) < 14) { // coding for zoom values under 14
                    for (int i = 0; i < 14; i++) {
                      if (Integer.parseInt(ttfZoom.getText()) == i) {
                        countThis = 14 - i; // gets difference
                        do {
                          counter = counter * 2; // found out code zooms in powers of 2.
                          pixelX =
                              0.000084525
                                  * counter; // Values per Latitude, trial and error method used to
                                             // find these numbers.
                          pixelY = 0.00006725 * counter; // Values per Longitude
                          counter1++;
                        } while (counter1 != countThis); // loops the amount of differences
                      }
                      counter = 1; // Resetters
                      counter1 = 0;
                    }
                  } else if (Integer.parseInt(ttfZoom.getText())
                      > 14) { // coding for zoom values over 14
                    for (int i = 14; i < 19; i++) {
                      if (Integer.parseInt(ttfZoom.getText()) == i) {
                        countThis = i - 14; // gets difference
                        do {
                          counter = counter * 2;
                          pixelX = 0.000084525 / counter; // Values per Latitude
                          pixelY = 0.00006725 / counter; // Values per Longitude	            	
                          counter1++;
                        } while (counter1 != countThis); // loops amount of differences
                      }
                      counter = 1; // Resetters
                      counter1 = 0;
                    }
                  } else { // coding for zoom default value of 14.
                    pixelX = 0.000084525;
                    pixelY = 0.00006725;
                  }

                  BigDecimal sendPixelX = new BigDecimal(pixelX);
                  BigDecimal sendPixelY = new BigDecimal(pixelY);

                  pixelX =
                      (sendPixelX.setScale(6, BigDecimal.ROUND_HALF_UP))
                          .doubleValue(); // allows for bigger decimal zoom variables
                  pixelY =
                      (sendPixelY.setScale(6, BigDecimal.ROUND_HALF_UP))
                          .doubleValue(); // Won't reach zoom 1-5 without these!
                }
              });
          panel1.add(
              btnGetMap,
              new TableLayoutConstraints(
                  5, 0, 5, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label3 ----
          label3.setText("Size Height");
          label3.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label3,
              new TableLayoutConstraints(
                  0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSizeH ----
          ttfSizeH.setText("512");
          panel1.add(
              ttfSizeH,
              new TableLayoutConstraints(
                  1, 1, 1, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label5 ----
          label5.setText("Longitude");
          label5.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label5,
              new TableLayoutConstraints(
                  2, 1, 2, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLati ----
          ttfLati.setText("-77.3489");
          panel1.add(
              ttfLati,
              new TableLayoutConstraints(
                  3, 1, 3, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- btnQuit ----
          btnQuit.setText("Quit");
          btnQuit.setMnemonic('Q');
          btnQuit.setHorizontalAlignment(SwingConstants.LEFT);
          btnQuit.setHorizontalTextPosition(SwingConstants.RIGHT);
          btnQuit.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  quitProgram();
                }
              });
          panel1.add(
              btnQuit,
              new TableLayoutConstraints(
                  5, 1, 5, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label1 ----
          label1.setText("License Key");
          label1.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label1,
              new TableLayoutConstraints(
                  0, 2, 0, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfLicense ----
          ttfLicense.setToolTipText("Enter your own URI for a file to download in the background");
          panel1.add(
              ttfLicense,
              new TableLayoutConstraints(
                  1, 2, 1, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- label6 ----
          label6.setText("Zoom");
          label6.setHorizontalAlignment(SwingConstants.RIGHT);
          panel1.add(
              label6,
              new TableLayoutConstraints(
                  2, 2, 2, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfZoom ----
          ttfZoom.setText("14");
          panel1.add(
              ttfZoom,
              new TableLayoutConstraints(
                  3, 2, 3, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfSave ----
          ttfSave.removeAllItems();
          // JComboBox ttfSave = new JComboBox();
          getSavedLocations(); // grabs a new list
          for (int i = 0; i < loc.size(); i++) // populates this list using a arrayList
          ttfSave.addItem(loc.get(i));

          ttfSave.setSelectedIndex(0);
          panel1.add(
              ttfSave,
              new TableLayoutConstraints(
                  5, 2, 5, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
          // Action Listener to update the coordinates on selected Location
          ttfSave.addActionListener(
              new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  if (mapIsUp == 0) {
                    Object contents = ttfSave.getSelectedItem(); // grabs users selection
                    System.out.println(contents);
                    if (contents != null) {
                      stringCoords = contents.toString();
                      setCoords = stringCoords.split("\\s+");
                      ttfLongi.setText(
                          setCoords[
                              1]); // sets the texts in the longitude and latitude fields to
                                   // coordinates selected
                      ttfLati.setText(setCoords[0]);
                    }
                  }
                }
              });
        }
        contentPanel.add(
            panel1,
            new TableLayoutConstraints(
                0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

        // ======== scrollPane1 ========
        {
          scrollPane1.setBorder(
              new TitledBorder("System.out - displays all status and progress messages, etc."));
          scrollPane1.setOpaque(false);

          // ---- ttaStatus ----
          ttaStatus.setBorder(Borders.createEmptyBorder("1dlu, 1dlu, 1dlu, 1dlu"));
          ttaStatus.setToolTipText(
              "<html>Task progress updates (messages) are displayed here,<br>along with any other output generated by the Task.<html>");
          scrollPane1.setViewportView(ttaStatus);
        }
        contentPanel.add(
            scrollPane1,
            new TableLayoutConstraints(
                0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

        // ======== panel2 ========
        {
          panel2.setOpaque(false);
          panel2.setBorder(
              new CompoundBorder(
                  new TitledBorder("Status - control progress reporting"), Borders.DLU2_BORDER));
          panel2.setLayout(
              new TableLayout(
                  new double[][] {
                    {0.45, TableLayout.FILL, 0.45},
                    {TableLayout.PREFERRED, TableLayout.PREFERRED}
                  }));
          ((TableLayout) panel2.getLayout()).setHGap(5);
          ((TableLayout) panel2.getLayout()).setVGap(5);

          // ======== panel3 ========
          {
            panel3.setOpaque(false);
            panel3.setLayout(new GridLayout(1, 2));

            // ---- checkboxRecvStatus ----
            checkboxRecvStatus.setText("Enable \"Recieve\"");
            checkboxRecvStatus.setOpaque(false);
            checkboxRecvStatus.setToolTipText("Task will fire \"send\" status updates");
            checkboxRecvStatus.setSelected(true);
            panel3.add(checkboxRecvStatus);

            // ---- checkboxSendStatus ----
            checkboxSendStatus.setText("Enable \"Send\"");
            checkboxSendStatus.setOpaque(false);
            checkboxSendStatus.setToolTipText("Task will fire \"recieve\" status updates");
            panel3.add(checkboxSendStatus);
          }
          panel2.add(
              panel3,
              new TableLayoutConstraints(
                  0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- ttfProgressMsg ----
          ttfProgressMsg.setText("Loading map from Google Static Maps");
          ttfProgressMsg.setToolTipText("Set the task progress message here");
          panel2.add(
              ttfProgressMsg,
              new TableLayoutConstraints(
                  2, 0, 2, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- progressBar ----
          progressBar.setStringPainted(true);
          progressBar.setString("progress %");
          progressBar.setToolTipText("% progress is displayed here");
          panel2.add(
              progressBar,
              new TableLayoutConstraints(
                  0, 1, 0, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));

          // ---- lblProgressStatus ----
          lblProgressStatus.setText("task status listener");
          lblProgressStatus.setHorizontalTextPosition(SwingConstants.LEFT);
          lblProgressStatus.setHorizontalAlignment(SwingConstants.LEFT);
          lblProgressStatus.setToolTipText(
              "Task status messages are displayed here when the task runs");
          panel2.add(
              lblProgressStatus,
              new TableLayoutConstraints(
                  2, 1, 2, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
        }
        contentPanel.add(
            panel2,
            new TableLayoutConstraints(
                0, 2, 0, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
      }
      dialogPane.add(contentPanel, BorderLayout.CENTER);
    }
    contentPane.add(dialogPane, BorderLayout.CENTER);
    setSize(675, 485);
    setLocationRelativeTo(null);
    // JFormDesigner - End of component initialization  //GEN-END:initComponents
  }
Example #29
0
  /** Deploys a process. */
  public Collection<QName> deploy(
      final File deploymentUnitDirectory,
      boolean activate,
      String duName,
      boolean autoincrementVersion) {
    __log.info(__msgs.msgDeployStarting(deploymentUnitDirectory));

    final Date deployDate = new Date();

    // Create the DU and compile/scan it before acquiring lock.
    final DeploymentUnitDir du = new DeploymentUnitDir(deploymentUnitDirectory);
    if (duName != null) {
      // Override the package name if given from the parameter
      du.setName(duName);
    }

    long version;
    if (autoincrementVersion || du.getStaticVersion() == -1) {
      // Process and DU use a monotonically increased single version number by default.
      try {
        version = getCurrentVersion();
      } finally {
        // we need to reset the current version thread local value.
        _currentVersion.set(null);
      }
    } else {
      version = du.getStaticVersion();
    }
    du.setVersion(version);

    try {
      du.compile();
    } catch (CompilationException ce) {
      String errmsg = __msgs.msgDeployFailCompileErrors(ce);
      __log.error(errmsg, ce);
      throw new ContextException(errmsg, ce);
    }

    du.scan();
    final DeployDocument dd = du.getDeploymentDescriptor();
    final ArrayList<ProcessConfImpl> processes = new ArrayList<ProcessConfImpl>();
    Collection<QName> deployed;

    _rw.writeLock().lock();

    try {
      if (_deploymentUnits.containsKey(du.getName())) {
        String errmsg = __msgs.msgDeployFailDuplicateDU(du.getName());
        __log.error(errmsg);
        throw new ContextException(errmsg);
      }

      retirePreviousPackageVersions(du);

      for (TDeployment.Process processDD : dd.getDeploy().getProcessArray()) {
        QName pid = toPid(processDD.getName(), version);

        if (_processes.containsKey(pid)) {
          String errmsg = __msgs.msgDeployFailDuplicatePID(processDD.getName(), du.getName());
          __log.error(errmsg);
          throw new ContextException(errmsg);
        }

        QName type = processDD.getType() != null ? processDD.getType() : processDD.getName();

        CBPInfo cbpInfo = du.getCBPInfo(type);
        if (cbpInfo == null) {
          String errmsg = __msgs.msgDeployFailedProcessNotFound(processDD.getName(), du.getName());
          __log.error(errmsg);
          throw new ContextException(errmsg);
        }

        ProcessConfImpl pconf =
            new ProcessConfImpl(
                pid,
                processDD.getName(),
                version,
                du,
                processDD,
                deployDate,
                calcInitialProperties(du.getProperties(), processDD),
                calcInitialState(processDD),
                eprContext,
                _configDir,
                generateProcessEventsAll);
        processes.add(pconf);
      }

      _deploymentUnits.put(du.getName(), du);

      for (ProcessConfImpl process : processes) {
        __log.info(__msgs.msgProcessDeployed(du.getDeployDir(), process.getProcessId()));
        _processes.put(process.getProcessId(), process);
      }

    } finally {
      _rw.writeLock().unlock();
    }

    // Do the deployment in the DB. We need this so that we remember deployments across system
    // shutdowns.
    // We don't fail if there is a DB error, simply print some errors.
    deployed =
        exec(
            new Callable<Collection<QName>>() {
              public Collection<QName> call(ConfStoreConnection conn) {
                // Check that this deployment unit is not deployed.
                DeploymentUnitDAO dudao = conn.getDeploymentUnit(du.getName());
                if (dudao != null) {
                  String errmsg = "Database out of synch for DU " + du.getName();
                  __log.warn(errmsg);
                  dudao.delete();
                }

                dudao = conn.createDeploymentUnit(du.getName());
                try {
                  dudao.setDeploymentUnitDir(deploymentUnitDirectory.getCanonicalPath());
                } catch (IOException e1) {
                  String errmsg =
                      "Error getting canonical path for "
                          + du.getName()
                          + "; deployment unit will not be available after restart!";
                  __log.error(errmsg);
                }

                ArrayList<QName> deployed = new ArrayList<QName>();
                // Going trough each process declared in the dd
                for (ProcessConfImpl pc : processes) {
                  try {
                    ProcessConfDAO newDao =
                        dudao.createProcess(pc.getProcessId(), pc.getType(), pc.getVersion());
                    newDao.setState(pc.getState());
                    for (Map.Entry<QName, Node> prop : pc.getProcessProperties().entrySet()) {
                      newDao.setProperty(prop.getKey(), DOMUtils.domToString(prop.getValue()));
                    }
                    deployed.add(pc.getProcessId());
                  } catch (Throwable e) {
                    String errmsg =
                        "Error persisting deployment record for "
                            + pc.getProcessId()
                            + "; process will not be available after restart!";
                    __log.error(errmsg, e);
                  }
                }
                return deployed;
              }
            });

    _rw.readLock().lock();
    boolean readLockHeld = true;
    try {
      for (ProcessConfImpl process : processes) {
        fireEvent(
            new ProcessStoreEvent(
                ProcessStoreEvent.Type.DEPLOYED,
                process.getProcessId(),
                process.getDeploymentUnit().getName()));
        fireStateChange(
            process.getProcessId(), process.getState(), process.getDeploymentUnit().getName());
      }
    } catch (Exception e) {
      // need to unlock as undeploy operation will need a writeLock
      _rw.readLock().unlock();
      readLockHeld = false;

      // A problem at that point means that engine deployment failed, we don't want the store to
      // keep the du
      __log.warn("Deployment failed within the engine, store undeploying process.", e);
      undeploy(deploymentUnitDirectory);
      if (e instanceof ContextException) throw (ContextException) e;
      else throw new ContextException("Deployment failed within the engine. " + e.getMessage(), e);
    } finally {
      if (readLockHeld) _rw.readLock().unlock();
    }

    return deployed;
  }