Example #1
0
  /**
   * Creates new node ids and recreates updatable index structures.
   *
   * @param data data
   * @throws IOException I/O Exception during index rebuild
   */
  public static void ids(final Data data) throws IOException {
    final MetaData md = data.meta;
    final int size = md.size;
    for (int pre = 0; pre < size; ++pre) data.id(pre, pre);
    md.lastid = size - 1;
    md.dirty = true;

    if (data.meta.updindex) {
      data.idmap = new IdPreMap(md.lastid);
      if (data.meta.textindex) optimize(IndexType.TEXT, data, true, true, true, null);
      if (data.meta.attrindex) optimize(IndexType.ATTRIBUTE, data, true, true, true, null);
    }
  }
Example #2
0
  public void createExcel(String file) {

    String filename = createPath(file);
    System.out.println(filename);

    /*
       try {
       WorkbookSettings ws = new WorkbookSettings();
       ws.setLocale(new Locale("sv", "SE"));
       WritableWorkbook workbook = Workbook.createWorkbook(new File(filename), ws);
       WritableSheet s = workbook.createSheet("Sheet1", 0);
    //writeDataSheet(s);
    workbook.write();
    workbook.close();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (WriteException e) {
    e.printStackTrace();
    }**/

    try {

      File newFile = new File(filename);
      Writer out =
          new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF8"));
      //	BufferedWrite output = new BufferedWriter(new OutputStreamReader(new
      // FileInputS§tream(filename), "iso-8859-1"));
      // FileWriter fw = new FileWriter(newFile.getAbsoluteFile());
      // BufferedWriter bw = new BufferedWriter(fw);
      // bw.write("Artikel;Antal/st;Pris/st;Total\n");
      out.append("Artikel;Antal/st;Pris/st;Total\n");
      for (Data d : dataList) {
        out.append(d.toString());
        out.append("\n");
        // bw.write(d.toString());
        // bw.write("\n");
      }
      // bw.close();
      out.flush();
      out.close();
    } catch (UnsupportedEncodingException unsuppEn) {
      unsuppEn.printStackTrace();
    } catch (IOException ioE) {
      ioE.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #3
0
 public void out(Object key, Object value) {
   List listeners;
   synchronized (this) {
     Data data = (Data) map.get(key);
     if (data == null) map.put(key, (data = new Data(key)));
     data.add(value);
     listeners = data.getListeners();
     this.notifyAll();
   }
   if (listeners != null) {
     Iterator iter = listeners.iterator();
     while (iter.hasNext()) {
       ((SpaceListener) iter.next()).notify(key, value);
     }
   }
 }
Example #4
0
 public void setType(Class type) {
   if (type == null || type == Object.class) this.type = null;
   else if (isEmpty()) this.type = type;
   else {
     type = Data.commonType(type, getCommonType());
     if (type != null) this.type = type;
   }
 }
Example #5
0
  /**
   * Lists resources of the specified database.
   *
   * @return success flag
   * @throws IOException I/O exception
   */
  private boolean listDB() throws IOException {
    final String db = args[0];
    final String path = args[1] != null ? args[1] : "";
    if (!Databases.validName(db)) return error(NAME_INVALID_X, db);

    final Table table = new Table();
    table.description = RESOURCES;
    table.header.add(INPUT_PATH);
    table.header.add(TYPE);
    table.header.add(MimeTypes.CONTENT_TYPE);
    table.header.add(SIZE);

    try {
      // add xml documents
      final Data data = Open.open(db, context);
      final Resources res = data.resources;
      final IntList il = res.docs(path);
      final int ds = il.size();
      for (int i = 0; i < ds; i++) {
        final int pre = il.get(i);
        final TokenList tl = new TokenList(3);
        final byte[] file = data.text(pre, true);
        tl.add(file);
        tl.add(DataText.M_XML);
        tl.add(MimeTypes.APP_XML);
        tl.add(data.size(pre, Data.DOC));
        table.contents.add(tl);
      }
      // add binary resources
      for (final byte[] file : res.binaries(path)) {
        final String f = string(file);
        final TokenList tl = new TokenList(3);
        tl.add(file);
        tl.add(DataText.M_RAW);
        tl.add(MimeTypes.get(f));
        tl.add(data.meta.binary(f).length());
        table.contents.add(tl);
      }
      Close.close(data, context);
    } catch (final IOException ex) {
      return error(Util.message(ex));
    }
    out.println(table.sort().finish());
    return true;
  }
  private Data dereference(XMLCryptoContext context) throws XMLSignatureException {
    Data data = null;

    // use user-specified URIDereferencer if specified; otherwise use deflt
    URIDereferencer deref = context.getURIDereferencer();
    if (deref == null) {
      deref = DOMURIDereferencer.INSTANCE;
    }
    try {
      data = deref.dereference(this, context);
      if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "URIDereferencer class name: " + deref.getClass().getName());
        log.log(Level.FINE, "Data class name: " + data.getClass().getName());
      }
    } catch (URIReferenceException ure) {
      throw new XMLSignatureException(ure);
    }

    return data;
  }
