private void serializeRuntimeException() throws WebServiceException {
    try {
      MessageFactory factory = _soapContext.getMessageFactory();
      SOAPMessage message = factory.createMessage();

      QName faultcode =
          new QName(
              message.getSOAPBody().getNamespaceURI(), "Server", message.getSOAPBody().getPrefix());

      message.getSOAPBody().addFault(faultcode, _runtimeException.getMessage());

      _soapContext.setMessage(message);
      _source = _soapContext.getMessage().getSOAPPart().getContent();
    } catch (SOAPException se) {
      throw new WebServiceException(se);
    }
  }
예제 #2
0
  /**
   * Creates the logfile to write log-infos into.
   *
   * @return The writer object instance
   */
  private static PrintWriter createLogFile() {
    String tempDir = System.getProperty("java.io.tmpdir");

    File tempDirFile = new File(tempDir);

    try {
      tempDirFile.mkdirs();
    } catch (RuntimeException e) {
      e.printStackTrace();
    }

    String logfilename = LOGFILENAME;
    System.out.println("creating Logfile: '" + logfilename + "' in: '" + tempDir + "'");

    File out = new File(tempDir, logfilename);

    PrintWriter logfile;
    if (tempDirFile.canWrite()) {
      try {
        BufferedWriter fw =
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out), "UTF-8"));
        logfile = setLogFile(new PrintWriter(fw));
      } catch (Exception e) {
        logfile = null;
        e.printStackTrace();
      }
    } else {
      logfile = null;
      System.err.println("Fatal: cannot write File: '" + logfilename + "' into: " + tempDirFile);
    }

    return logfile;
  }
예제 #3
0
  protected int streamThroughFailing(XMLInputFactory f, String contents, String msg)
      throws XMLStreamException {
    int result = 0;
    try {
      XMLStreamReader sr = constructStreamReader(f, contents);
      result = streamThrough(sr);
    } catch (XMLStreamException ex) { // good
      if (PRINT_EXP_EXCEPTION) {
        System.out.println(
            "Expected failure: '" + ex.getMessage() + "' " + "(matching message: '" + msg + "')");
      }
      return 0;
    } catch (RuntimeException ex2) { // ok
      if (PRINT_EXP_EXCEPTION) {
        System.out.println(
            "Expected failure: '" + ex2.getMessage() + "' " + "(matching message: '" + msg + "')");
      }
      return 0;
    } catch (Throwable t) { // not so good
      fail("Expected an XMLStreamException or RuntimeException for " + msg + ", got: " + t);
    }

    fail("Expected an exception for " + msg);
    return result; // never gets here
  }
 public void close() throws IOException {
   try {
     myArtifactsBuildData.close();
   } finally {
     try {
       synchronized (mySourceToOutputLock) {
         closeSourceToOutputStorages();
       }
     } finally {
       try {
         closeStorage(mySrcToFormMap);
       } finally {
         final Mappings mappings = myMappings;
         if (mappings != null) {
           try {
             mappings.close();
           } catch (RuntimeException e) {
             final Throwable cause = e.getCause();
             if (cause instanceof IOException) {
               throw ((IOException) cause);
             }
             throw e;
           }
         }
       }
     }
   }
 }
예제 #5
0
 void setFormData(WObject.FormData formData) {
   if (!(formData.values.length == 0)) {
     List<String> attributes = new ArrayList<String>();
     attributes = new ArrayList<String>(Arrays.asList(formData.values[0].split(";")));
     if (attributes.size() == 6) {
       try {
         this.volume_ = Double.parseDouble(attributes.get(0));
       } catch (RuntimeException e) {
         this.volume_ = -1;
       }
       try {
         this.current_ = Double.parseDouble(attributes.get(1));
       } catch (RuntimeException e) {
         this.current_ = -1;
       }
       try {
         this.duration_ = Double.parseDouble(attributes.get(2));
       } catch (RuntimeException e) {
         this.duration_ = -1;
       }
       this.playing_ = attributes.get(3).equals("0");
       this.ended_ = attributes.get(4).equals("1");
       try {
         this.readyState_ = intToReadyState(Integer.parseInt(attributes.get(5)));
       } catch (RuntimeException e) {
         throw new WException(
             "WAbstractMedia: error parsing: " + formData.values[0] + ": " + e.toString());
       }
     } else {
       throw new WException("WAbstractMedia: error parsing: " + formData.values[0]);
     }
   }
 }
