Example #1
0
    private void getFileList() {
      myMessage.stateChanged("REMOTEFILELIST");
      URL theURL = null;
      ;
      try {
        theURL = new URL(myProperties.getProperty("BASEURL"));
      } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      ;

      String theRemoteBaseDir = myProperties.getProperty("REMOTEBASEDIR");
      Properties props = System.getProperties();
      props.put("http.proxyHost", myProperties.getProperty("PROXYHOST"));
      props.put("http.proxyPort", myProperties.getProperty("PROXYPORT"));
      String data = "";
      try {
        data =
            URLEncoder.encode("filelocation", "UTF-8")
                + "="
                + URLEncoder.encode(theRemoteBaseDir, "UTF-8");
        data +=
            "&"
                + URLEncoder.encode("fileprocess", "UTF-8")
                + "="
                + URLEncoder.encode("REMOTEFILELIST", "UTF-8");

        URLConnection conn = theURL.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        myMessage.messageChanged(0, "Get the File List");
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line2;
        myFileList = new HashMap<String, List>();
        while (((line2 = rd.readLine()) != null) && !isCancelled()) {
          CSV parser = new CSV('|');
          List theFileList = parser.parse(line2);
          // myFileList.put((String)theFileList.get(1), theFileList);
          for (int i = 0; i < theFileList.size(); i++) {
            if (i == 1) {
              myFileList.put((String) theFileList.get(i), theFileList);
            }
          }
        }
        rd.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Example #2
0
  private boolean hasADuplicateUsername(CSV studentGrades) {
    List usernameList = studentGrades.getStudentUsernames();
    List duplicatesList = new ArrayList();

    while (usernameList.size() > 0) {
      String username = (String) usernameList.get(0);
      usernameList.remove(username);
      if (usernameList.contains(username) && !duplicatesList.contains(username)) {
        duplicatesList.add(username);
      }
    }

    if (duplicatesList.size() <= 0) {
      return false;
    }

    if (duplicatesList.size() == 1) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "single_duplicate_username", new Object[] {});
    } else {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "mult_duplicate_usernames", new Object[] {});
    }

    for (int i = 0; i < duplicatesList.size(); i++) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "duplicate_username", new Object[] {duplicatesList.get(i)});
    }

    PostemTool.populateMessage(
        FacesMessage.SEVERITY_ERROR, "duplicate_username_dir", new Object[] {});

    return true;
  }
  /* (non-Javadoc)
   * @see org.nightlabs.jfire.geography.GeographyTemplateDataManagerRemote#storeGeographyTemplateDistrictData(org.nightlabs.jfire.geography.District)
   */
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  @RolesAllowed("_Guest_")
  public void storeGeographyTemplateDistrictData(final District storedDistrict)
      throws IOException, SecurityException {
    assertWritingAllowed();

    final PersistenceManager pm = createPersistenceManager();
    try {
      pm.getFetchPlan().setMaxFetchDepth(1);
      pm.getFetchPlan().setGroup(FetchPlan.ALL);

      // initialize:
      Geography.sharedInstance();

      String rootOrganisationID;

      try {
        final InitialContext initialContext = new InitialContext();
        try {
          rootOrganisationID = Organisation.getRootOrganisationID(initialContext);
        } // try
        finally {
          initialContext.close();
        } // finally
      } // try
      catch (final NamingException x) {
        throw new RuntimeException(
            x); // it's definitely an unexpected exception if we can't access the local JNDI.
      } // catch

      final CountryID countryID = CountryID.create(storedDistrict.getCountryID());

      final ByteArrayOutputStream out = new ByteArrayOutputStream();
      final Writer w = new OutputStreamWriter(new DeflaterOutputStream(out), IOUtil.CHARSET_UTF_8);
      try {
        w.write(DISTRICT_CSV_HEADER);
        // TODO: write all old data!
        if (storedDistrict != null) {
          final String csvLines = GeographyImplResourceCSV.district2csvLines(storedDistrict);

          if (logger.isDebugEnabled()) logger.debug(csvLines);

          //					csvLines.trim();
          w.write(csvLines);
        } // if
      } // try
      finally {
        w.close();
      } // finally

      CSV.setCSVData(
          pm, rootOrganisationID, CSV.CSV_TYPE_DISTRICT, countryID.countryID, out.toByteArray());

      clearCache();
    } // try
    finally {
      pm.close();
    } // finally
  }