Example #7
0
 /**
  * Finds the closest namespace node for the specified pre value.
  *
  * @param pre pre value
  * @param data data reference
  * @return node
  */
 NSNode find(final int pre, final Data data) {
   final int s = find(pre);
   // no match found: return current node
   if (s == -1) return this;
   final NSNode ch = children[s];
   final int cp = ch.pr;
   // return exact hit
   if (cp == pre) return ch;
   // found node is preceding sibling
   if (cp + data.size(cp, Data.ELEM) <= pre) return this;
   // continue recursive search
   return children[s].find(pre, data);
 }
Example #8
0
 public Class getCommonType() {
   Class t = null;
   Iterator i = iterator();
   while (i.hasNext()) {
     Object e = i.next();
     if (e == null) continue;
     else if (t == null) t = e.getClass();
     else {
       t = Data.commonType(t, e.getClass());
       if (t == null || t == Object.class) return null;
     }
   }
   return t;
 }
Example #9
0
  @Override
  protected boolean run() {
    final boolean create = context.user.has(Perm.CREATE);
    String path = MetaData.normPath(args[0]);
    if (path == null || path.endsWith(".")) return error(NAME_INVALID_X, args[0]);

    if (in == null) {
      final IO io = IO.get(args[1]);
      if (!io.exists() || io.isDir()) return error(RES_NOT_FOUND_X, create ? io : args[1]);
      in = io.inputSource();
      // set/add name of document
      if ((path.isEmpty() || path.endsWith("/")) && !(io instanceof IOContent)) path += io.name();
    }

    // ensure that the final name is not empty
    if (path.isEmpty()) return error(NAME_INVALID_X, path);

    // ensure that the name is not empty and contains no trailing dots
    final Data data = context.data();
    if (data.inMemory()) return error(NO_MAINMEM);

    final IOFile file = data.meta.binary(path);
    if (path.isEmpty() || path.endsWith(".") || file == null || file.isDir())
      return error(NAME_INVALID_X, create ? path : args[0]);

    // start update
    if (!data.startUpdate()) return error(DB_PINNED_X, data.meta.name);

    try {
      store(in, file);
      return info(QUERY_EXECUTED_X_X, "", perf);
    } catch (final IOException ex) {
      return error(FILE_NOT_STORED_X, Util.message(ex));
    } finally {
      data.finishUpdate();
    }
  }
Example #10
0
 /** Inserts an attribute with namespace. */
 @Test
 public void insertAttributeWithNs() {
   create(1);
   query("insert node attribute { QName('ns', 'pref:local') } { } into /*");
   final Data data = context.data();
   assertEquals(false, data.nsFlag(0));
   assertEquals(true, data.nsFlag(1));
   assertEquals(false, data.nsFlag(2));
   assertEquals(0, data.uriId(1, data.kind(1)));
   assertEquals(1, data.uriId(2, data.kind(2)));
   assertEquals("ns", string(data.nspaces.uri(1)));
 }
