/*
   * Execute query against a list of sensors
   *
   * */
  public static String executeQuery(
      String envelope, String query, String matchingSensors, String format) throws ParseException {

    // String matchingSensors = getListOfSensorsAsString(envelope);
    String reformattedQuery = reformatQuery(query, matchingSensors);
    StringBuilder sb = new StringBuilder();
    Connection connection = null;

    try {
      connection = Main.getDefaultStorage().getConnection();
      Statement statement =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet results = statement.executeQuery(reformattedQuery);
      ResultSetMetaData metaData; // Additional information about the results
      int numCols, numRows; // How many rows and columns in the table
      metaData = results.getMetaData(); // Get metadata on them
      numCols = metaData.getColumnCount(); // How many columns?
      results.last(); // Move to last row
      numRows = results.getRow(); // How many rows?

      String s;

      // headers
      // sb.append("# Query: " + query + NEWLINE);
      sb.append("# Query: " + reformattedQuery.replaceAll("\n", "\n# ") + NEWLINE);

      sb.append("# ");
      for (int col = 0; col < numCols; col++) {
        sb.append(metaData.getColumnLabel(col + 1));
        if (col < numCols - 1) sb.append(SEPARATOR);
      }
      sb.append(NEWLINE);

      for (int row = 0; row < numRows; row++) {
        results.absolute(row + 1); // Go to the specified row
        for (int col = 0; col < numCols; col++) {
          Object o = results.getObject(col + 1); // Get value of the column
          if (o == null) s = "null";
          else s = o.toString();
          if (col < numCols - 1) sb.append(s).append(SEPARATOR);
          else sb.append(s);
        }
        sb.append(NEWLINE);
      }
    } catch (SQLException e) {
      sb.append("ERROR in execution of query: " + e.getMessage());
    } finally {
      Main.getDefaultStorage().close(connection);
    }

    return sb.toString();
  }
