Esempio n. 1
0
  /**
   * Ecrit la piece donnée dans le fichier temporaire sur le disque
   *
   * @param piece : pièce à écrire
   * @param num : numéros de la pièce
   */
  private synchronized void writePieceTmpFile(byte[] piece, int num) {
    if (num < 0 || num >= this.nbPieces()) {
      throw new IllegalArgumentException();
    }
    if (piece.length > _piecesize) {
      throw new IllegalArgumentException();
    }

    try {
      RandomAccessFile writer_tmp = new RandomAccessFile(this, "rw");
      FileChannel writer = writer_tmp.getChannel();

      int index_piece = ((int) this.length() - this.headerSize()) / _piecesize;

      if (piece.length < _piecesize) {
        piece = Arrays.copyOf(piece, _piecesize);
      }
      Tools.write(writer, 4 + _key.length() + 4 + 4 + 4 * num, index_piece);
      Tools.write(writer, this.headerSize() + _piecesize * index_piece, piece);

      writer.force(true);
      writer_tmp.close();
    } catch (Exception e) {
      System.out.println("Unable to write tmp file piece");
      e.printStackTrace();
    }
  }
Esempio n. 2
0
  /** Initialise le header du fichier temporaire */
  private void initHeaderTmpFile() {
    try {
      FileOutputStream writer_tmp = new FileOutputStream(this);
      FileChannel writer = writer_tmp.getChannel();

      int offset = 0;

      // Taille de la clef
      Tools.write(writer, offset, _key.length());
      offset += 4;
      // Clef
      Tools.write(writer, offset, _key);
      offset += _key.length();
      // Size
      Tools.write(writer, offset, _size);
      offset += 4;
      // piecesize
      Tools.write(writer, offset, _piecesize);
      offset += 4;
      // Buffermap
      int i;
      for (i = 0; i < this.nbPieces(); i++) {
        Tools.write(writer, offset, -1);
        offset += 4;
      }

      writer.force(true);
      writer_tmp.close();
    } catch (Exception e) {
      System.out.println("Unable to create a new tmp file");
      e.printStackTrace();
    }
  }
  protected HighlightSeverity getSeverity(@NotNull RefElement element) {
    final PsiElement psiElement = element.getPointer().getContainingFile();
    if (psiElement != null) {
      final GlobalInspectionContextImpl context = getContext();
      final String shortName = getSeverityDelegateName();
      final Tools tools = context.getTools().get(shortName);
      if (tools != null) {
        for (ScopeToolState state : tools.getTools()) {
          InspectionToolWrapper toolWrapper = state.getTool();
          if (toolWrapper == getToolWrapper()) {
            return context
                .getCurrentProfile()
                .getErrorLevel(HighlightDisplayKey.find(shortName), psiElement)
                .getSeverity();
          }
        }
      }

      final InspectionProfile profile =
          InspectionProjectProfileManager.getInstance(context.getProject()).getInspectionProfile();
      final HighlightDisplayLevel level =
          profile.getErrorLevel(HighlightDisplayKey.find(shortName), psiElement);
      return level.getSeverity();
    }
    return null;
  }
Esempio n. 4
0
  /**
   * Lis et retourne une piece depuis le fichier temporaire sur le disque (la piece doit exister)
   *
   * @param num : numéros de la piece
   */
  private synchronized byte[] readPieceTmpFile(int num) {
    if (num < 0 || num >= this.nbPieces()) {
      throw new IllegalArgumentException();
    }

    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int index_piece = Tools.readInt(reader, 4 + _key.length() + 4 + 4 + 4 * num);
      if (index_piece < 0) {
        throw new IllegalArgumentException();
      }

      int size = _piecesize;
      if (num == this.nbPieces() - 1) {
        size = _size - _piecesize * (this.nbPieces() - 1);
      }

      byte[] piece = Tools.readBytes(reader, this.headerSize() + _piecesize * index_piece, size);
      reader_tmp.close();

      return piece;
    } catch (Exception e) {
      System.out.println("Unable to read tmp file piece");
      e.printStackTrace();
    }
    return new byte[0];
  }
Esempio n. 5
0
    @Override
    public void actionPerformed(ActionEvent arg0) {
      try {
        pref.clear();
        Tools.notify((Image) null, "Prefs", "Preferences were cleared");
      } catch (Exception e) {
        System.out.println("Remove preferences from splash fail");
      }

      s.setIcon(new ImageIcon(Tools.findImage("splash")));
      p.remove(r);
    }