Example #11
0
  /**
   * Optimizes the structures of a database.
   *
   * @param data data
   * @param enforceText enforce creation or deletion of text index
   * @param enforceAttr enforce creation or deletion of attribute index
   * @param enforceToken enforce creation or deletion of token index
   * @param enforceFt enforce creation or deletion of full-text index
   * @param cmd calling command instance (may be {@code null})
   * @throws IOException I/O Exception during index rebuild
   */
  public static void optimize(
      final Data data,
      final boolean enforceText,
      final boolean enforceAttr,
      final boolean enforceToken,
      final boolean enforceFt,
      final Optimize cmd)
      throws IOException {

    // initialize structural indexes
    final MetaData md = data.meta;
    if (!md.uptodate) {
      data.paths.init();
      data.elemNames.init();
      data.attrNames.init();
      md.dirty = true;

      final IntList pars = new IntList(), elms = new IntList();
      int n = 0;

      for (int pre = 0; pre < md.size; ++pre) {
        final byte kind = (byte) data.kind(pre);
        final int par = data.parent(pre, kind);
        while (!pars.isEmpty() && pars.peek() > par) {
          pars.pop();
          elms.pop();
        }

        final int level = pars.size();
        if (kind == Data.DOC) {
          data.paths.put(0, Data.DOC, level);
          pars.push(pre);
          elms.push(0);
          ++n;
        } else if (kind == Data.ELEM) {
          final int id = data.nameId(pre);
          data.elemNames.index(data.elemNames.key(id), null, true);
          data.paths.put(id, Data.ELEM, level);
          pars.push(pre);
          elms.push(id);
        } else if (kind == Data.ATTR) {
          final int id = data.nameId(pre);
          final byte[] val = data.text(pre, false);
          data.attrNames.index(data.attrNames.key(id), val, true);
          data.paths.put(id, Data.ATTR, level, val, md);
        } else {
          final byte[] val = data.text(pre, true);
          if (kind == Data.TEXT && level > 1) data.elemNames.index(elms.peek(), val);
          data.paths.put(0, kind, level, val, md);
        }
        if (cmd != null) cmd.pre = pre;
      }
      md.ndocs = n;
      md.uptodate = true;
    }

    // rebuild value indexes
    optimize(IndexType.TEXT, data, md.createtext, md.textindex, enforceText, cmd);
    optimize(IndexType.ATTRIBUTE, data, md.createattr, md.attrindex, enforceAttr, cmd);
    optimize(IndexType.TOKEN, data, md.createtoken, md.tokenindex, enforceToken, cmd);
    optimize(IndexType.FULLTEXT, data, md.createft, md.ftindex, enforceFt, cmd);
  }
Example #12
0
 public synchronized Object inp(Object key) {
   Data data = (Data) map.get(key);
   if (data == null) map.put(key, (data = new Data(key)));
   return data.remove();
 }
Example #13
0
 public synchronized int size(Object key) {
   Data data = (Data) map.get(key);
   if (data == null) map.put(key, (data = new Data(key)));
   return data.size();
 }
Example #14
0
 public synchronized void removeListener(Object key, SpaceListener listener) {
   Data data = (Data) map.get(key);
   if (data != null) data.removeListener(listener);
 }
