Ejemplo n.º 1
0
  /**
   * Delete a student from the database. Also deletes the student's folders. Throws
   * InvalidDBRequestException if any error in database connection.
   *
   * @param username student's user name
   * @throws InvalidDBRequestException
   */
  private void purgeStudent(String username) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete from scores
      count = stmt.executeUpdate("delete from scores where user_login = '******'");

      // delete from student
      count = stmt.executeUpdate("delete from student where login = '******'");

      // delete student's folder
      File studentDir = new File("./StudentQuizzes/" + username);
      if (!(studentDir.delete())) {
        System.err.println("Error in deleting folder for student: " + username);
      }

      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }
Ejemplo n.º 2
0
  public boolean logEvent(
      final IClient client, final String eventText, final InputStream logFileStream) {
    Integer id =
        executeWithConnection(
            new ConnectionExecuteFunction<Integer>() {
              public Integer execute(Connection c) throws SQLException {
                return logEvent(client, eventText, logFileStream, c);
              }
            });

    if (id == null) {
      // DB error would have already been logged.
      return false;
    }

    boolean ok = false;
    if (logFileStream == null) {
      ok = true;
    } else {
      File userMailDir = client.getUserMailbox().getBaseDir();
      File logFile = getEventLogFile(userMailDir, id.intValue());
      try {
        FileUtils.copyStreamToFile(logFileStream, logFile);
        ok = true;
      } catch (IOException ioe) {
        m_logger
            .log("Can't write log file")
            .param(LoggingConsts.USER_ID, client.getUserId())
            .param(LoggingConsts.FILENAME, logFile == null ? "" : logFile.getAbsolutePath())
            .param(LoggingConsts.CONTENT, eventText)
            .error(ioe);
      }
    }
    return ok;
  }
Ejemplo n.º 3
0
  public static String getDbConfig(String field) {
    String value = "";
    try {
      File directory = new File(".");
      String path = directory.getCanonicalPath();
      String s = File.separator;
      FileInputStream fstream =
          new FileInputStream(path + s + "src" + s + "config" + s + "dbconfig.cfg");

      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;

      while ((strLine = br.readLine()) != null) {
        if (strLine.indexOf("password") >= 0 && field.equals("password") == true) {
          value = strLine.substring(strLine.indexOf('\t') + 1);
          break;
        }

        if (strLine.indexOf("username") >= 0 && field.equals("username") == true) {
          value = strLine.substring(strLine.indexOf('\t') + 1);
        }
      }

    } catch (IOException e) {
      JOptionPane.showMessageDialog(null, e);
    }

    return value;
  }