예제 #6
0
  private void initializeContent() {

    InputStream is = null;
    try {

      File tempFile = new File(kloWorkspaceFile.getTempName(owner));
      if (tempFile.exists()) {
        is = new FileInputStream(tempFile);
      } else {

        if (kloWorkspaceFile.getFileName() == null) {
          throw new IOException("The file doesn't exist.");
        }

        File file = new File(kloWorkspaceFile.getFileName());
        if (!file.exists()) {
          throw new IOException("Can't access the file: " + file.toURI());
        }
        is = new FileInputStream(file);
      }

      splitSourceFile(highlightSource(is));
    } catch (IOException exception) {
      sourceCode = "Can't read file: " + exception.getLocalizedMessage();
    } catch (RuntimeException re) {
      sourceCode = "Problem for display the source code content: " + re.getLocalizedMessage();
    } finally {
      IOUtils.closeQuietly(is);
    }
  }
예제 #7
0
 public static void doThis() {
   try {
     NonRTException.entry();
     RTException.entry();
   } catch (RuntimeException e) {
     e.printStackTrace();
     // } catch (IOException e) {
     //   e.printStackTrace();
   }
 }
예제 #8
0
 private void doDisableMetadataIndexing() {
   ArchivalUnit au = getAu();
   if (au == null) return;
   try {
     disableMetadataIndexing(au, false);
   } catch (RuntimeException e) {
     log.error("Can't disable metadata indexing", e);
     errMsg = "Error: " + e.toString();
   }
 }
예제 #9
0
 private void forceReindexMetadata() {
   ArchivalUnit au = getAu();
   if (au == null) return;
   try {
     startReindexingMetadata(au, true);
   } catch (RuntimeException e) {
     log.error("Can't reindex metadata", e);
     errMsg = "Error: " + e.toString();
   }
 }