Esempio n. 6
0
 // Method: checkExecScript
 // Verifies that execScript exists and is executable
 public boolean checkExecScript() {
   if (Tools.CheckFile(execScript)) {
     tcInstanceTools.LogMessage('d', "Found test case script: " + execScript);
     if (Tools.CheckExecutable(execScript)) {
       tcInstanceTools.LogMessage('d', "Script " + execScript + " is executable");
       return true;
     } else {
       tcInstanceTools.LogMessage('e', "Script " + execScript + " is not executable");
       return false;
     }
   } else {
     tcInstanceTools.LogMessage('e', "Cannot find test case script: " + execScript);
     return false;
   }
 }
Esempio n. 7
0
  /**
   * Créer le fichier complet correspondant Copie et réassemble les données Supprime le fichier
   * temporaire et renvoi le nouveau fichier
   */
  public synchronized FileShared tmpToComplete() {
    String name = this.getName();
    name = name.substring(0, name.length() - ((String) App.config.get("tmpExtension")).length());

    File complete = new File(App.config.get("downloadDir") + File.separator + name);
    if (complete.exists()) {
      throw new IllegalArgumentException();
    }

    try {
      FileOutputStream writer_tmp = new FileOutputStream(complete, true);
      FileChannel writer = writer_tmp.getChannel();

      int i;
      for (i = 0; i < this.nbPieces(); i++) {
        byte[] piece = this.readPieceTmpFile(i);
        Tools.write(writer, 0, piece);
      }

      writer.force(true);
      writer_tmp.close();
    } catch (Exception e) {
      System.out.println("Unable to write complete file");
      e.printStackTrace();
    }

    this.delete();

    return new FileShared(name);
  }
Esempio n. 8
0
 /**
  * @param expected the expected value
  * @param typeAdapter the body adapter for the cell
  * @param formatter the formatter
  * @param minLenForToggle the value determining whether the content should be rendered as a
  *     collapseable section.
  * @return the formatted content for a cell with a wrong expectation
  */
 public static String makeContentForWrongCell(
     String expected,
     RestDataTypeAdapter typeAdapter,
     CellFormatter<?> formatter,
     int minLenForToggle) {
   StringBuffer sb = new StringBuffer();
   sb.append(Tools.toHtml(expected));
   if (formatter.isDisplayActual()) {
     sb.append(toHtml("\n"));
     sb.append(formatter.label("expected"));
     String actual = typeAdapter.toString();
     sb.append(toHtml("-----"));
     sb.append(toHtml("\n"));
     if (minLenForToggle >= 0 && actual.length() > minLenForToggle) {
       sb.append(makeToggleCollapseable("toggle actual", toHtml(actual)));
     } else {
       sb.append(toHtml(actual));
     }
     sb.append(toHtml("\n"));
     sb.append(formatter.label("actual"));
   }
   List<String> errors = typeAdapter.getErrors();
   if (errors.size() > 0) {
     sb.append(toHtml("-----"));
     sb.append(toHtml("\n"));
     for (String e : errors) {
       sb.append(toHtml(e + "\n"));
     }
     sb.append(toHtml("\n"));
     sb.append(formatter.label("errors"));
   }
   return sb.toString();
 }
  /**
   * Prints a linkage specification block to a stream.
   *
   * @param spec The block to print.
   * @param stream The stream on which to print the block.
   */
  public static void defaultPrint(LinkageSpecification spec, OutputStream stream) {
    PrintStream p = new PrintStream(stream);

    p.print("extern \"");
    p.print(spec.calling_convention);
    p.print("\"\n{\n");
    Tools.printlnList(spec.children, stream);
    p.print("}");
  }