Example #4
0
  public String processCsvDownload() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      return "permission_error";
    }
    Long currentGbId = ((Gradebook) gradebookTable.getRowData()).getId();
    currentGradebook = gradebookManager.getGradebookByIdWithHeadingsAndStudents(currentGbId);

    List csvContents = new ArrayList();
    if (currentGradebook.getHeadings().size() > 0) {
      csvContents.add(currentGradebook.getHeadings());
    }
    Iterator si = currentGradebook.getStudents().iterator();
    while (si.hasNext()) {
      List sgl = new ArrayList();
      StudentGrades sg = (StudentGrades) si.next();
      sgl.add(sg.getUsername());
      sgl.addAll(sg.getGrades());
      csvContents.add(sgl);
    }

    CSV newCsv = new CSV(csvContents, currentGradebook.getHeadings().size() > 0);

    this.csv = newCsv.getCsv();
    return "download_csv";
  }
Example #5
0
 public static void main(String[] args) {
   File file = new File(new File("").getAbsolutePath() + "\\src\\ch22_11\\in.csv");
   List<String[]> list;
   try {
     list = CSV.readCSVTable(new FileReader(file), 2);
     for (String[] strings : list) {
       for (String str : strings) {
         System.out.print(str + "\t");
       }
       System.out.println();
     }
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #6
0
  public String processCreate() {

    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      this.currentGradebook = null;
      this.csv = null;
      this.newTemplate = null;
      // this.release = null;
      return "permission_error";
    }
    if (currentGradebook.getId() == null) {
      ArrayList gb = getGradebooks();
      Iterator gi = gb.iterator();
      while (gi.hasNext()) {
        if (((Gradebook) gi.next()).getTitle().equals(currentGradebook.getTitle())) {
          // To stay consistent, remove current messages when adding a new message
          // so as to only display one error message before returning
          PostemTool.clearMessages();
          PostemTool.populateMessage(
              FacesMessage.SEVERITY_ERROR, "duplicate_title", new Object[] {});
          return "create_gradebook";
        }
      }
    }
    if (currentGradebook.getTitle() == null || currentGradebook.getTitle().equals("")) {
      // To stay consistent, remove current messages when adding a new message
      // so as to only display one error message before returning
      PostemTool.clearMessages();
      PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "missing_title", new Object[] {});
      return "create_gradebook";
    } else if (currentGradebook.getTitle().trim().length() > TITLE_MAX_LENGTH) {
      PostemTool.clearMessages();
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR,
          "title_too_long",
          new Object[] {
            new Integer(currentGradebook.getTitle().trim().length()), new Integer(TITLE_MAX_LENGTH)
          });
      return "create_gradebook";
    }

    Reference attachment = getAttachmentReference();
    if (attachment == null) {
      return "create_gradebook";
    }

    if (!this.delimiter.equals(COMMA_DELIM_STR) && !this.delimiter.equals(TAB_DELIM_STR)) {
      PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "invalid_delim", new Object[] {});
      return "create_gradebook";
    }

    if (attachment != null) {
      // logger.info("*** Non-Empty CSV!");
      try {

        char csv_delim = CSV.COMMA_DELIM;
        if (this.delimiter.equals(TAB_DELIM_STR)) {
          csv_delim = CSV.TAB_DELIM;
        }

        // Read the data

        ContentResource cr = contentHostingService.getResource(attachment.getId());
        // Check the type
        if (ResourceProperties.TYPE_URL.equalsIgnoreCase(cr.getContentType())) {
          // Going to need to read from a stream
          String csvURL = new String(cr.getContent());
          // Load the URL
          csv = URLConnectionReader.getText(csvURL);
          if (LOG.isDebugEnabled()) {
            LOG.debug(csv);
          }
        } else {
          csv = new String(cr.getContent());
          if (LOG.isDebugEnabled()) {
            LOG.debug(csv);
          }
        }
        CSV grades = new CSV(csv, withHeader, csv_delim);

        if (withHeader == true) {
          if (grades.getHeaders() != null) {

            List headingList = grades.getHeaders();
            for (int col = 0; col < headingList.size(); col++) {
              String heading = (String) headingList.get(col).toString().trim();
              // Make sure there are no blank headings
              if (heading == null || heading.equals("")) {
                PostemTool.populateMessage(
                    FacesMessage.SEVERITY_ERROR, "blank_headings", new Object[] {});
                return "create_gradebook";
              }
              // Make sure the headings don't exceed max limit
              if (heading.length() > HEADING_MAX_LENGTH) {
                PostemTool.populateMessage(
                    FacesMessage.SEVERITY_ERROR,
                    "heading_too_long",
                    new Object[] {new Integer(HEADING_MAX_LENGTH)});
                return "create_gradebook";
              }
            }
          }
        }

        if (grades.getStudents() != null) {
          if (!usernamesValid(grades)) {
            return "create_gradebook";
          }

          if (hasADuplicateUsername(grades)) {
            return "create_gradebook";
          }
        }

        if (this.newTemplate != null && this.newTemplate.trim().length() > 0) {
          if (this.newTemplate.trim().length() > TEMPLATE_MAX_LENGTH) {
            PostemTool.populateMessage(
                FacesMessage.SEVERITY_ERROR,
                "template_too_long",
                new Object[] {
                  new Integer(this.newTemplate.trim().length()), new Integer(TEMPLATE_MAX_LENGTH)
                });
            return "create_gradebook";
          }
        }

        if (withHeader == true) {
          if (grades.getHeaders() != null) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_INFO, "has_headers", new Object[] {});
          }
        }
        if (grades.getStudents() != null) {
          PostemTool.populateMessage(
              FacesMessage.SEVERITY_INFO,
              "has_students",
              new Object[] {new Integer(grades.getStudents().size())});
        }
        if (withHeader == true) {
          currentGradebook.setHeadings(grades.getHeaders());
        }
        List slist = grades.getStudents();

        if (oldGradebook.getId() != null && !this.userPressedBack) {
          Set oldStudents = currentGradebook.getStudents();
          oldGradebook.setStudents(oldStudents);
        }

        currentGradebook.setStudents(new TreeSet());
        // gradebookManager.saveGradebook(currentGradebook);
        Iterator si = slist.iterator();
        while (si.hasNext()) {
          List ss = (List) si.next();
          String uname = ((String) ss.remove(0)).trim();
          // logger.info("[POSTEM] processCreate -- adding student " +
          // uname);
          gradebookManager.createStudentGradesInGradebook(uname, ss, currentGradebook);
          if (currentGradebook.getStudents().size() == 1) {
            currentGradebook.setFirstUploadedUsername(
                uname); // otherwise, the verify screen shows first in ABC order
          }
        }
      } catch (DataFormatException exception) {
        /*
         * TODO: properly subclass exception in order to allow for localized
         * messages (add getRowNumber/setRowNumber). Set exception message to be
         * key in .properties file
         */
        PostemTool.populateMessage(
            FacesMessage.SEVERITY_ERROR, exception.getMessage(), new Object[] {});
        return "create_gradebook";
      } catch (IdUnusedException e) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
        return "create_gradebook";
      } catch (TypeException e) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
        return "create_gradebook";
      } catch (PermissionException e) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
        return "create_gradebook";
      } catch (ServerOverloadException e) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
        return "create_gradebook";
      } catch (IOException e) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
        return "create_gradebook";
      }
    } else if (this.csv != null) {
      // logger.info("**** Non Null Empty CSV!");
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "has_students", new Object[] {new Integer(0)});
      currentGradebook.setHeadings(new ArrayList());
      if (oldGradebook.getId() != null) {
        Set oldStudents = currentGradebook.getStudents();
        oldGradebook.setStudents(oldStudents);
      }

      currentGradebook.setStudents(new TreeSet());
    }

    if (this.newTemplate != null && this.newTemplate.trim().length() > 0) {
      currentGradebook.setTemplate(gradebookManager.createTemplate(newTemplate.trim()));
    } else if (this.newTemplate != null) {
      // logger.info("*** Non Null Empty Template!");
      currentGradebook.setTemplate(null);
    }

    /*
     * if("No".equals(this.release)) { currentGradebook.setReleased(new
     * Boolean(false)); //logger.info("Set to No, " +
     * currentGradebook.getReleased()); } else {
     * currentGradebook.setReleased(new Boolean(true)); //logger.info("Set to
     * Yes, " + currentGradebook.getReleased()); }
     */

    // gradebookManager.saveGradebook(currentGradebook);
    // logger.info(currentGradebook.getId());
    // currentGradebook = null;
    if ((this.csv != null && this.csv.trim().length() > 0)
        || (this.newTemplate != null && this.newTemplate.trim().length() > 0)) {
      this.csv = null;
      this.newTemplate = null;
      return "verify";
    }

    Iterator oi = oldGradebook.getStudents().iterator();
    while (oi.hasNext()) {
      gradebookManager.deleteStudentGrades((StudentGrades) oi.next());
    }
    this.userId = SessionManager.getCurrentSessionUserId();
    currentGradebook.setLastUpdated(new Timestamp(new Date().getTime()));
    currentGradebook.setLastUpdater(this.userId);
    gradebookManager.saveGradebook(currentGradebook);

    this.currentGradebook = null;
    this.oldGradebook = null;
    this.withHeader = true;
    // this.gradebooks = null;
    return "main";
  }