Ejemplo n.º 4
0
 static void genclass(DelegatorGenerator dg, Class intfcl, String fqcn, File srcroot)
     throws IOException {
   File genDir = new File(srcroot, dirForFqcn(fqcn));
   if (!genDir.exists()) {
     System.err.println(
         JdbcProxyGenerator.class.getName()
             + " -- creating directory: "
             + genDir.getAbsolutePath());
     genDir.mkdirs();
   }
   String fileName = CodegenUtils.fqcnLastElement(fqcn) + ".java";
   Writer w = null;
   try {
     w = new BufferedWriter(new FileWriter(new File(genDir, fileName)));
     dg.writeDelegator(intfcl, fqcn, w);
     w.flush();
     System.err.println("Generated " + fileName);
   } finally {
     try {
       if (w != null) w.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
  /* use badsource and badsink */
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data = bad_source(request, response);

    /* POTENTIAL FLAW: unvalidated or sandboxed value */
    File fIn = new File(data);
    if (fIn.exists() && fIn.isFile()) {
      IO.writeLine(new BufferedReader(new FileReader(fIn)).readLine());
    }
  }
 // Fireup tomcat and register this servlet
 public static void main(String[] args) throws LifecycleException, SQLException {
   Tomcat tomcat = new Tomcat();
   tomcat.setPort(8080);
   File base = new File(System.getProperty("java.io.tmpdir"));
   Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
   Tomcat.addServlet(rootCtx, "log", new LogService());
   rootCtx.addServletMapping("/*", "log");
   tomcat.start();
   tomcat.getServer().await();
 }
Ejemplo n.º 7
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    HttpSession session = request.getSession();
    request.setCharacterEncoding("UTF-8");

    BufferedInputStream fileIn = new BufferedInputStream(request.getInputStream());
    String fn = request.getParameter("fileName");
    byte[] buf = new byte[1024];
    File file = new File("/var/www/uploadres/" + session.getAttribute("username") + fn);
    BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file));
    while (true) {
      int bytesIn = fileIn.read(buf, 0, 1024);
      if (bytesIn == -1) break;
      else fileOut.write(buf, 0, bytesIn);
    }

    fileOut.flush();
    fileOut.close();
    System.out.println(file.getAbsolutePath());

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      try {
        Connection conn = DriverManager.getConnection(url, user, pwd);
        Statement stmt = conn.createStatement();
        String sql =
            "UPDATE Users SET photo = '"
                + file.getName()
                + "' WHERE username='******'";
        stmt.execute(sql);
        //				PreparedStatement pstmt = conn.prepareStatement("UPDATE Users SET photo = ? WHERE
        // username='******'");
        //				InputStream inp = new BufferedInputStream(new FileInputStream(file));
        //				pstmt.setBinaryStream(1, inp, (int)file.length());
        //				pstmt.executeUpdate();
        System.out.println("OK");
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 8
0
  public static void addToResultsFile(
      String executingDatabaseName,
      long runTime,
      long rowsLoaded,
      long rowsLoadedPerSecond,
      File resultsFile) {

    boolean resultsFileCreated = false;

    try {
      if (!resultsFile.exists()) {

        resultsFileCreated = resultsFile.createNewFile();
      }

      OutputStream resultsFileStream = new FileOutputStream(resultsFile, true);

      if (resultsFileCreated) {
        // Write header lines.

        String header =
            "timeOfTest, runTime, databaseBeingTested, rowsLoaded, rowsLoadedPerSecond, hotStart, config, replicas"
                + "\n";

        resultsFileStream.write(header.getBytes());
      }

      String results =
          startDate.getTime()
              + ", "
              + runTime
              + ", "
              + executingDatabaseName
              + ", "
              + rowsLoaded
              + ", "
              + rowsLoadedPerSecond
              + ", "
              + hotStart
              + ", "
              + configInfo
              + ", "
              + numberOfReplicas
              + "\n";
      resultsFileStream.write(results.getBytes());

      resultsFileStream.flush();

      resultsFileStream.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 9
0
 public static void setIconImage(JFrame jf) {
   File directory = new File(".");
   try {
     String path = directory.getCanonicalPath();
     String s = File.separator;
     jf.setIconImage(
         Toolkit.getDefaultToolkit().getImage(path + s + "src" + s + "images" + s + "logo.gif"));
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, "Unexpected Error. Exiting application");
   }
 }
Ejemplo n.º 10
0
  /**
   * �õ�ϵͳ���õ��ϴ��ļ�����·��
   *
   * @return String
   */
  public static String getPath(String loadPath) {
    String path = PropertiesReader.GetProptery(loadPath);
    if (path == null || "".equals(path)) {
      throw new java.lang.IllegalStateException("�ϴ��ļ��ı���·��û�����á�" + loadPath + "=?");
    }

    File file = new File(path);
    if (!file.isDirectory()) {
      file.mkdirs();
    }
    return path;
  }
Ejemplo n.º 11
0
 /**
  * Creates and returns an InputStream from the file path / http location given.
  *
  * @throws DataServiceFault
  * @see InputStream
  */
 public static InputStream getInputStreamFromPath(String path)
     throws IOException, DataServiceFault {
   InputStream ins;
   if (path.startsWith("http://")) {
     /* This is a url file path */
     URL url = new URL(path);
     ins = url.openStream();
   } else if (isRegistryPath(path)) {
     try {
       RegistryService registryService = DataServicesDSComponent.getRegistryService();
       if (registryService == null) {
         throw new DataServiceFault(
             "DBUtils.getInputStreamFromPath(): Registry service is not available");
       }
       Registry registry;
       if (path.startsWith(DBConstants.CONF_REGISTRY_PATH_PREFIX)) {
         if (path.length() > DBConstants.CONF_REGISTRY_PATH_PREFIX.length()) {
           path = path.substring(DBConstants.CONF_REGISTRY_PATH_PREFIX.length());
           registry = registryService.getConfigSystemRegistry(getCurrentTenantId());
         } else {
           throw new DataServiceFault("Empty configuration registry path given");
         }
       } else {
         if (path.length() > DBConstants.GOV_REGISTRY_PATH_PREFIX.length()) {
           path = path.substring(DBConstants.GOV_REGISTRY_PATH_PREFIX.length());
           registry = registryService.getGovernanceSystemRegistry(getCurrentTenantId());
         } else {
           throw new DataServiceFault("Empty governance registry path given");
         }
       }
       if (registry.resourceExists(path)) {
         Resource serviceResource = registry.get(path);
         ins = serviceResource.getContentStream();
       } else {
         throw new DataServiceFault(
             "The given XSLT resource path at '" + path + "' does not exist");
       }
     } catch (RegistryException e) {
       String msg = "Error in retrieving the resource: " + path;
       log.error(msg, e);
       throw new DataServiceFault(e, msg);
     }
   } else {
     File csvFile = new File(path);
     if (path.startsWith("." + File.separator) || path.startsWith(".." + File.separator)) {
       /* this is a relative path */
       path = csvFile.getAbsolutePath();
     }
     /* local file */
     ins = new FileInputStream(path);
   }
   return ins;
 }
 public static void main(String[] args) throws SQLException {
   // declare a connection by using Connection interface
   Connection connection = null;
   /* Create string of connection url within specified format with machine
   name, port number and database name. Here machine name id localhost
   and database name is mahendra. */
   String connectionURL = "jdbc:mysql://localhost:3306/mahendra";
   /*declare a resultSet that works as a table resulted by execute a specified
   sql query. */
   ResultSet rs = null;
   // Declare prepare statement.
   PreparedStatement psmnt = null;
   // declare FileInputStream object to store binary stream of given image.
   FileInputStream fis;
   try {
     // Load JDBC driver "com.mysql.jdbc.Driver"
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     /* Create a connection by using getConnection() method that takes
     parameters of string type connection url, user name and password to
     connect to database. */
     connection = DriverManager.getConnection(connectionURL, "root", "root");
     // create a file object for image by specifying full path of image as parameter.
     File image = new File("C:/image.jpg");
     /* prepareStatement() is used for create statement object that is
     used for sending sql statements to the specified database. */
     psmnt =
         connection.prepareStatement(
             "insert into save_image(name, city, image, Phone) " + "values(?,?,?,?)");
     psmnt.setString(1, "mahendra");
     psmnt.setString(2, "Delhi");
     psmnt.setString(4, "123456");
     fis = new FileInputStream(image);
     psmnt.setBinaryStream(3, (InputStream) fis, (int) (image.length()));
     /* executeUpdate() method execute specified sql query. Here this query
     insert data and image from specified address. */
     int s = psmnt.executeUpdate();
     if (s > 0) {
       System.out.println("Uploaded successfully !");
     } else {
       System.out.println("unsucessfull to upload image.");
     }
   } // catch if found any exception during rum time.
   catch (Exception ex) {
     System.out.println("Found some error : " + ex);
   } finally {
     // close all the connections.
     connection.close();
     psmnt.close();
   }
 }
Ejemplo n.º 13
0
 /**
  * Takes a line and looks for an archive group tag. If one is found, the information from the tag
  * is returned as an <CODE>ArchiveGroup</CODE>. If a tag is found, the data in the tag is stored
  * in the <CODE>HashMap</CODE> provided.
  *
  * @param currentLine The line in which to look for the archive tag.
  * @param template The <CODE>Template</CODE> to which the <CODE>ArchiveGroup</CODE> belongs.
  * @return The archive request tag data as an instance of <CODE>ArchiveGroup</CODE>, <CODE>null
  *     </CODE> if the line passed in does not contain an arFile tag.
  */
 private ArchiveGroup parseArchiveGroupTag(String currentLine, Template template) {
   ArchiveGroup archiveTag;
   Matcher currentMatcher = archiveRequestPattern.matcher(currentLine);
   if (currentMatcher.find()) {
     String fileName = currentMatcher.group(1);
     archiveTag = template.getArchiveGroup(fileName);
     if (archiveTag == null) {
       File groupFile = new File(fileName);
       archiveTag = new ArchiveGroup(groupFile.getParent(), groupFile.getName());
       template.addArchiveGroup(archiveTag);
     }
   } else archiveTag = null;
   return archiveTag;
 }
Ejemplo n.º 14
0
 /**
  * If 'file' exists, attempt to delete it. Logs, but doesn't throw upon failure.
  *
  * @param file
  * @param userId only for logging.
  */
 private void deleteFileIfNeeded(File file, int userId) {
   if (file.exists()) {
     boolean ok = file.delete();
     if (!ok) {
       // This is a problem because it may delay informing a client to leave
       // activation.
       LogMessageGen lmg = new LogMessageGen();
       lmg.setSubject("Unable to delete file");
       lmg.param(LoggingConsts.USER_ID, userId);
       lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath());
       m_logCategory.error(lmg.toString());
     }
   }
 }
Ejemplo n.º 15
0
  // Logs a new entry in the library RSS file
  public static synchronized void addRSSEntry(
      String title, String link, String description, File rssFile) {
    // File rssFile=new File("nofile.xml");

    try {
      System.out.println("Looking for RSS file: " + rssFile.getCanonicalPath());
      if (rssFile.exists()) {

        SAXReader reader = new SAXReader();
        Document document = reader.read(rssFile);
        Element root = document.getRootElement();
        Element channel = root.element("channel");
        List items = channel.elements("item");
        int numItems = items.size();
        items = null;
        if (numItems > 9) {
          Element removeThisItem = channel.element("item");
          channel.remove(removeThisItem);
        }

        Element newItem = channel.addElement("item");
        Element newTitle = newItem.addElement("title");
        Element newLink = newItem.addElement("link");
        Element newDescription = newItem.addElement("description");
        newTitle.setText(title);
        newDescription.setText(description);
        newLink.setText(link);

        Element pubDate = channel.element("pubDate");
        pubDate.setText((new java.util.Date()).toString());

        // now save changes
        FileWriter mywriter = new FileWriter(rssFile);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLWriter writer = new XMLWriter(mywriter, format);
        writer.write(document);
        writer.close();
      }
    } catch (IOException ioe) {
      System.out.println("ERROR: Could not find the RSS file.");
      ioe.printStackTrace();
    } catch (DocumentException de) {
      System.out.println("ERROR: Could not read the RSS file.");
      de.printStackTrace();
    } catch (Exception e) {
      System.out.println("Unknown exception trying to add an entry to the RSS file.");
      e.printStackTrace();
    }
  }
Ejemplo n.º 16
0
  public static File findResourceOnFileSystem(String resourceName) {
    File resourceFile = null;

    URL resourceURL = ServletUtilities.class.getClassLoader().getResource(resourceName);
    if (resourceURL != null) {
      String resourcePath = resourceURL.getPath();
      if (resourcePath != null) {
        File tmp = new File(resourcePath);
        if (tmp.exists()) {
          resourceFile = tmp;
        }
      }
    }
    return resourceFile;
  }
Ejemplo n.º 17
0
 public static String[] get_filelist(String path, boolean nodirs, boolean nofiles) {
   File folder = new File(path);
   if (folder.isDirectory()) {
     File[] listOfFiles = folder.listFiles();
     java.util.Vector<String> r = new java.util.Vector<String>();
     for (int i = 0; listOfFiles != null && i < listOfFiles.length; i++) {
       if ((listOfFiles[i].isFile() && !nofiles) || (listOfFiles[i].isDirectory() && !nodirs)) {
         r.add(listOfFiles[i].getName());
       }
     }
     return r.toArray(new String[0]);
   } else {
     return null; // A: no existe o no es directorio
   }
 }
Ejemplo n.º 18
0
  public static void main(String argv[]) {
    Connection con = null;
    PreparedStatement pstmt = null;
    InputStream fin = null;
    String url = "jdbc:oracle:thin:@localhost:1521:XE";
    String userid = "hr1";
    String passwd = "123456";
    String picName[] = {"iconPet29.jpg", "iconPet30.png"};
    int[] picPetId = {29, 30};
    int rowsUpdated = 0;
    try {
      con = DriverManager.getConnection(url, userid, passwd);

      for (int i = 0; i < picName.length; i++) {
        File pic = new File("WebContent/images", picName[i]); // �۹���|- picFrom
        // ������|- Ĵ�p:
        // File pic = new File("x:\\aa\\bb\\picFrom", picName);
        long flen = pic.length();
        fin = new FileInputStream(pic);
        pstmt = con.prepareStatement("UPDATE PET SET icon = ? WHERE ID = ?");
        pstmt.setBinaryStream(1, fin, (int) flen); // void
        // pstmt.setBinaryStream(int
        // parameterIndex,
        // InputStream x,
        // int length)
        // throws
        // SQLException
        pstmt.setInt(2, picPetId[i]);
        rowsUpdated += pstmt.executeUpdate();
      }

      System.out.print("Changed " + rowsUpdated);

      if (1 == rowsUpdated) System.out.println(" row.");
      else System.out.println(" rows.");

      fin.close();
      pstmt.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
      }
    }
  }
 public static void init() throws Exception {
   Properties props = new Properties();
   int pid = OSProcess.getId();
   String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
   /** * Return file as string and then modify the string accordingly ** */
   String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
   file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
   String modified_file_str = modifyFile(file_as_str);
   FileOutputStream fos = new FileOutputStream(path);
   BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
   wr.write(modified_file_str);
   wr.flush();
   wr.close();
   props.setProperty("cache-xml-file", path);
   //    String tableName = "";
   //		  props.setProperty("mcast-port", "10339");
   try {
     //			   ds = DistributedSystem.connect(props);
     ds = (new ExceptionsDUnitTest("temp")).getSystem(props);
     cache = CacheFactory.create(ds);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new Exception("" + e);
   }
 }