Esempio n. 10
0
  private void construct() {
    setTitle("JPokemon (ver 0.1)");
    setIconImage(Tools.findImage("main-icon"));
    setSize(720, 457); // WIDTH, HEIGHT
    setUndecorated(true);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    // Using JLayeredPane so my buttons can sit on the picture
    p = new JLayeredPane();
    ImageIcon bg;
    // Add Splash
    if (pref.getBoolean("beat", false)) bg = new ImageIcon(Tools.findImage("splashalt"));
    else bg = new ImageIcon(Tools.findImage("splash"));
    s.setIcon(bg);
    s.setBounds(10, 10, 700, 437);
    p.add(s, new Integer(-1));

    // Load Button
    LoadButton l = new LoadButton(this);
    l.setBounds(550, 100, 110, 30); // 10px border on all sides
    p.add(l, new Integer(0));

    // New Game Button
    NewButton n = new NewButton(this);
    n.setBounds(550, 60, 110, 30);
    p.add(n, new Integer(0));

    // Exit Game Button
    QuitButton q = new QuitButton(this);
    q.setBounds(550, 140, 110, 30);
    p.add(q, new Integer(0));

    // OPTIONAL: Reset Splash logon
    if (pref.getBoolean("beat", false)) {
      r = new ResetButton();
      r.setBounds(550, 180, 110, 30);
      p.add(r, new Integer(0));
    }
    add(p);

    setLocationRelativeTo(null);
  }
  public String toString() {
    StringBuilder str = new StringBuilder(80);

    str.append("extern \"");
    str.append(calling_convention);
    str.append("\"\n{\n");
    str.append(Tools.listToString(children, "\n") + "\n");
    str.append("}");

    return str.toString();
  }
Esempio n. 12
0
  /**
   * Prints a __builtin_offsetof expression to a stream.
   *
   * @param expr The expression to print.
   * @param stream The stream on which to print the expression.
   */
  public static void defaultPrint(OffsetofExpression expr, OutputStream stream) {
    PrintStream p = new PrintStream(stream);

    p.print("__builtin_offsetof");

    p.print("(");
    Tools.printListWithSeparator(expr.specs, stream, " ");
    p.print(",");
    expr.getExpression().print(stream);
    p.print(")");
  }
Esempio n. 13
0
  public String toString() {
    StringBuilder str = new StringBuilder(80);

    str.append("__builtin_offsetof");
    str.append("(");
    str.append(Tools.listToString(specs, " "));
    str.append(",");
    str.append(getExpression().toString());
    str.append(")");

    return str.toString();
  }
Esempio n. 14
0
  /** Lis le header du fichier temporaire et charge ses informations */
  private void readHeaderTmpFile() {
    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int key_size = 0;
      int offset = 0;

      // Taile de le clef
      key_size = Tools.readInt(reader, offset);
      offset += 4;
      // Clef
      _key = Tools.readString(reader, offset, key_size);
      offset += key_size;
      // Size
      _size = Tools.readInt(reader, offset);
      offset += 4;
      // piecesize
      _piecesize = Tools.readInt(reader, offset);
      offset += 4;
      // Buffermap
      _buffermap = new Buffermap(this.nbPieces(), false);
      int i;
      for (i = 0; i < this.nbPieces(); i++) {
        int index = Tools.readInt(reader, offset);
        if (index >= 0) {
          _buffermap.setBit(i, true);
        } else {
          _buffermap.setBit(i, false);
        }
        offset += 4;
      }

      reader_tmp.close();
    } catch (Exception e) {
      System.out.println("Unable to read tmp file header");
      e.printStackTrace();
    }
  }
Esempio n. 15
0
 /**
  * Find report with input, throw exception if could not found. When there's more than one, use id
  * small one
  *
  * @param clientDomain
  * @param tableName
  * @param reportType
  * @return
  * @throws Exception
  */
 private int getReportId(String clientDomain, String tableName, String reportType)
     throws Exception {
   reportType = reportType.toUpperCase();
   Table table = nds.schema.TableManager.getInstance().findTable(tableName);
   if (table == null) throw new NDSException("table " + tableName + " not found.");
   String sql =
       "select r.id from ad_report r, ad_client c where c.domain='"
           + clientDomain
           + "' and r.ad_table_id="
           + table.getId()
           + " and r.reporttype='"
           + reportType
           + "' and c.id=r.ad_client_id order by id asc";
   return Tools.getInt(QueryEngine.getInstance().doQueryOne(sql), -1);
 }
Esempio n. 16
0
  /**
   * return OutputStream of JasperReport object, this page could only be viewed from localhost for
   * security concern. parameter can be (id), or (table and type)
   *
   * @param id - report id, or
   * @param table - table name
   * @param type - reporttype "s","l","o", case insensitive
   * @param client(*) - client domain
   * @param version - version number, default to -1
   */
  public void process(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String clientName = request.getParameter("client");
    int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1);
    if (objectId == -1) {
      // try using table and type
      objectId =
          getReportId(clientName, request.getParameter("table"), request.getParameter("type"));
    }
    if (objectId == -1) {
      logger.error("report not found, request is:" + Tools.toString(request));
      throw new NDSException("report not found");
    }
    int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1);
    File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName));
    if (reportXMLFile.exists()) {
      // generate jasperreport if file not exists or not newer
      String reportName =
          reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf("."));
      File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper");
      if (!reportJasperFile.exists()
          || reportJasperFile.lastModified() < reportXMLFile.lastModified()) {
        JasperCompileManager.compileReportToFile(
            reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath());
      }
      InputStream is = new FileInputStream(reportJasperFile);
      response.setContentType("application/octetstream;");
      response.setContentLength((int) reportJasperFile.length());

      // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\"");
      ServletOutputStream os = response.getOutputStream();

      byte[] b = new byte[8192];
      int bInt;
      while ((bInt = is.read(b, 0, b.length)) != -1) {
        os.write(b, 0, bInt);
      }
      is.close();
      os.flush();
      os.close();
    } else {
      throw new NDSException("Not found report template");
    }
  }