예제 #10
0
파일: Cache.java 프로젝트: Calc86/ipartner
  /**
   * @param path
   * @return byte or null
   */
  public byte[] getFile(String path) {
    Log.d(TAG, "get file " + path); // NON-NLS

    File f = new File(getFullCachePath(path));
    if (!f.exists()) {
      Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS
      return null;
    }

    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      FileInputStream fileInputStream = new FileInputStream(f);
      byte[] buf = new byte[1024];
      int numRead = 0;
      while ((numRead = fileInputStream.read(buf)) != -1) out.write(buf, 0, numRead);

      fileInputStream.close();

      return out.toByteArray();

    } catch (FileNotFoundException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (StreamCorruptedException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (IOException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (IllegalArgumentException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (RuntimeException e) {
      // не позволим кэшу убить нашу программу
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (Exception e) {
      // не позволим кэшу убить нашу программу
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    }
  }
  public static void main(String[] args) {
    String inputMaf = null;
    String outputMaf = null;

    // default config params
    boolean useCache = true; // use cache or not
    boolean sort = false; // sort output MAF cols or not
    boolean addMissing = false; // add missing standard cols or not

    // process program arguments

    int i;

    for (i = 0; i < args.length; i++) {
      if (args[i].startsWith("-")) {
        if (args[i].equalsIgnoreCase("-nocache")) {
          useCache = false;
        } else if (args[i].equalsIgnoreCase("-sort")) {
          sort = true;
        } else if (args[i].equalsIgnoreCase("-std")) {
          addMissing = true;
        }
      } else {
        break;
      }
    }

    if (args.length - i < 2) {
      System.out.println(
          "command line usage: oncotateMaf.sh [-nocache] [-sort] [-std] "
              + "<input_maf_file> <output_maf_file>");
      System.exit(1);
    }

    inputMaf = args[i];
    outputMaf = args[i + 1];

    int oncoResult = 0;

    try {
      oncoResult = driver(inputMaf, outputMaf, useCache, sort, addMissing);
    } catch (RuntimeException e) {
      System.out.println("Fatal error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    } finally {
      // check errors at the end
      if (oncoResult != 0) {
        // TODO produce different error codes, for different types of errors?
        System.out.println("Process completed with " + oncoResult + " error(s).");
        System.exit(2);
      }
    }
  }
예제 #12
0
 @Override
 public void write(@SuppressWarnings("NullableProblems") byte[] bytes) {
   try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true))) {
     bos.write(bytes);
     bos.close();
   } catch (IOException e) {
     RuntimeException ex =
         new RuntimeException("Unable to write to file " + file.getAbsolutePath());
     ex.initCause(e);
     throw ex;
   }
 }
예제 #13
0
  public void testPrune() throws Exception {
    CtClass cc = sloader.get("test2.Prune");
    cc.stopPruning(false);
    System.out.println(cc);
    cc.addField(new CtField(CtClass.intType, "f", cc));
    cc.toBytecode();
    try {
      cc.defrost();
      fail("can call defrost()");
    } catch (RuntimeException e) {
      assertTrue(e.getMessage().indexOf("prune") >= 0);
    }

    System.out.println(cc);
  }
예제 #14
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    // session属于http范畴,所以要将ServletRequest转换成httpServletRequest

    try {
      HttpServletRequest req = (HttpServletRequest) request;
      HttpSession session = req.getSession();
      if (session.getAttribute("username") != null) {
        chain.doFilter(request, response);
      } else {
        request.getRequestDispatcher("error.jsp").forward(request, response);
      }
    } catch (RuntimeException e) {
      e.printStackTrace();
    }
  }
예제 #15
0
  @Override
  public void render(Parameters blockParameters, Writer w, RenderHints hints)
      throws FrameworkException {

    if (decorate) {
      try {
        decorateIntro(hints, w, null);
      } catch (IOException ioe) {
        throw new FrameworkException(ioe);
      }
    }
    String name = getResource();
    ResourceLoader loader = ResourceLoader.Type.valueOf(resourceType.toUpperCase()).get();
    try {
      InputStream is = loader.getResourceAsStream(name);
      if (is == null)
        throw new FrameworkException(
            "No such resource " + loader.getResource(name) + " in " + loader);
      if (xsl == null) {
        Reader r = loader.getReader(is, name);
        char[] buf = new char[1000];
        int c;
        while ((c = r.read(buf, 0, 1000)) > 0) {
          w.write(buf, 0, c);
        }
      } else {
        /// convert using the xsl and spit out that.
        URL x = ResourceLoader.getConfigurationRoot().getResource(xsl);
        Utils.xslTransform(blockParameters, loader.getResource(name), is, w, x);
      }
    } catch (IOException ioe) {
      throw new FrameworkException(ioe);
    } catch (javax.xml.transform.TransformerException te) {
      throw new FrameworkException(te.getMessage(), te);
    } catch (RuntimeException e) {
      log.debug(e.getMessage(), e);
      throw e;
    } finally {
      if (decorate) {
        try {
          decorateOutro(hints, w);
        } catch (IOException ioe) {
          throw new FrameworkException(ioe);
        }
      }
    }
  }
예제 #16
0
  /**
   * Obtains DOMImpementaton interface providing a number of methods for performing operations that
   * are independent of any particular DOM instance.
   *
   * @throw DOMException <code>NOT_SUPPORTED_ERR</code> if cannot get DOMImplementation
   * @throw FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @return DOMImplementation implementation
   */
  private static DOMImplementation getDOMImplementation()
      throws DOMException { // can be made public

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    try {
      return factory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException ex) {
      throw new DOMException(
          DOMException.NOT_SUPPORTED_ERR,
          "Cannot create parser satisfying configuration parameters"); // NOI18N
    } catch (RuntimeException e) {
      // E.g. #36578, IllegalArgumentException. Try to recover gracefully.
      throw (DOMException)
          new DOMException(DOMException.NOT_SUPPORTED_ERR, e.toString()).initCause(e);
    }
  }
예제 #17
0
 public void handleElement(Element e) {
   // create family
   if (e.getName().equals("family")) {
     try {
       lexicon.add(new Family(e));
     } catch (RuntimeException exc) {
       System.err.println("Skipping family: " + e.getAttributeValue("name"));
       System.err.println(exc.toString());
     }
   }
   // save distributive attributes
   else if (e.getName().equals("distributive-features")) distrElt = e;
   // save licensing features
   else if (e.getName().equals("licensing-features")) licensingElt = e;
   // save relation sort order
   else if (e.getName().equals("relation-sorting")) relationSortingElt = e;
 }
  /**
   * @param javaParameters parameters.
   * @param forceDynamicClasspath whether dynamic classpath will be used for this execution, to
   *     prevent problems caused by too long command line.
   * @return a command line.
   * @throws CantRunException if there are problems with JDK setup.
   */
  public GeneralCommandLine createFromJavaParameters(
      final SimpleJavaParameters javaParameters, final boolean forceDynamicClasspath)
      throws CantRunException {
    try {
      return ApplicationManager.getApplication()
          .runReadAction(
              new Computable<GeneralCommandLine>() {
                public GeneralCommandLine compute() {
                  try {
                    final Sdk jdk = javaParameters.getJdk();
                    if (jdk == null) {
                      throw new CantRunException(
                          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
                    }

                    final SdkTypeId sdkType = jdk.getSdkType();
                    if (!(sdkType instanceof JavaSdkType)) {
                      throw new CantRunException(
                          ExecutionBundle.message("run.configuration.error.no.jdk.specified"));
                    }

                    final String exePath = ((JavaSdkType) sdkType).getVMExecutablePath(jdk);
                    if (exePath == null) {
                      throw new CantRunException(
                          ExecutionBundle.message("run.configuration.cannot.find.vm.executable"));
                    }
                    if (javaParameters.getMainClass() == null
                        && javaParameters.getJarPath() == null) {
                      throw new CantRunException(
                          ExecutionBundle.message("main.class.is.not.specified.error.message"));
                    }

                    return setupJVMCommandLine(exePath, javaParameters, forceDynamicClasspath);
                  } catch (CantRunException e) {
                    throw new RuntimeException(e);
                  }
                }
              });
    } catch (RuntimeException e) {
      if (e.getCause() instanceof CantRunException) {
        throw (CantRunException) e.getCause();
      } else {
        throw e;
      }
    }
  }
예제 #19
0
  private boolean startCrawl(ArchivalUnit au, boolean force, boolean deep)
      throws CrawlManagerImpl.NotEligibleException {
    CrawlManagerImpl cmi = (CrawlManagerImpl) crawlMgr;
    if (force) {
      RateLimiter limit = cmi.getNewContentRateLimiter(au);
      if (!limit.isEventOk()) {
        limit.unevent();
      }
    }
    cmi.checkEligibleToQueueNewContentCrawl(au);
    String delayMsg = "";
    String deepMsg = "";
    try {
      cmi.checkEligibleForNewContentCrawl(au);
    } catch (CrawlManagerImpl.NotEligibleException e) {
      delayMsg = ", Start delayed due to: " + e.getMessage();
    }
    Configuration config = ConfigManager.getCurrentConfig();
    int pri = config.getInt(PARAM_CRAWL_PRIORITY, DEFAULT_CRAWL_PRIORITY);

    CrawlReq req;
    try {
      req = new CrawlReq(au);
      req.setPriority(pri);
      if (deep) {
        int d = Integer.parseInt(formDepth);
        if (d < 0) {
          errMsg = "Illegal refetch depth: " + d;
          return false;
        }
        req.setRefetchDepth(d);
        deepMsg = "Deep (" + req.getRefetchDepth() + ") ";
      }
    } catch (NumberFormatException e) {
      errMsg = "Illegal refetch depth: " + formDepth;
      return false;
    } catch (RuntimeException e) {
      log.error("Couldn't create CrawlReq: " + au, e);
      errMsg = "Couldn't create CrawlReq: " + e.toString();
      return false;
    }
    cmi.startNewContentCrawl(req, null);
    statusMsg = deepMsg + "Crawl requested for " + au.getName() + delayMsg;
    return true;
  }
예제 #20
0
  /**
   * Evaluates and returns the value of the expression as an object. The EvaluatorVisitor member ev
   * is used to do the evaluation procedure. This method is useful when the type of the value is
   * unknown, or not important.
   *
   * @return The calculated value of the expression if no errors occur. Returns null otherwise.
   */
  public Object getValueAsObject() {
    Object result;

    if (topNode == null) return null;
    // evaluate the expression
    try {
      result = ev.getValue(topNode, symTab);
    } catch (ParseException e) {
      if (debug) System.out.println(e);
      errorList.addElement("Error during evaluation: " + e.getMessage());
      return null;
    } catch (RuntimeException e) {
      if (debug) System.out.println(e);
      errorList.addElement(e.getClass().getName() + ": " + e.getMessage());
      return null;
    }
    return result;
  }
예제 #21
0
  // @Ignore
  @Test
  public void validateNegativeMaxLengthTest() {
    ValidationTestApp validationTestApp =
        new ValidationTestApp(
            new File(testMeta.getDir()), -1L, new SingleHDFSByteExactlyOnceWriter());

    boolean error = false;

    try {
      LocalMode.runApp(validationTestApp, 1);
    } catch (RuntimeException e) {
      if (e.getCause() instanceof ConstraintViolationException) {
        error = true;
      }
    }

    Assert.assertEquals("Max length validation not thrown with -1 max length", true, error);
  }
예제 #22
0
 public void handleElement(Element e) {
   // create morph item
   if (e.getName().equals("entry")) {
     try {
       morphItems.add(new MorphItem(e));
     } catch (RuntimeException exc) {
       System.err.println("Skipping morph item: " + e.getAttributeValue("word"));
       System.err.println(exc.toString());
     }
   }
   // create macro item
   else if (e.getName().equals("macro")) {
     try {
       macroItems.add(new MacroItem(e));
     } catch (RuntimeException exc) {
       System.err.println("Skipping macro item: " + e.getAttributeValue("name"));
       System.err.println(exc.toString());
     }
   }
 }
예제 #23
0
 public static void main(String... args) {
   try {
     JavaCompiler javac = javax.tools.ToolProvider.getSystemJavaCompiler();
     DiagnosticListener<JavaFileObject> dl =
         new DiagnosticListener<JavaFileObject>() {
           public void report(Diagnostic<? extends JavaFileObject> message) {
             throw new NullPointerException(SILLY_BILLY);
           }
         };
     StandardJavaFileManager fm = javac.getStandardFileManager(dl, null, null);
     Iterable<? extends JavaFileObject> files =
         fm.getJavaFileObjectsFromStrings(Arrays.asList("badfile.java"));
     javac.getTask(null, fm, dl, null, null, files).call();
   } catch (RuntimeException e) {
     Throwable cause = e.getCause();
     if (cause instanceof NullPointerException && cause.getMessage().equals(SILLY_BILLY)) return;
     throw new Error("unexpected exception caught: " + e);
   } catch (Throwable t) {
     throw new Error("unexpected exception caught: " + t);
   }
   throw new Error("no exception caught");
 }
예제 #24
0
 private OAuthAccessToken parseJsonToken(HttpMessage response) {
   com.google.gson.JsonObject root = new com.google.gson.JsonObject();
   com.google.gson.JsonParseException pe = null;
   try {
     root =
         (com.google.gson.JsonObject) new com.google.gson.JsonParser().parse(response.getBody());
   } catch (com.google.gson.JsonParseException error) {
     pe = error;
   }
   boolean ok = root != null;
   if (!ok) {
     logger.error(
         new StringWriter().append("parseJsonToken(): ").append(pe.toString()).toString());
     throw new OAuthProcess.TokenError(WString.tr("Wt.Auth.OAuthService.badjson"));
   } else {
     if (response.getStatus() == 200) {
       try {
         String accessToken = root.get("access_token").getAsString();
         int secs = JsonUtils.orIfNullInt(root.get("expires_in"), -1);
         WDate expires = null;
         if (secs > 0) {
           expires = new WDate(new Date()).addSeconds(secs);
         }
         String refreshToken = JsonUtils.orIfNullString(root.get("refreshToken"), "");
         return new OAuthAccessToken(accessToken, expires, refreshToken);
       } catch (RuntimeException e) {
         logger.error(
             new StringWriter().append("token response error: ").append(e.toString()).toString());
         throw new OAuthProcess.TokenError(WString.tr("Wt.Auth.OAuthService.badresponse"));
       }
     } else {
       throw new OAuthProcess.TokenError(
           WString.tr(
               "Wt.Auth.OAuthService."
                   + JsonUtils.orIfNullString(root.get("error"), "missing error")));
     }
   }
 }
예제 #25
0
  public void testMakeNestedClass() throws Exception {
    CtClass outer = sloader.get("test2.Nested4");
    try {
      CtClass inner = outer.makeNestedClass("Inner", false);
      fail();
    } catch (RuntimeException e) {
      print(e.getMessage());
    }

    CtClass nested = outer.makeNestedClass("Inner", true);
    outer.stopPruning(true);
    outer.writeFile();
    outer.defrost();
    String src = "public int f() { return test2.Nested4.value; }";

    CtMethod m = CtNewMethod.make(src, nested);
    nested.addMethod(m);
    nested.writeFile();
    outer.writeFile();

    Object iobj = make(nested.getName());
    assertEquals(6, invoke(iobj, "f"));
  }
예제 #26
0
파일: JSSA.java 프로젝트: behnaaz/jerl
 public JSSA(Type.Class c, DataInput in, ConstantPool cp) throws IOException {
   super(c, in, cp);
   local = new Expr[maxLocals];
   stack = new Expr[maxStack];
   int n = 0;
   if (!isStatic()) local[n++] = new Argument("this", method.getDeclaringClass());
   for (int i = 0; i < this.method.getNumArgs(); i++)
     local[n++] = new Argument("arg" + i, this.method.getArgType(i));
   for (int i = 0; i < size(); i++) {
     int op = get(i);
     Object arg = getArg(i);
     try {
       Object o = addOp(op, arg);
       if (o != null) {
         ops[numOps] = o;
         ofs[numOps++] = i;
       }
     } catch (RuntimeException e) {
       System.err.println("Had a problem at PC: " + i + " of " + method);
       e.printStackTrace();
       throw new IOException("invalid class file");
     }
   }
 }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    try {
      Object accountObject = session.getValue(ACCOUNT);

      // If no account object was put in the session, or
      // if one exists but it is not a hashtable, then
      // redirect the user to the original login page

      if (accountObject == null)
        throw new RuntimeException("You need to log in to use this service!");

      if (!(accountObject instanceof Hashtable))
        throw new RuntimeException("You need to log in to use this service!");

      Hashtable account = (Hashtable) accountObject;

      String userName = (String) account.get("name");

      //////////////////////////////////////////////
      // Display Messages for the user who logged in
      //////////////////////////////////////////////
      out.println("<HTML>");
      out.println("<HEAD>");
      out.println("<TITLE>Contacts for " + userName + "</TITLE>");
      out.println("</HEAD>");
      out.println("<BODY BGCOLOR='#EFEFEF'>");
      out.println("<H3>Welcome " + userName + "</H3>");

      out.println("<CENTER>");

      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con =
            DriverManager.getConnection(
                "jdbc:mysql://localhost/contacts?user=kareena&password=kapoor");

        stmt = con.createStatement();
        rs =
            stmt.executeQuery(
                "SELECT * FROM contacts WHERE userName='******' ORDER BY contactID");

        out.println("<form name='deleteContactsForm' method='post' action='deleteContact'>");

        out.println("<TABLE BGCOLOR='#EFEFFF' CELLPADDING='2' CELLSPACING='4' BORDER='1'>");
        out.println("<TR BGCOLOR='#D6DFFF'>");
        out.println("<TD ALIGN='center'><B>Contact ID</B></TD>");
        out.println("<TD ALIGN='center'><B>Contact Name</B></TD>");
        out.println("<TD ALIGN='center'><B>Comment</B></TD>");
        out.println("<TD ALIGN='center'><B>Date</B></TD>");
        out.println("<TD ALIGN='center'><B>Delete Contacts</B></TD>");
        out.println("</TR>");

        int nRows = 0;
        while (rs.next()) {
          nRows++;
          String messageID = rs.getString("contactID");
          String fromUser = rs.getString("contactName");
          String message = rs.getString("comments");
          String messageDate = rs.getString("dateAdded");

          out.println("<TR>");
          out.println("<TD>" + messageID + "</TD>");
          out.println("<TD>" + fromUser + "</TD>");
          out.println("<TD>" + message + "</TD>");
          out.println("<TD>" + messageDate + "</TD>");
          out.println(
              "<TD><input type='checkbox' name='msgList' value='" + messageID + "'> Delete</TD>");
          out.println("</TR>");
        }

        out.println("<TR>");
        out.println(
            "<TD COLSPAN='6' ALIGN='center'><input type='submit' value='Delete Selected Contacts'></TD>");
        out.println("</TR>");

        out.println("</TABLE>");
        out.println("</FORM>");
      } catch (Exception e) {
        out.println("Could not connect to the users database.<P>");
        out.println("The error message was");
        out.println("<PRE>");
        out.println(e.getMessage());
        out.println("</PRE>");
      } finally {
        if (rs != null) {
          try {
            rs.close();
          } catch (SQLException ignore) {
          }
        }
        if (stmt != null) {
          try {
            stmt.close();
          } catch (SQLException ignore) {
          }
        }
        if (con != null) {
          try {
            con.close();
          } catch (SQLException ignore) {
          }
        }
      }

      out.println("</CENTER>");
      out.println("</BODY>");
      out.println("</HTML>");

    } catch (RuntimeException e) {
      out.println("<script language=\"javascript\">");
      out.println("alert(\"You need to log in to use this service!\");");
      out.println("</script>");

      out.println("<a href='index.html'>Click Here</a> to go to the main page.<br><br>");

      out.println(
          "Or Click on the button to exit<FORM><INPUT onClick=\"javascipt:window.close()\" TYPE=\"BUTTON\" VALUE=\"Close Browser\" TITLE=\"Click here to close window\" NAME=\"CloseWindow\" STYLE=\"font-family:Verdana, Arial, Helvetica; font-size:smaller; font-weight:bold\"></FORM>");

      log(e.getMessage());
      return;
    }
  }