Example #7
0
  private boolean usernamesValid(CSV studentGrades) {
    boolean usersAreValid = true;
    List blankRows = new ArrayList();
    List invalidUsernames = new ArrayList();
    int row = 1;

    List siteMembers = getSiteMembers();

    List studentList = studentGrades.getStudentUsernames();
    Iterator studentIter = studentList.iterator();
    while (studentIter.hasNext()) {
      row++;
      String usr = (String) studentIter.next();

      if (LOG.isDebugEnabled()) {
        LOG.debug("usernamesValid : username="******"usernamesValid : siteMembers" + siteMembers);
      }
      if (usr == null || usr.equals("")) {

        usersAreValid = false;
        blankRows.add(new Integer(row));
      } else if (siteMembers == null
          || (siteMembers != null && !siteMembers.contains(getUserDefined(usr)))) {
        usersAreValid = false;
        invalidUsernames.add(usr);
      }
    }

    if (blankRows.size() == 1) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "missing_single_username", new Object[] {});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "missing_location", new Object[] {blankRows.get(0)});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "missing_username_dir", new Object[] {});
    } else if (blankRows.size() > 1) {
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "missing_mult_usernames", new Object[] {});
      for (int i = 0; i < blankRows.size(); i++) {
        PostemTool.populateMessage(
            FacesMessage.SEVERITY_ERROR, "missing_location", new Object[] {blankRows.get(i)});
      }
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "missing_username_dir", new Object[] {});
    }

    if (invalidUsernames.size() == 1) {
      PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "blank", new Object[] {});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "single_invalid_username", new Object[] {});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "invalid_username", new Object[] {invalidUsernames.get(0)});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "single_invalid_username_dir", new Object[] {});
    } else if (invalidUsernames.size() > 1) {
      PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "blank", new Object[] {});
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "mult_invalid_usernames", new Object[] {});
      for (int j = 0; j < invalidUsernames.size(); j++) {
        PostemTool.populateMessage(
            FacesMessage.SEVERITY_ERROR,
            "invalid_username",
            new Object[] {invalidUsernames.get(j)});
      }
      PostemTool.populateMessage(
          FacesMessage.SEVERITY_ERROR, "mult_invalid_usernames_dir", new Object[] {});
    }
    return usersAreValid;
  }
  @Test
  public void testCreateService() throws Exception {
    Activator instance = Activator.getDefault();
    assertNotNull("Run as a JUnit Plug-in Test", instance);

    Bundle bundle = instance.getBundle();
    URL url = bundle.getEntry("cities.csv");
    System.out.println("Bundle URL" + url);

    URL fileUrl = FileLocator.toFileURL(url);
    System.out.println("Bundle URL" + fileUrl);

    // get the service factory
    IServiceFactory factory = CatalogPlugin.getDefault().getServiceFactory();

    // create the service

    List<IService> services = factory.createService(fileUrl);

    // ensure the service was created
    assertNotNull(services);
    assertEquals(1, services.size());

    // ensure the right type of service was created
    IService service = services.get(0);
    assertNotNull(service);

    ICatalog catalog = CatalogPlugin.getDefault().getLocalCatalog();
    catalog.add(service); // we can now find this service!

    List<IResolve> found = catalog.search("csv", null, null);
    assertEquals(2, found.size());

    // get all the resources from the service
    List<? extends IGeoResource> resources = service.resources(null);
    assertNotNull(resources);
    assertEquals(resources.size(), 1);

    CSV csv = null;
    for (IGeoResource resource : resources) {
      IGeoResourceInfo info = resource.getInfo(null);

      String description = info.getDescription();
      assertNotNull(description);
      System.out.println("Description:" + description);

      ReferencedEnvelope bounds = info.getBounds();
      assertTrue(!bounds.isNull());
      System.out.println("Bounds:" + bounds);

      if (resource.canResolve(CSV.class)) {
        csv = resource.resolve(CSV.class, null);
      }
    }
    CsvReader reader = csv.reader();
    reader.readHeaders();
    reader.setCaptureRawRecord(true);
    reader.setTrimWhitespace(true);
    int count = 0;
    while (reader.readRecord()) {
      String x = reader.get("x");
      String y = reader.get("y");
      System.out.print(reader.getCurrentRecord() + " point " + x + " x " + y);
      Point point = CSV.getPoint(reader);
      System.out.println("-->" + point);

      count++;
    }
    reader.close();
    System.out.println(count);
  }
  /* (non-Javadoc)
   * @see org.nightlabs.jfire.geography.GeographyTemplateDataManagerRemote#storeGeographyTemplateLocationData(org.nightlabs.jfire.geography.Location)
   */
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  @RolesAllowed("_Guest_")
  public void storeGeographyTemplateLocationData(Location storedLocation)
      throws IOException, SecurityException {
    assertWritingAllowed();

    final PersistenceManager pm = createPersistenceManager();
    try {
      NLJDOHelper.enableTransactionSerializeReadObjects(pm);
      try {
        pm.getFetchPlan().setMaxFetchDepth(1);
        pm.getFetchPlan().setGroup(FetchPlan.ALL);

        final Geography geography = Geography.sharedInstance();
        geography
            .clearCache(); // ensure that the data we're going to manipulate in this transaction are
                           // really up-to-date.

        String rootOrganisationID;

        try {
          final InitialContext initialContext = new InitialContext();
          try {
            rootOrganisationID = Organisation.getRootOrganisationID(initialContext);
          } finally {
            initialContext.close();
          }
        } catch (final NamingException x) {
          throw new RuntimeException(
              x); // it's definitely an unexpected exception if we can't access the local JNDI.
        }

        LocationID locationID =
            LocationID.create(
                storedLocation.getCountryID(), rootOrganisationID, storedLocation.getLocationID());
        final CountryID countryID = CountryID.create(storedLocation.getCountryID());

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final Writer w =
            new OutputStreamWriter(new DeflaterOutputStream(out), IOUtil.CHARSET_UTF_8);
        try {
          w.write(LOCATION_CSV_HEADER);
          for (final Region r : geography.getRegions(countryID, true)) {
            for (final City c : geography.getCities(RegionID.create(r), true)) {
              for (Location existLocation : geography.getLocations(CityID.create(c), true)) {
                if (LocationID.create(
                        existLocation.getCountryID(),
                        rootOrganisationID,
                        existLocation.getLocationID())
                    .equals(locationID)) {
                  existLocation = storedLocation;
                  storedLocation = null;
                  locationID = null;
                } // if

                final String csvLines = GeographyImplResourceCSV.location2csvLines(existLocation);

                if (logger.isDebugEnabled()) logger.debug(csvLines);

                w.write(csvLines);
              } // for
            } // for
          } // for

          if (storedLocation != null) {
            final String csvLines = GeographyImplResourceCSV.location2csvLines(storedLocation);

            if (logger.isDebugEnabled()) logger.debug(csvLines);

            csvLines.trim();
            w.write(csvLines);
          } // if
        } finally {
          w.close();
        }

        CSV.setCSVData(
            pm, rootOrganisationID, CSV.CSV_TYPE_LOCATION, countryID.countryID, out.toByteArray());

        clearCache();

      } finally {
        NLJDOHelper.disableTransactionSerializeReadObjects(pm);
      }
    } finally {
      pm.close();
    }
  }
  /* (non-Javadoc)
   * @see org.nightlabs.jfire.geography.GeographyTemplateDataManagerRemote#storeGeographyTemplateCityData(org.nightlabs.jfire.geography.City)
   */
  @TransactionAttribute(TransactionAttributeType.REQUIRED)
  @RolesAllowed("_Guest_")
  public void storeGeographyTemplateCityData(City storedCity)
      throws IOException, SecurityException {
    assertWritingAllowed();

    final PersistenceManager pm = createPersistenceManager();
    try {
      pm.getFetchPlan().setMaxFetchDepth(1);
      pm.getFetchPlan().setGroup(FetchPlan.ALL);

      final Geography geography = Geography.sharedInstance();

      String rootOrganisationID;

      try {
        final InitialContext initialContext = new InitialContext();
        try {
          rootOrganisationID = Organisation.getRootOrganisationID(initialContext);
        } // try
        finally {
          initialContext.close();
        } // finally
      } // try
      catch (final NamingException x) {
        throw new RuntimeException(
            x); // it's definitely an unexpected exception if we can't access the local JNDI.
      } // catch

      CityID cityID = CityID.create(storedCity);
      final CountryID countryID = CountryID.create(storedCity);

      final ByteArrayOutputStream out = new ByteArrayOutputStream();
      final Writer w = new OutputStreamWriter(new DeflaterOutputStream(out), IOUtil.CHARSET_UTF_8);
      try {
        w.write(CITY_CSV_HEADER);
        for (final Region existRegion : geography.getRegions(countryID, true)) {
          for (City existCity : geography.getCities(RegionID.create(existRegion), true)) {
            if (CityID.create(existCity).equals(cityID)) { // if come in this case it is update
              existCity = storedCity;
              storedCity = null;
              cityID = null;
            } // if

            final String csvLines = GeographyImplResourceCSV.city2csvLines(existCity);

            if (logger.isDebugEnabled()) logger.debug(csvLines);

            w.write(csvLines);
          } // for
        } // for

        if (storedCity != null) { // add new city
          final String csvLines = GeographyImplResourceCSV.city2csvLines(storedCity);

          if (logger.isDebugEnabled()) logger.debug(csvLines);

          csvLines.trim();
          w.write(csvLines);
        } // if
      } // try
      finally {
        w.close();
      } // finally

      CSV.setCSVData(
          pm, rootOrganisationID, CSV.CSV_TYPE_CITY, countryID.countryID, out.toByteArray());

      clearCache();
    } // try
    finally {
      pm.close();
    } // finally
  }