Esempio n. 17
0
  /**
   * Lis et retourne une pièce depuis le fichier complet sur le disque
   *
   * @param num : numéros de la piece
   */
  private byte[] readPieceCompleteFile(int num) {
    if (num < 0 || num >= this.nbPieces()) {
      throw new IllegalArgumentException();
    }

    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      FileChannel reader = reader_tmp.getChannel();

      int size = _piecesize;
      if (num == this.nbPieces() - 1) {
        size = _size - _piecesize * (this.nbPieces() - 1);
      }

      byte[] piece = Tools.readBytes(reader, _piecesize * num, size);
      reader_tmp.close();

      return piece;
    } catch (Exception e) {
      System.out.println("Unable to read complete file piece");
      e.printStackTrace();
    }
    return new byte[0];
  }
 public Declaration findSymbol(IDExpression name) {
   return Tools.findSymbol(this, name);
 }
 public List getParentTables() {
   return Tools.getParentTables(this);
 }
Esempio n. 20
0
 public static void main(String args[]) {
   if (System.getProperty("java.version").substring(0, 3).compareTo("1.5") < 0) {
     javax.swing.JOptionPane.showMessageDialog(
         null, "ImageJ " + VERSION + " requires Java 1.5 or later.");
     System.exit(0);
   }
   boolean noGUI = false;
   int mode = STANDALONE;
   arguments = args;
   // System.setProperty("file.encoding", "UTF-8");
   int nArgs = args != null ? args.length : 0;
   boolean commandLine = false;
   for (int i = 0; i < nArgs; i++) {
     String arg = args[i];
     if (arg == null) continue;
     if (args[i].startsWith("-")) {
       if (args[i].startsWith("-batch")) noGUI = true;
       else if (args[i].startsWith("-debug")) IJ.setDebugMode(true);
       else if (args[i].startsWith("-ijpath") && i + 1 < nArgs) {
         if (IJ.debugMode) IJ.log("-ijpath: " + args[i + 1]);
         Prefs.setHomeDir(args[i + 1]);
         commandLine = true;
         args[i + 1] = null;
       } else if (args[i].startsWith("-port")) {
         int delta = (int) Tools.parseDouble(args[i].substring(5, args[i].length()), 0.0);
         commandLine = true;
         if (delta == 0) mode = EMBEDDED;
         else if (delta > 0 && DEFAULT_PORT + delta < 65536) port = DEFAULT_PORT + delta;
       }
     }
   }
   // If existing ImageJ instance, pass arguments to it and quit.
   boolean passArgs = mode == STANDALONE && !noGUI;
   if (IJ.isMacOSX() && !commandLine) passArgs = false;
   if (passArgs && isRunning(args)) return;
   ImageJ ij = IJ.getInstance();
   if (!noGUI && (ij == null || (ij != null && !ij.isShowing()))) {
     ij = new ImageJ(null, mode);
     ij.exitWhenQuitting = true;
   }
   int macros = 0;
   for (int i = 0; i < nArgs; i++) {
     String arg = args[i];
     if (arg == null) continue;
     if (arg.startsWith("-")) {
       if ((arg.startsWith("-macro") || arg.startsWith("-batch")) && i + 1 < nArgs) {
         String arg2 = i + 2 < nArgs ? args[i + 2] : null;
         Prefs.commandLineMacro = true;
         if (noGUI && args[i + 1].endsWith(".js")) Interpreter.batchMode = true;
         IJ.runMacroFile(args[i + 1], arg2);
         break;
       } else if (arg.startsWith("-eval") && i + 1 < nArgs) {
         String rtn = IJ.runMacro(args[i + 1]);
         if (rtn != null) System.out.print(rtn);
         args[i + 1] = null;
       } else if (arg.startsWith("-run") && i + 1 < nArgs) {
         IJ.run(args[i + 1]);
         args[i + 1] = null;
       }
     } else if (macros == 0 && (arg.endsWith(".ijm") || arg.endsWith(".txt"))) {
       IJ.runMacroFile(arg);
       macros++;
     } else if (arg.length() > 0 && arg.indexOf("ij.ImageJ") == -1) {
       File file = new File(arg);
       IJ.open(file.getAbsolutePath());
     }
   }
   if (IJ.debugMode && IJ.getInstance() == null) new JavaProperties().run("");
   if (noGUI) System.exit(0);
 }