예제 #28
0
  /**
   * Saves the tags in this dataType to the file argument. It will be saved as
   * TagConstants.MP3_FILE_SAVE_WRITE
   *
   * @param fileToSave file to save the this dataTypes tags to
   * @throws FileNotFoundException if unable to find file
   * @throws IOException on any I/O error
   */
  public void save(File fileToSave) throws IOException {
    // Ensure we are dealing with absolute filepaths not relative ones
    File file = fileToSave.getAbsoluteFile();

    logger.config("Saving  : " + file.getPath());

    // Checks before starting write
    precheck(file);

    RandomAccessFile rfile = null;
    try {
      // ID3v2 Tag
      if (TagOptionSingleton.getInstance().isId3v2Save()) {
        if (id3v2tag == null) {
          rfile = new RandomAccessFile(file, "rw");
          (new ID3v24Tag()).delete(rfile);
          (new ID3v23Tag()).delete(rfile);
          (new ID3v22Tag()).delete(rfile);
          logger.config("Deleting ID3v2 tag:" + file.getName());
          rfile.close();
        } else {
          logger.config("Writing ID3v2 tag:" + file.getName());
          final MP3AudioHeader mp3AudioHeader = (MP3AudioHeader) this.getAudioHeader();
          final long mp3StartByte = mp3AudioHeader.getMp3StartByte();
          final long newMp3StartByte = id3v2tag.write(file, mp3StartByte);
          if (mp3StartByte != newMp3StartByte) {
            logger.config("New mp3 start byte: " + newMp3StartByte);
            mp3AudioHeader.setMp3StartByte(newMp3StartByte);
          }
        }
      }
      rfile = new RandomAccessFile(file, "rw");

      // Lyrics 3 Tag
      if (TagOptionSingleton.getInstance().isLyrics3Save()) {
        if (lyrics3tag != null) {
          lyrics3tag.write(rfile);
        }
      }
      // ID3v1 tag
      if (TagOptionSingleton.getInstance().isId3v1Save()) {
        logger.config("Processing ID3v1");
        if (id3v1tag == null) {
          logger.config("Deleting ID3v1");
          (new ID3v1Tag()).delete(rfile);
        } else {
          logger.config("Saving ID3v1");
          id3v1tag.write(rfile);
        }
      }
    } catch (FileNotFoundException ex) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE_FILE_NOT_FOUND.getMsg(file.getName()),
          ex);
      throw ex;
    } catch (IOException iex) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(file.getName(), iex.getMessage()),
          iex);
      throw iex;
    } catch (RuntimeException re) {
      logger.log(
          Level.SEVERE,
          ErrorMessage.GENERAL_WRITE_FAILED_BECAUSE.getMsg(file.getName(), re.getMessage()),
          re);
      throw re;
    } finally {
      if (rfile != null) {
        rfile.close();
      }
    }
  }