Beispiel #2
0
  public boolean initialize() {

    try {
      initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
      uid = Math.random();

      postParameters = new ArrayList<NameValuePair>();
      postParameters.add(
          new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
      postParameters.add(
          new BasicNameValuePair(
              PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
      // Init the http client
      if (initParams.isSSLRequired()) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(
            new FileInputStream(new File("conf/servertestkeystore")),
            Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        int sslPort =
            Main.getContainerConfig().getSSLPort() > 0
                ? Main.getContainerConfig().getSSLPort()
                : ContainerConfig.DEFAULT_SSL_PORT;
        Scheme sch = new Scheme("https", socketFactory, sslPort);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
      }
      Scheme plainsch =
          new Scheme(
              "http",
              PlainSocketFactory.getSocketFactory(),
              Main.getContainerConfig().getContainerPort());
      httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
      //
      lastReceivedTimestamp = initParams.getStartTime();
      structure = registerAndGetStructure();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      NotificationRegistry.getInstance().removeNotification(uid);
      return false;
    }

    return true;
  }
Beispiel #3
0
 public static void main(String[] args) {
   Main.gsnControllerPort = Integer.parseInt(args[0]);
   updateSplashIfNeeded(
       new String[] {"GSN is trying to start.", "All GSN logs are available at: logs/gsn.log"});
   try {
     Main.getInstance();
   } catch (Exception e) {
     updateSplashIfNeeded(
         new String[] {"Starting GSN failed! Look at logs/gsn.log for more information."});
     try {
       Thread.sleep(4000);
     } catch (InterruptedException e1) {
       e1.printStackTrace();
     }
   }
   closeSplashIfneeded();
 }
  /**
   * *****************************************************************************************************************
   */
  private void checkSessionScheme(HttpServletRequest req, HttpServletResponse res)
      throws IOException {

    if (req.getScheme().equals("https") == true) {
      if ((req.getSession().getAttribute("scheme") == null)) {
        req.getSession().setAttribute("scheme", "https");
      }
    } else if (req.getScheme().equals("http") == true) {
      if ((req.getSession().getAttribute("scheme") == null)) {
        req.getSession().setAttribute("scheme", "http");
      }
      res.sendRedirect(
          "https://"
              + req.getServerName()
              + ":"
              + Main.getContainerConfig().getSSLPort()
              + "/gsn/MyUserUpdateWaitingListServlet");
    }
  }
Beispiel #5
0
  private Main() throws Exception {

    ValidityTools.checkAccessibilityOfFiles(
        DEFAULT_GSN_LOG4J_PROPERTIES,
        WrappersUtil.DEFAULT_WRAPPER_PROPERTIES_FILE,
        DEFAULT_GSN_CONF_FILE);
    ValidityTools.checkAccessibilityOfDirs(DEFAULT_VIRTUAL_SENSOR_DIRECTORY);
    PropertyConfigurator.configure(Main.DEFAULT_GSN_LOG4J_PROPERTIES);
    //  initializeConfiguration();
    try {
      controlSocket = new GSNController(null, gsnControllerPort);
      containerConfig = loadContainerConfiguration();
      updateSplashIfNeeded(
          new String[] {
            "GSN is starting at port:" + containerConfig.getContainerPort(),
            "All GSN logs are available at: logs/gsn.log"
          });
      System.out.println(
          "Global Sensor Networks (GSN) is Starting on port "
              + containerConfig.getContainerPort()
              + "...");
      System.out.println("The logs of GSN server are available in logs/gsn.log file.");
      System.out.println("To Stop GSN execute the gsn-stop script.");
    } catch (FileNotFoundException e) {
      logger.error(
          new StringBuilder()
              .append("The the configuration file : conf/gsn.xml")
              .append(" doesn't exist.")
              .toString());
      logger.error(e.getMessage());
      logger.error("Check the path of the configuration file and try again.");
      if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e);
      throw new Exception(e);
    }
    int maxDBConnections =
        System.getProperty("maxDBConnections") == null
            ? DEFAULT_MAX_DB_CONNECTIONS
            : Integer.parseInt(System.getProperty("maxDBConnections"));
    int maxSlidingDBConnections =
        System.getProperty("maxSlidingDBConnections") == null
            ? DEFAULT_MAX_DB_CONNECTIONS
            : Integer.parseInt(System.getProperty("maxSlidingDBConnections"));
    int maxServlets =
        System.getProperty("maxServlets") == null
            ? DEFAULT_JETTY_SERVLETS
            : Integer.parseInt(System.getProperty("maxServlets"));

    // Init the AC db connection.
    if (Main.getContainerConfig().isAcEnabled() == true) {
      ConnectToDB.init(
          containerConfig.getStorage().getJdbcDriver(),
          containerConfig.getStorage().getJdbcUsername(),
          containerConfig.getStorage().getJdbcPassword(),
          containerConfig.getStorage().getJdbcURL());
    }

    mainStorage =
        StorageManagerFactory.getInstance(
            containerConfig.getStorage().getJdbcDriver(),
            containerConfig.getStorage().getJdbcUsername(),
            containerConfig.getStorage().getJdbcPassword(),
            containerConfig.getStorage().getJdbcURL(),
            maxDBConnections);
    //
    StorageConfig sc =
        containerConfig.getSliding() != null
            ? containerConfig.getSliding().getStorage()
            : containerConfig.getStorage();
    windowStorage =
        StorageManagerFactory.getInstance(
            sc.getJdbcDriver(),
            sc.getJdbcUsername(),
            sc.getJdbcPassword(),
            sc.getJdbcURL(),
            maxSlidingDBConnections);
    //
    validationStorage =
        StorageManagerFactory.getInstance(
            "org.h2.Driver", "sa", "", "jdbc:h2:mem:validator", Main.DEFAULT_MAX_DB_CONNECTIONS);

    if (logger.isInfoEnabled())
      logger.info("The Container Configuration file loaded successfully.");

    try {
      logger.debug(
          "Starting the http-server @ port: "
              + containerConfig.getContainerPort()
              + " (maxDBConnections: "
              + maxDBConnections
              + ", maxSlidingDBConnections: "
              + maxSlidingDBConnections
              + ", maxServlets:"
              + maxServlets
              + ")"
              + " ...");
      Server jettyServer =
          getJettyServer(
              getContainerConfig().getContainerPort(),
              getContainerConfig().getSSLPort(),
              maxServlets);
      jettyServer.start();
      logger.debug("http-server running @ port: " + containerConfig.getContainerPort());
    } catch (Exception e) {
      throw new Exception(
          "Start of the HTTP server failed. The HTTP protocol is used in most of the communications: "
              + e.getMessage(),
          e);
    }
    VSensorLoader vsloader = VSensorLoader.getInstance(DEFAULT_VIRTUAL_SENSOR_DIRECTORY);
    controlSocket.setLoader(vsloader);

    String msrIntegration = "gsn.msr.sensormap.SensorMapIntegration";
    try {
      vsloader.addVSensorStateChangeListener(
          (VSensorStateChangeListener) Class.forName(msrIntegration).newInstance());
    } catch (Exception e) {
      logger.warn("MSR Sensor Map integration is disabled.");
    }

    vsloader.addVSensorStateChangeListener(new SQLValidatorIntegration(SQLValidator.getInstance()));
    vsloader.addVSensorStateChangeListener(DataDistributer.getInstance(LocalDeliveryWrapper.class));
    vsloader.addVSensorStateChangeListener(DataDistributer.getInstance(PushDelivery.class));
    vsloader.addVSensorStateChangeListener(DataDistributer.getInstance(RestDelivery.class));

    ContainerImpl.getInstance()
        .addVSensorDataListener(DataDistributer.getInstance(LocalDeliveryWrapper.class));
    ContainerImpl.getInstance()
        .addVSensorDataListener(DataDistributer.getInstance(PushDelivery.class));
    ContainerImpl.getInstance()
        .addVSensorDataListener(DataDistributer.getInstance(RestDelivery.class));
    vsloader.startLoading();
  }
Beispiel #6
0
  public static int register_sensor(
      String username, String password, VSensorConfig conf, String gsnURI)
      throws RemoteException, FileNotFoundException {

    gsn.msr.sensormap.sensorman.ServiceStub.Guid passGUID = login_to_sensor_map(username, password);
    HashMap<String, MetaData> output =
        MetaData.createMetaData(Main.getContainerConfig().getMsrMap().get("metadata"));

    logger.warn("Registering sensor " + conf.getName() + " on Sensormap...");

    gsn.msr.sensormap.sensorman.ServiceStub stub =
        new gsn.msr.sensormap.sensorman.ServiceStub(); // the
    // default
    // implementation
    // should
    // point
    // to
    // the
    // right
    // endpoint

    StringBuilder pComments = new StringBuilder();
    StringBuilder pNames = new StringBuilder();
    StringBuilder pMetadata = new StringBuilder();
    StringBuilder pTypes = new StringBuilder();
    String groupName = Main.getContainerConfig().getMsrMap().get("group-name");

    for (DataField df : conf.getOutputStructure()) {
      MetaData metaData = output.get(df.getName().toLowerCase().trim());
      String pType = null;
      String pUnit = "";

      if (metaData != null) {
        pTypes.append(metaData.getSensorType()).append("|");
        pType = metaData.getSensorType();
        pMetadata.append(metaData.getMetadata()).append("|");
        pComments.append(metaData.getComments()).append("|");
        pNames.append(metaData.getSensorName()).append("|");
        pUnit = metaData.getUnit();
      } else {
        pTypes.append(df.getName()).append("|");
        pNames.append(df.getName()).append("|");
        pType = df.getName();
      }
      if (!dataTypeCache.contains(pType)) {
        gsn.msr.sensormap.sensorman.ServiceStub.CreateSingularSensorType createType =
            new gsn.msr.sensormap.sensorman.ServiceStub.CreateSingularSensorType();
        createType.setPublisherName(username);
        createType.setPassCode(passGUID);
        createType.setName(pType);
        createType.setUnit(pUnit);
        createType.setDataType("scalar");
        createType.setIconUrl("");
        String result =
            stub.CreateSingularSensorType(createType).getCreateSingularSensorTypeResult();
        logger.info("Registering data type: " + pType + " , MSR's output: " + result);
        dataTypeCache.add(pType);
      }
    }

    gsn.msr.sensormap.userman.ServiceStub.AddGroup createGroup =
        new gsn.msr.sensormap.userman.ServiceStub.AddGroup();
    gsn.msr.sensormap.userman.ServiceStub login = new gsn.msr.sensormap.userman.ServiceStub();
    createGroup.setGrpName(conf.getName());
    if (groupName != null && groupName.trim().length() > 0) createGroup.setParentGroup(groupName);
    createGroup.setAdmin(username);
    String call_output = login.AddGroup(createGroup).getAddGroupResult();
    logger.info(
        "Creating a group called : "
            + conf.getName()
            + " With Parent: "
            + groupName
            + " MSR: "
            + call_output);

    gsn.msr.sensormap.sensorman.ServiceStub.DeleteVectorSensor deleteVSensorParam =
        new gsn.msr.sensormap.sensorman.ServiceStub.DeleteVectorSensor();
    deleteVSensorParam.setOriginalPublisherName(username);
    deleteVSensorParam.setPublisherName(username);
    deleteVSensorParam.setPassCode(passGUID);
    deleteVSensorParam.setSensorName(conf.getName());
    deleteVSensorParam.setSensorType("GSN-" + conf.getName());

    call_output = stub.DeleteVectorSensor(deleteVSensorParam).getDeleteVectorSensorResult();
    logger.info("Unregister: " + conf.getName() + " - MSR: " + call_output);

    gsn.msr.sensormap.sensorman.ServiceStub.RegisterCompositeSensor registerVectorSensorParams =
        new gsn.msr.sensormap.sensorman.ServiceStub.RegisterCompositeSensor();

    registerVectorSensorParams.setPublisherName(username);
    registerVectorSensorParams.setPassCode(passGUID);
    registerVectorSensorParams.setVectorSensorName(conf.getName());
    registerVectorSensorParams.setWsURL(gsnURI + "services/Service?wsdl");
    registerVectorSensorParams.setAlt(conf.getAltitude().toString());
    registerVectorSensorParams.setLat(conf.getLatitude().toString());
    registerVectorSensorParams.setLon(conf.getLongitude().toString());
    registerVectorSensorParams.setDesc(conf.getDescription());
    registerVectorSensorParams.setVectorSensorType("GSN-" + conf.getName());
    registerVectorSensorParams.setParamTypes(pTypes.toString());
    registerVectorSensorParams.setParamComments(pComments.toString());
    registerVectorSensorParams.setParamMetaData(pMetadata.toString());
    registerVectorSensorParams.setParamNames(pNames.toString());
    registerVectorSensorParams.setAccessControl("protected");
    registerVectorSensorParams.setDataType("vector");
    registerVectorSensorParams.setIcon("image/CImg/weather_tower.gif");
    registerVectorSensorParams.setGroupName(conf.getName());

    call_output =
        stub.RegisterCompositeSensor(registerVectorSensorParams).getRegisterCompositeSensorResult();

    if (call_output.indexOf("OK") >= 0) {
      logger.warn(
          "Sensor " + conf.getName() + " registered correctly. SensorMap says: " + call_output);
      return REGISTER_SENSOR_OK_CREATED_NEW;
    }

    if (call_output.indexOf(
            "Error: Sensor with the same publisher name and sensor name already exists")
        >= 0) {
      logger.warn(
          "Sensor "
              + conf.getName()
              + " not registered (already exists). SensorMap says: "
              + call_output);
      return REGISTER_SENSOR_ERROR_ALREADY_EXISTS;
    }

    logger.warn("Sensor " + conf.getName() + " not registered. SensorMap says: " + call_output);
    return REGISTER_SENSOR_ERROR_NOT_CREATED;
  }