Esempio n. 21
0
 /** 标签体处理 */
 public void doTag() throws JspException, IOException {
   // 使用WebApplicationContextUtils工具类获取Spring IOC容器中的dao实例
   dao =
       (BaseDAOImpl)
           WebApplicationContextUtils.getRequiredWebApplicationContext(
                   ((PageContext) getJspContext()).getServletContext())
               .getBean("dao");
   // 构造查询新闻列表的HQL语句
   if (newstype.equals("4")) { // 所有类型
     hql =
         " from News as a where a.status=1 and a.newscolumns.columnCode in("
             + Tools.formatString(section)
             + ") and a.isPicNews=1 order by a.priority desc,a.id desc";
   } else {
     hql =
         " from News as a where a.status=1 and a.newscolumns.columnCode in("
             + Tools.formatString(section)
             + ") and a.newsType="
             + newstype
             + " and a.isPicNews=1 order by a.priority desc,a.id desc";
   }
   StringBuffer sb = new StringBuffer();
   List list = dao.query(hql, 1, number);
   if (list == null || list.size() == 0) {
     // 输出处理结果到页面上
     getJspContext().getOut().println("");
     return;
   }
   Iterator it = list.iterator();
   sb.append("    <script language=javascript>\n");
   sb.append("	var focus_width" + slideno + "=" + width + ";     /*幻灯片新闻图片宽度*/\n");
   sb.append("	var focus_height" + slideno + "=" + height + ";    /*幻灯片新闻图片高度*/\n");
   sb.append("	var text_height" + slideno + "=20;    /*幻灯片新闻文字标题高度*/\n");
   sb.append(
       "	var swf_height"
           + slideno
           + " = focus_height"
           + slideno
           + "+text_height"
           + slideno
           + ";\n");
   sb.append("	var pics" + slideno + " = '';\n");
   sb.append("	var links" + slideno + " = '';\n");
   sb.append("	var texts" + slideno + " = '';\n");
   sb.append("	function ati" + slideno + "(url, img, title)\n");
   sb.append("	{\n");
   sb.append("		if(pics" + slideno + " != '')\n");
   sb.append("		{\n");
   sb.append("			pics" + slideno + " = \"|\" + pics" + slideno + ";\n");
   sb.append("			links" + slideno + " = \"|\" + links" + slideno + ";\n");
   sb.append("			texts" + slideno + " = \"|\" + texts" + slideno + ";\n");
   sb.append("		}");
   sb.append("		pics" + slideno + " = escape(img) + pics" + slideno + ";\n");
   sb.append("		links" + slideno + " = escape(url) + links" + slideno + ";\n");
   sb.append("		texts" + slideno + " = title + texts" + slideno + ";\n");
   sb.append("	}\n");
   sb.append("    </script>\n");
   sb.append("    <script language=javascript>	\n");
   while (it.hasNext()) {
     obj = (News) it.next();
     if (obj.getTitle().length() > titlelen) {
       sb.append(
           "      ati"
               + slideno
               + "('"
               + baseurl
               + obj.getHtmlPath()
               + "', '"
               + baseurl
               + "/"
               + obj.getPicture().trim()
               + "', '"
               + Tools.cutString(obj.getTitle(), titlelen * 2)
               + "');\n");
     } else {
       sb.append(
           "      ati"
               + slideno
               + "('"
               + baseurl
               + obj.getHtmlPath()
               + "', '"
               + baseurl
               + "/"
               + obj.getPicture().trim()
               + "', '"
               + obj.getTitle()
               + "');\n");
     }
   }
   sb.append(
       "	document.write('<embed src=\""
           + baseurl
           + "/js/pixviewer.swf\" wmode=\"opaque\" FlashVars=\"pics='+pics"
           + slideno
           + "+'&links='+links"
           + slideno
           + "+'&texts='+texts"
           + slideno
           + "+'&borderwidth='+focus_width"
           + slideno
           + "+'&borderheight='+focus_height"
           + slideno
           + "+'&textheight='+text_height"
           + slideno
           + "+'\" menu=\"false\" bgcolor=\"#DADADA\" quality=\"high\" width=\"'+ focus_width"
           + slideno
           + "+'\" height=\"'+ swf_height"
           + slideno
           + " +'\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\"/>');	\n");
   sb.append("</script>\n");
   // 输出处理结果到页面上
   getJspContext().getOut().println(sb);
 }