예제 #29
0
파일: Cache.java 프로젝트: Calc86/ipartner
  /**
   * @param path
   * @param t
   * @return
   */
  public List<?> getList(String path, java.lang.reflect.Type t) {
    Log.d(TAG, "get list " + path); // NON-NLS

    File f = new File(getFullCachePath(path));
    if (!f.exists()) {
      Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS
      return null;
    }

    List<?> list;
    try {
      StringBuffer fileData = new StringBuffer();
      BufferedReader reader = new BufferedReader(new FileReader(f));
      char[] buf = new char[1024];
      int numRead = 0;
      while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
      }
      reader.close();
      String json = fileData.toString();
      Log.d(TAG, "cache: " + json); // NON-NLS

      list = gson.fromJson(json, t);
    } catch (FileNotFoundException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (StreamCorruptedException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (IOException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (JsonSyntaxException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (IllegalArgumentException e) {
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (RuntimeException e) {
      // не позволим кэшу убить нашу программу
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    } catch (Exception e) {
      // не позволим кэшу убить нашу программу
      Log.w(TAG, e.getMessage());
      e.printStackTrace();
      absoluteDelete(path);
      return null;
    }

    return list;
  }
예제 #30
0
  // given EntriesItem
  private void getWithEntriesItem(
      Word w,
      MorphItem mi,
      String stem,
      String pred,
      String targetPred,
      String targetRel,
      EntriesItem item,
      MacroAdder macAdder,
      Map<String, Double> supertags,
      Set<String> supertagsFound,
      SignHash result) {
    // ensure apropos
    if (targetPred != null && !targetPred.equals(pred)) return;
    if (targetRel != null
        && !targetRel.equals(item.getIndexRel())
        && !targetRel.equals(item.getCoartRel())) return;
    if (!item.getActive().booleanValue()) return;
    if (mi.excluded(item)) return;

    try {
      // copy and add macros
      Category cat = item.getCat().copy();
      macAdder.addMacros(cat);

      // replace DEFAULT_VAL with pred, after first
      // unifying type of associated nom var(s) with sem class
      unifySemClass(cat, mi.getWord().getSemClass());
      REPLACEMENT = pred;
      cat.deepMap(defaultReplacer);

      // check supertag
      // TODO: think about earlier checks for efficiency, for grammars where macros and preds don't
      // matter
      // Double lexprob = null; // nb: skipping lex log probs, don't seem to be helpful
      if (supertags != null) {
        // skip if not found
        String stag = cat.getSupertag();
        if (!supertags.containsKey(stag)) return;
        // otherwise update found supertags
        supertagsFound.add(stag);
        // get lex prob
        // lexprob = supertags.get(stag);
      }

      // propagate types of nom vars
      propagateTypes(cat);

      // handle distrib attrs and inherits-from
      propagateDistributiveAttrs(cat);
      expandInheritsFrom(cat);

      // merge stem, pos, sem class from morph item, plus supertag from cat
      Word word = Word.createFullWord(w, mi.getWord(), cat.getSupertag());

      // set origin and lexprob
      Sign sign = new Sign(word, cat);
      sign.setOrigin();
      // if (lexprob != null) {
      //	sign.addData(new SupertaggerAdapter.LexLogProb((float) Math.log10(lexprob)));
      // }
      // return sign
      result.insert(sign);
    } catch (RuntimeException exc) {
      System.err.println(
          "Warning: ignoring entry: "
              + item.getName()
              + " of family: "
              + item.getFamilyName()
              + " for stem: "
              + stem
              + " b/c: "
              + exc.toString());
    }
  }