Example #11
0
    private boolean getStatus(long theFileSize) {
      URL theURL = null;
      ;
      try {
        theURL = new URL(myProperties.getProperty("BASEURL"));
      } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      ;

      String data = "";
      boolean theStatus = false;
      try {
        data =
            URLEncoder.encode("filelocation", "UTF-8")
                + "="
                + URLEncoder.encode(myProperties.getProperty("REMOTEBASEDIR"), "UTF-8");
        data +=
            "&"
                + URLEncoder.encode("fileprocess", "UTF-8")
                + "="
                + URLEncoder.encode("STATUS", "UTF-8");
        data +=
            "&"
                + URLEncoder.encode("filename", "UTF-8")
                + "="
                + URLEncoder.encode(myProperties.getProperty("REMOTEDOWNLOADFILENAME"), "UTF-8");

        URLConnection conn = theURL.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line2;
        CSV theParser = new CSV('|');
        while (((line2 = rd.readLine()) != null) && !isCancelled()) {
          List list = theParser.parse(line2);
          System.out.println((String) list.get(0));
          if (((String) list.get(0)).equals(" Process running")) {
            theStatus = true;
            myMessage.messageChanged(
                (int) getPercentage(Long.parseLong((String) list.get(1)), theFileSize),
                "Process Running downloaded " + (String) list.get(1) + " bytes");
          }
          if (((String) list.get(0)).equals(" Process stopped")) {
            theStatus = false;
            myMessage.messageChanged(
                (int) getPercentage(Long.parseLong((String) list.get(1)), theFileSize),
                "Process Stopped File size =  " + (String) list.get(1) + " bytes");
          }
        }
        rd.close();

      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println("theStatus =" + theStatus);
      return theStatus;
    }