Example #15
0
  /**
   * Process an HTML get or post.
   *
   * @exception ServletException From inherited class.
   * @exception IOException From inherited class.
   */
  public void scanOutXML(
      PrintWriter out,
      String strDirectory,
      String strFilename,
      String[] strPlus,
      String[] strMinus,
      boolean bExcludeParams,
      boolean bAnalyzeParams)
      throws IOException {
    File dir = new File(strDirectory + '/' + strFilename);
    if (dir.isDirectory()) return;

    try {
      FileReader is = new FileReader(strDirectory + '/' + strFilename);
      BufferedReader r = new BufferedReader(is);
      String string = null;
      Hashtable ht = new Hashtable();
      Set setstrExtensions = new HashSet();
      int iCount = 0;
      int iBytes = 0;
      while ((string = r.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(string, " \"", false);
        Data data = new Data();
        int iTokenCount = 0;
        while (st.hasMoreTokens()) {
          iTokenCount++;
          string = st.nextToken();
          if (iTokenCount == IP) data.m_IP = string;
          if (iTokenCount == URL) {
            if (bExcludeParams)
              if (string.indexOf('?') != -1) string = string.substring(0, string.indexOf('?'));
            if (bAnalyzeParams)
              if (string.indexOf('?') != -1) string = string.substring(string.indexOf('?') + 1);
            data.m_URL = string;
          }
          if (iTokenCount == PROTOCOL)
            if (!string.startsWith("HTTP")) {
              data.m_URL += " " + string;
              iTokenCount--;
            }
          if (iTokenCount == BYTES) data.m_iBytes = Integer.parseInt(string);
        }
        if (!this.filterURL(data.m_URL, strPlus, strMinus, setstrExtensions)) continue;
        iCount++;
        iBytes += data.m_iBytes;
        if (ht.get(data.m_URL) == null) ht.put(data.m_URL, data);
        else {
          int iThisBytes = data.m_iBytes;
          data = (Data) ht.get(data.m_URL);
          data.m_iCount++;
          data.m_iBytes += iThisBytes;
        }
      }
      Comparator comparator = new Test();
      TreeMap tm = new TreeMap(comparator);
      Iterator iterator = ht.values().iterator();
      while (iterator.hasNext()) {
        Data data = (Data) iterator.next();
        tm.put(new Integer(data.m_iCount), data);
      }
      out.println("<file>");
      this.printXML(out, "directory", strDirectory);
      this.printXML(out, "name", strFilename);
      iterator = tm.values().iterator();
      while (iterator.hasNext()) {
        out.println("<data>");
        Data data = (Data) iterator.next();
        this.printXML(out, "url", data.m_URL);
        this.printXML(out, "count", Integer.toString(data.m_iCount));
        out.println("</data>");
      }
      this.printXML(out, "hits", Integer.toString(iCount));
      this.printXML(out, "bytes", Integer.toString(iBytes));
      this.printXML(out, "unique", Integer.toString(tm.size()));

      iterator = setstrExtensions.iterator();
      out.println("<extensions>");
      while (iterator.hasNext()) {
        this.printXML(out, "extension", (String) iterator.next());
      }
      out.println("</extensions>");

      out.println("</file>");
    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
  public static void main(String[] args) throws IOException {

    int n;
    String aux[] = new String[32];
    int linie, coloana;
    Data.setACC(10);
    Data.setBRK(10);
    Data.setMaxSPD(100);
    Data.setgetSteeringCar(0.5);
    try {
      // create socket
      socket = new Socket("127.0.0.1", 6666);
      // we attempt to bypass nagle's algorithm
      socket.setTcpNoDelay(true);

      // initialize our communication class
      comm = new NetworkCommunication(socket);
      comm.initStreams();

      // send initial packet, aka the team's name
      comm.writeInt(H_TEAM_NAME);
      comm.writeInt(1);
      comm.writeString(args[0]);
      // comm.writeString("void");
    } catch (UnknownHostException e) {
      System.out.println("could not connect to server");
      System.exit(1);
    } catch (IOException e) {
      System.out.println("No I/O");
      System.exit(1);
    }
    System.out.println("Sent team name....entering main loop");

    while (true) {
      try {
        int header = comm.readInt();
        switch (header) {
          case H_MAP_DIM: // 2
            {
              Data.setMapWidth(comm.readInt());
              Data.setMapHeigh(comm.readInt());
              Data.Map = new int[Data.getMapHeigh()][Data.getMapWidth()];

              int nr_data_recieve = Data.getMapHeigh() * Data.getMapWidth() / 32 + 1;
              for (int i = 0; i < nr_data_recieve; i++) {
                n = comm.readInt();
                for (int j = 0; j < 32; j++) {
                  if ((n & (1 << j)) == 0) aux[31 - j] = "0";
                  else aux[31 - j] = "1";
                }
                for (int k = 0; k < 32; k++) {
                  linie = (32 * i + k) / Data.getMapWidth();
                  coloana = (32 * i + k) - (linie * Data.getMapWidth());
                  if (Data.getMapHeigh() > linie && Data.getMapWidth() > coloana)
                    Data.Map[linie][coloana] = Integer.parseInt(aux[k]);
                }
              }

              System.out.println("Received map dimentions packet");
            }
            ;
            break;

          case H_INITIAL_INFO: // 3
            {
              Data.setStartPointX(comm.readInt());
              Data.setStartPointY(comm.readInt());
              Data.setWidth_meters(comm.readInt());
              Data.setHeight_meters(comm.readInt());
              Data.setDirection(comm.readInt());
              Data.setNumberOfLaps(comm.readInt());
              Data.setMaximumLapTime(comm.readInt());
              Data.setCarAngle(comm.readDouble());

              // trimite-m la server car configuration
              comm.writeInt(H_CAR_CONFIG);
              comm.writeInt(Data.getACC());
              comm.writeInt(Data.getBRK());
              comm.writeInt(Data.getMaxSPD());
              comm.writeDouble(Data.getSteeringCar());

              System.out.println("Received initial information packet");
            }
            ;
            break;

          case H_CAR_CONFIRM: // 4
            {
              Data.setACC(comm.readInt());
              Data.setBRK(comm.readInt());
              Data.setMaxSPD(comm.readInt());
              Data.setgetSteeringCar(comm.readDouble());
              System.out.println("Received car confirm packet");

              // System.out.println(Data.getACC()+" "+Data.getBRK()+" "+Data.getSteeringCar());

              // pornim masina :))
              Engine.StartPosition(100, 0, Data.getCarAngle());

              comm.writeInt(H_DRIVE_INFO);
              comm.writeDouble(Data.getAccelerationPercentage());
              comm.writeDouble(Data.getBrakePercentage());
              comm.writeDouble(Data.getWantedAngle());
              comm.writeInt(0); // drop queue

              System.out.println("Send driving info1");
            }
            ;
            break;

          case H_POS_CONFIRM: // 6
            {
              Data.setCurrent_X_Meters(comm.readDouble());
              Data.setCurrent_Y_Meters(comm.readDouble());
              Data.setCurrentSpeed(comm.readDouble());
              Data.setCurrentAngleInRadians(comm.readDouble());
              Data.setCurrentDirection(comm.readInt());
              System.out.println("Received position confirmation packet");
              // System.out.println(Data.getCurrent_X_Meters()+"-"+Data.getCurrent_Y_Meters()+"pozitia masinii");
              // System.out.println(Data.getCurrentSpeed()+"-"+Data.getCurrentDirection()+"-"+Engine.FromRadiusToAngle(Data.getCurrentAngleInRadians()));

              Engine.evalPosition();

              comm.writeInt(H_DRIVE_INFO);
              comm.writeDouble(Data.getAccelerationPercentage());
              comm.writeDouble(Data.getBrakePercentage());
              comm.writeDouble(Data.getWantedAngle());
              comm.writeInt(0); // drop queue

              // System.out.println("Send driving info2");

            }
            ;
            break;

          case H_END_RACE:
            {
              System.out.println("Received end race packet");
            }
            ;
            break;

          default:
            {
              System.out.println("Unknown packet");
              // System.out.println(header);
            }
        }
      } catch (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
      }
    }
  }
Example #17
0
 public synchronized void addListener(Object key, SpaceListener listener) {
   Data data = (Data) map.get(key);
   if (data == null) map.put(key, (data = new Data(key)));
   data.addListener(listener);
 }