Ejemplo n.º 20
0
 private static void createContactDir(String strContact) {
   File dirCurrent = new File(strDestVMDir + strContact);
   if (!dirCurrent.exists()) {
     try {
       boolean success = (dirCurrent).mkdir();
       if (!success) {
         throw new Exception("Well that wasn't planned for...");
       }
     } catch (Exception e) {
       System.err.println(e.getLocalizedMessage());
       System.err.println();
       System.err.println(e.getStackTrace());
       System.exit(0);
     }
   }
 }
Ejemplo n.º 21
0
  public SeatInfo() {
    File file = new File(".", "data");
    file.mkdir();
    File f = new File(file, "SeatInfo.txt");

    try {
      raf = new RandomAccessFile(f, "rw");

      if (raf.length() == 0) {
        raf.setLength(31 * 4 * FLIGHT_PER_DAY);
        for (int i = 0; i < 31 * FLIGHT_PER_DAY; i++) raf.writeInt(0);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * Unpacks file into temporary directory
   *
   * @param inputStream InputStream representing archive file
   * @param originalFileName Name of the archive
   * @return Directory to which the archive was unpacked
   * @throws IOException
   * @throws ZipException
   */
  private File unpackArchive(InputStream inputStream, String originalFileName)
      throws IOException, ZipException {
    String randomDirectoryName = RandomStringUtils.randomAlphanumeric(8);
    File directoryForUnpacking =
        FileUtils.getFile(FileUtils.getTempDirectoryPath(), randomDirectoryName);
    FileUtils.forceMkdir(directoryForUnpacking);
    File zipFileDownloaded = FileUtils.getFile(FileUtils.getTempDirectoryPath(), originalFileName);

    try (OutputStream os = new FileOutputStream(zipFileDownloaded)) {
      IOUtils.copy(inputStream, os);
    }

    ZipFile zipFile = new ZipFile(zipFileDownloaded);
    zipFile.extractAll(directoryForUnpacking.toString());
    FileUtils.forceDelete(zipFileDownloaded);
    return directoryForUnpacking;
  }
Ejemplo n.º 23
0
  public CacheFileNames getCacheFileNames(final UserAccount user) {

    SecureHashKeyResult toRet =
        executeWithConnection(
            new ConnectionExecuteFunction<SecureHashKeyResult>() {
              public SecureHashKeyResult execute(Connection c) throws SQLException {
                return getSecureHashKey(user, c);
              }
            });

    if (toRet == null) {
      // A DB error should have been logged.
      return null;
    }

    // EMSDEV-7854.  Signal file manipulation is done outside of a DB transaction.
    String stateFile = null;
    String newmailFile = null;
    ClientHashSupport hash = null;
    byte[] key = toRet.getKey();
    if (key != null) {
      hash = new ClientHashSupport();
      hash.setCustomerId(user.getCustomerID());
      hash.setHashKey(key);
      hash.setUserId(user.getUserID());
      hash.getStateCachePath();
      hash.setLastActivationId(user.getLastActivationId());

      // Lines below don't hit the spindle.
      File stateFileF = new File(getCacheBase(), hash.getStateCachePath());
      stateFile = stateFileF.getAbsolutePath();

      File newmailFileF = new File(getCacheBase(), hash.getNewMailCachePath());
      newmailFile = newmailFileF.getAbsolutePath();

      if (toRet.isJustCreated()) {
        // If Webmail doesn't find the signal file, it polls the database,
        // so ensure the files are there.
        updateSignalFiles(hash, user.getUserState(), user.isDeleted());
      }
    }
    return new CacheFileNames(stateFile, newmailFile);
  }
Ejemplo n.º 24
0
 /*
  * �������µ��ļ�·���ַ�
  */
 private static String getAbstractPath(String path) {
   Calendar cl = Calendar.getInstance();
   int year = cl.get(Calendar.YEAR);
   int month = cl.get(Calendar.MONTH);
   StringBuffer buffer = new StringBuffer();
   buffer.append(year);
   buffer.append("/");
   month++;
   if (month < 10) {
     buffer.append(0);
   }
   buffer.append(month);
   buffer.append("/");
   File renameTo = new File(path + buffer.toString());
   if (!renameTo.isDirectory()) {
     renameTo.mkdirs();
   }
   return buffer.toString();
 }
Ejemplo n.º 25
0
  public String execute() {
    HttpSession session = ServletActionContext.getRequest().getSession();
    if (photo == null) return "setinfo";
    String uploadPath = "/var/www/uploadres";
    String photoName = session.getAttribute("username") + this.getPhotoFileName();
    File toPhotoFile = new File(new File(uploadPath), photoName);

    if (!toPhotoFile.getParentFile().exists()) toPhotoFile.getParentFile().mkdirs();
    try {
      FileUtils.copyFile(photo, toPhotoFile);
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        try {
          Connection conn = DriverManager.getConnection(url, user, pwd);
          Statement stmt = conn.createStatement();
          String sql =
              "UPDATE Users SET photo = '"
                  + photoName
                  + "' WHERE username='******'";
          stmt.execute(sql);
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return "setinfo";
  }
Ejemplo n.º 26
0
  /**
   * Private method to delete a visualization script file of a quiz taken by a student.
   *
   * @param uniqueId a unique number of that indicates the instance of the quiz taking in the
   *     database
   * @param studentName student's user name
   * @param testName quiz name
   */
  private void deleteVisualization(String uniqueId, String studentName, String testName) {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();

      // get quiz visulization type
      ResultSet rs =
          stmt.executeQuery("select visual_type from test where name = '" + testName + "'");
      // construct the quiz vizualisation file name
      String visFileName =
          new String("./StudentQuizzes/" + studentName + "/" + testName + uniqueId);
      if (rs.next())
        if (rs.getString(1).trim().equalsIgnoreCase("gaigs")) visFileName = visFileName + ".sho";
        else if (rs.getString(1).trim().equalsIgnoreCase("samba"))
          visFileName = visFileName + ".sam";
        else if (rs.getString(1).trim().equalsIgnoreCase("animal"))
          visFileName = visFileName + ".ani";
        else {
          System.err.println("visualization type unknown for quiz: " + rs.getString(3) + "\n");
        }
      else {
        System.err.println("Visulization type not found for quiz: " + rs.getString(3) + "\n");
      }

      // delete the file
      File visFile = new File(visFileName);
      if (debug) System.out.println("deleting " + visFileName);
      if (visFile.exists())
        if (!visFile.delete()) System.err.println("can't delete the visualization file");

      rs.close();
      stmt.close();
      db.close();
    } catch (Exception e) {
      System.err.println("Execption thrown from deleteVisualisation: " + e.getMessage());
    }
  }
Ejemplo n.º 27
0
  public static void main(String[] args) throws Exception {

    File f = new File(inputFile);
    if (f.exists()) {
      Scanner input = new Scanner(f);
      String credentials = input.nextLine();
      input.close();
      String uname = credentials.split(",")[0].split("=")[1];
      String pword = credentials.split(",")[1].split("=")[1];

      con = connectToDb(uname, pword);
      if (con != null) {
        System.out.println("Connected to Database:" + con);
        loadData(uname, pword);
        task1();
        task2();
        task3();
        task4();
        con.close();
      } else System.out.println("Connection Error");
    } else System.out.println("Input file system.in not found");
  }
Ejemplo n.º 28
0
  public ClientSession getClientSession(String activationToken) {
    if (!StringUtils.hasValue(activationToken)) {
      m_logCategory.warn("activationToken is required");
      return null;
    }

    File file = getSessionFile(activationToken);
    if (!file.exists()) {
      // Can't assume it's an authentication problem -- session file is removed
      // during active->recovery transition.
      // If this occurs, the client gets a 401 and will call into 'transition' or 'checkin'.
      LogMessageGen lmg = new LogMessageGen();
      lmg.setSubject("Session file not found");
      lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath());
      m_logCategory.info(lmg.toString());
      return null;
    }
    try {
      ClientSession clientSession = null;
      clientSession = new ClientSession();
      clientSession.read(file);
      clientSession.setActivationToken(activationToken);
      return clientSession;
    } catch (IOException ioe) {
      // Possible if the state file was removed after the file.exists() above,
      // or some other problem.
      // info, not warning because a client could ask for this file right when
      // the session is being removed.  The client will then do a 'checkin',
      // same as described above.
      LogMessageGen lmg = new LogMessageGen();
      lmg.setSubject("Unable to read session file");
      lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath());
      m_logCategory.info(lmg.toString(), ioe);
    }
    return null;
  }
Ejemplo n.º 29
0
 /**
  * Doesn't write the file atomically. Logs, but doesn't throw upon failure.
  *
  * @param file can't be null.
  * @param userId only for logging.
  * @param content
  * @param errorLevel if true log an error level message; otherwise warning level.
  */
 private void touchFile(File file, byte[] content, int userId, boolean errorLevel) {
   OutputStream out = null;
   try {
     file.getParentFile().mkdirs();
     out = new FileOutputStream(file);
     out.write(content);
     out.close();
     out = null;
   } catch (IOException ioe) {
     LogMessageGen lmg = new LogMessageGen();
     lmg.setSubject("Unable to touch cache file");
     lmg.param(LoggingConsts.USER_ID, userId);
     lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath());
     lmg.param(LoggingConsts.CONTENT, content);
     if (errorLevel) {
       m_logCategory.error(lmg.toString(), ioe);
     } else {
       m_logCategory.warn(lmg.toString(), ioe);
     }
   } finally {
     // normally closed above; just for leak prevention.
     IOUtils.safeClose(out, false, m_logCategory);
   }
 }
Ejemplo n.º 30
0
  private static void writeResultToResultsFile(
      String logFileLocation,
      String executingDatabaseName,
      long runTime,
      long rowsLoaded,
      long rowsLoadedPerSecond) {
    String resultsFolderPath =
        logFileLocation + "benchmark-results" + File.separator + "load-data-summary";

    // Create folder if it doesn't exist.
    File resultsFolder = new File(resultsFolderPath);
    resultsFolder.mkdirs();

    // Add results to a CSV file for a single database, and to a generic file for all database
    // results.
    File specificDbResultsFile =
        new File(resultsFolderPath + File.separator + executingDatabaseName + ".csv");
    addToResultsFile(
        executingDatabaseName, runTime, rowsLoaded, rowsLoadedPerSecond, specificDbResultsFile);

    File genericResultsFile = new File(resultsFolderPath + File.separator + "all.csv");
    addToResultsFile(
        executingDatabaseName, runTime, rowsLoaded, rowsLoadedPerSecond, genericResultsFile);
  }