Esempio n. 22
0
	public void write2(String strRoute, String strElement, String strSet,
			int flag) {

		//SAXBuilder builder=new SAXBuilder();
		try {
			String str = null;
			Document doc = builder.build(xmlFileName);
			Element root = doc.getRootElement();
			Element element = root;

			StringTokenizer st = new StringTokenizer(strRoute, ";");
			str = st.nextToken();

			while (st.hasMoreTokens()) {
				str = st.nextToken();
				//mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,str);
				element = element.getChild(str);

			}

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"test :"+str);
			element = (Element) element.getParent();

			//若需要改写的不是XML文件的第一个同名元素,则获取该元素
			//方法为:将之前的元素依次移到后面,需要改写的元素前移至第一个
			/*
			 * if(flag>1) { int j=flag; while(j!=1) {
			 * 
			 * Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); j--; } }
			 */
			element = element.getChild(str).getChild(strElement);

			//	mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP,"gettxt
			// "+element.getText());

			element.setText(strSet);

			//若需要改写的不是XML文件的第一个同名元素
			//上面改变了次序,需要在成功改写后恢复原有次序
			/*
			 * if(flag!=1) {
			 * 
			 * java.util.List children=element.getChildren(); Iterator
			 * iterator=children.iterator(); int count=0;
			 * while(iterator.hasNext()) { Element
			 * child=(Element)iterator.next(); count++; }
			 * 
			 * System.out.println("count"+count);
			 * 
			 * k=(count+1-flag)%count;
			 * 
			 * while(k!=0) { Element tmp=element.getChild(str);
			 * element.addContent(tmp.detach()); k--; } }
			 *  
			 */
			XMLOutputter outputter = new XMLOutputter("", false, "GB2312");
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new FileWriter(xmlFileName)));

			Document myDocument = root.getDocument();

			outputter.output(myDocument, out);
			out.close();

		} catch (JDOMException jdome) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, xmlFileName
			//					+ " is not well-formed" + "\n" + jdome);
			System.out.println("[" + Tools.getDateTime2() + "]XML数据文件:"
					+ xmlFileName + "  不正确!!");
			jdome.printStackTrace();

		} catch (IOException ioe) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, ioe);
			System.out.println("[" + Tools.getDateTime2() + "]IO出错!!");
			ioe.printStackTrace();
		} catch (Exception e) {
			//			mypage.FcfeMain.wR(mypage.FcfeMain.SIM_APP_ERP, "write not
			// succeed"
			//					+ "\n" + e);
			System.out.println("[" + Tools.getDateTime2() + "]未知错误!!");
			e.printStackTrace();

		}

	}
Esempio n. 23
0
  /**
   * Run the program.
   *
   * @param args Command-line arguments: <token file> <model file>.
   */
  public static void main(String[] args) {

    // check number of command-line arguments
    if (args.length != 2) {
      System.out.println(
          "USAGE: java " + LearnTypos.class.getName() + " <token file> <model file>");
      System.exit(0);
    }

    // check if token file exists
    File tokenFile = new File(args[0]);
    if (!tokenFile.isFile()) {
      System.err.println(
          "ERROR: token file \"" + tokenFile.getAbsolutePath() + "\" does not exist");
      System.exit(1);
    }

    // check if model file exists
    File modelFile = new File(args[1]);
    Model model;
    if (!modelFile.isFile()) {
      System.out.println("Creating new model...");
      model = new Model();
    } else {
      System.out.println("Loading existing model...");
      model = (Model) Tools.deserialize(modelFile);
    }

    // add tokens to model
    try {
      System.out.println("Adding token to model...");
      FileReader fileReader = new FileReader(tokenFile);
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      String line;

      try {

        // treat each line as a token
        while ((line = bufferedReader.readLine()) != null) {
          model.addToken(line.trim());
        }

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        bufferedReader.close();
        fileReader.close();
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // serialize model
    System.out.println("Saving model to file...");
    Tools.serialize(modelFile, model);

    System.out.println("Done!");
  }