private void randomDomainNamePos() {
   Random rand = new Random();
   List<String> domainList = this.diamondConfigure.getDomainNameList();
   if (!domainList.isEmpty()) {
     this.domainNamePos.set(rand.nextInt(domainList.size()));
   }
 }
  protected List<Location> deserializeSearchResults(InputStream inputStream) throws JAXBException {

    JAXBContext jaxbContext = JAXBContext.newInstance(SearchData.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SearchData data = (SearchData) unmarshaller.unmarshal(inputStream);

    List<Location> locations = new ArrayList<Location>();

    for (LocationResult l : data.getResults()) {
      Location location = new Location();
      location.setCity(l.getCity());
      location.setLatitude(l.getLatitude());
      location.setLongitude(l.getLongitude());
      location.setStateOrCountry(l.getRegion() != null ? l.getRegion() : l.getCountry());

      StringBuffer code = new StringBuffer();
      code.append(l.getCity());
      if (l.getRegion() != null && !l.getRegion().contains(", ")) {
        code.append(", ").append(l.getRegion());
      }
      if (l.getCountry() != null) {
        code.append(", ").append(l.getCountry());
      }
      location.setLocationCode(code.toString());
      locations.add(location);
    }

    return locations;
  }
  private synchronized void doConfigClearspace() throws UnauthorizedException {

    Log.debug("Starting Clearspace configuration.");

    List<String> bindInterfaces = getServerInterfaces();
    if (bindInterfaces.size() == 0) {
      // We aren't up and running enough to tell Clearspace what interfaces to bind to.
      Log.debug("No bind interfaces found to config Clearspace");
      throw new IllegalStateException("There are no binding interfaces.");
    }

    try {

      XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo();

      String path = IM_URL_PREFIX + "configureComponent/";

      // Creates the XML with the data
      Document groupDoc = DocumentHelper.createDocument();
      Element rootE = groupDoc.addElement("configureComponent");
      Element domainE = rootE.addElement("domain");
      domainE.setText(serverInfo.getXMPPDomain());
      for (String bindInterface : bindInterfaces) {
        Element hostsE = rootE.addElement("hosts");
        hostsE.setText(bindInterface);
      }
      Element portE = rootE.addElement("port");
      portE.setText(String.valueOf(ExternalComponentManager.getServicePort()));

      Log.debug(
          "Trying to configure Clearspace with: Domain: "
              + serverInfo.getXMPPDomain()
              + ", hosts: "
              + bindInterfaces.toString()
              + ", port: "
              + port);

      executeRequest(POST, path, rootE.asXML());

      // Done, Clearspace was configured correctly, clear the task
      Log.debug("Clearspace was configured, stopping the task.");
      TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask);
      configClearspaceTask = null;

    } catch (UnauthorizedException ue) {
      throw ue;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UnsupportedOperationException
      throw new UnsupportedOperationException("Unexpected error", e);
    }
  }
  private List<String> getServerInterfaces() {

    List<String> bindInterfaces = new ArrayList<String>();

    String interfaceName = JiveGlobals.getXMLProperty("network.interface");
    String bindInterface = null;
    if (interfaceName != null) {
      if (interfaceName.trim().length() > 0) {
        bindInterface = interfaceName;
      }
    }

    int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090);
    int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091);

    if (bindInterface == null) {
      try {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netInterface : Collections.list(nets)) {
          Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
          for (InetAddress address : Collections.list(addresses)) {
            if ("127.0.0.1".equals(address.getHostAddress())) {
              continue;
            }
            if (address.getHostAddress().startsWith("0.")) {
              continue;
            }
            Socket socket = new Socket();
            InetSocketAddress remoteAddress =
                new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort);
            try {
              socket.connect(remoteAddress);
              bindInterfaces.add(address.getHostAddress());
              break;
            } catch (IOException e) {
              // Ignore this address. Let's hope there is more addresses to validate
            }
          }
        }
      } catch (SocketException e) {
        // We failed to discover a valid IP address where the admin console is running
        return null;
      }
    } else {
      bindInterfaces.add(bindInterface);
    }

    return bindInterfaces;
  }
Beispiel #5
0
 private void LoadQueriesBtnMouseClicked(
     java.awt.event.MouseEvent evt) { // GEN-FIRST:event_LoadQueriesBtnMouseClicked
   // Algorithm
   /*
    * Goto queries' directory and load all queryfile.query to Combobox
    * Change local directory to repository diretory
    * List all file there
    * Try to load all file and add to combobox
    *
    *
    */
   String sQueryRepositoryPath = "/home/natuan/Documents/OntologyMysql/QueriesRepository/";
   File dir = new File(sQueryRepositoryPath);
   String[] children = dir.list();
   if (children == null) {
     // Either dir does not exist or is not a directory
   } else {
     System.out.println("list files");
     for (int i = 0; i < children.length; i++) {
       // Get filename of file or directory
       String filename = children[i];
       String sContent = ReadWholeFileToString(sQueryRepositoryPath + filename);
       queryList.add(sContent);
       QueriesCmb.addItem(filename);
       SparqlTxtArea.setText(sContent);
       //   System.out.println(filename);
     }
     QueriesCmb.setSelectedIndex(children.length - 1);
   }
 } // GEN-LAST:event_LoadQueriesBtnMouseClicked
  @Override
  public List<CopyToEnvironmentItem> processMandatoryDependencies(
      CopyToEnvironmentItem item, List<String> pathsToDeploy, Set<String> missingDependenciesPaths)
      throws DeploymentException {
    List<CopyToEnvironmentItem> mandatoryDependencies = new ArrayList<CopyToEnvironmentItem>();
    String site = item.getSite();
    String path = item.getPath();
    if (item.getAction() == CopyToEnvironmentItem.Action.NEW
        || item.getAction() == CopyToEnvironmentItem.Action.MOVE) {
      String helpPath = path.replace("/" + _indexFile, "");
      int idx = helpPath.lastIndexOf("/");
      String parentPath = helpPath.substring(0, idx) + "/" + _indexFile;
      if (_contentRepository.isNew(site, parentPath)
          || _contentRepository.isRenamed(site, parentPath)) {
        String parentFullPath = _contentRepository.getFullPath(site, parentPath);
        if (!missingDependenciesPaths.contains(parentFullPath)
            && !pathsToDeploy.contains(parentFullPath)) {
          try {
            _deploymentDAL.cancelWorkflow(site, parentPath);
          } catch (DeploymentDALException e) {
            LOGGER.error(
                "Error while canceling workflow for path {0}, site {1}", e, site, parentPath);
          }
          missingDependenciesPaths.add(parentFullPath);
          CopyToEnvironmentItem parentItem = createMissingItem(site, parentPath, item);
          processItem(parentItem);
          mandatoryDependencies.add(parentItem);
          mandatoryDependencies.addAll(
              processMandatoryDependencies(parentItem, pathsToDeploy, missingDependenciesPaths));
        }
      }

      List<String> dependentPaths = _contentRepository.getDependentPaths(site, path);
      for (String dependentPath : dependentPaths) {
        if (_contentRepository.isNew(site, dependentPath)
            || _contentRepository.isRenamed(site, dependentPath)) {
          String dependentFullPath = _contentRepository.getFullPath(site, dependentPath);
          if (!missingDependenciesPaths.contains(dependentFullPath)
              && !pathsToDeploy.contains(dependentFullPath)) {
            try {
              _deploymentDAL.cancelWorkflow(site, dependentPath);
            } catch (DeploymentDALException e) {
              LOGGER.error(
                  "Error while canceling workflow for path {0}, site {1}", e, site, dependentPath);
            }
            missingDependenciesPaths.add(dependentFullPath);
            CopyToEnvironmentItem dependentItem = createMissingItem(site, dependentPath, item);
            processItem(dependentItem);
            mandatoryDependencies.add(dependentItem);
            mandatoryDependencies.addAll(
                processMandatoryDependencies(
                    dependentItem, pathsToDeploy, missingDependenciesPaths));
          }
        }
      }
    }

    return mandatoryDependencies;
  }
  /**
   * Sends an IQ packet to the Clearspace external component and returns the IQ packet returned by
   * CS or <tt>null</tt> if no answer was received before the specified timeout.
   *
   * @param packet IQ packet to send.
   * @param timeout milliseconds to wait before timing out.
   * @return IQ packet returned by Clearspace responsing the packet we sent.
   */
  public IQ query(final IQ packet, int timeout) {
    // Complain if FROM is empty
    if (packet.getFrom() == null) {
      throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
    }
    // If CS is not connected then return null
    if (clearspaces.isEmpty()) {
      return null;
    }
    // Set the target address to the IQ packet. Roate list so we distribute load
    String component;
    synchronized (clearspaces) {
      component = clearspaces.get(0);
      Collections.rotate(clearspaces, 1);
    }
    packet.setTo(component);
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
    final IQRouter router = XMPPServer.getInstance().getIQRouter();
    router.addIQResultListener(
        packet.getID(),
        new IQResultListener() {
          public void receivedAnswer(IQ packet) {
            answer.offer(packet);
          }

          public void answerTimeout(String packetId) {
            Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
          }
        });
    XMPPServer.getInstance().getIQRouter().route(packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
 public void componentInfoReceived(IQ iq) {
   // Check if it's a Clearspace component
   boolean isClearspace = false;
   Element childElement = iq.getChildElement();
   for (Iterator it = childElement.elementIterator("identity"); it.hasNext(); ) {
     Element identity = (Element) it.next();
     if ("component".equals(identity.attributeValue("category"))
         && "clearspace".equals(identity.attributeValue("type"))) {
       isClearspace = true;
     }
   }
   // If component is Clearspace then keep track of the component
   if (isClearspace) {
     clearspaces.add(iq.getFrom().getDomain());
   }
 }
  @Override
  public void deployItemsToTarget(
      String site, List<PublishingSyncItem> filteredItems, PublishingTargetItem target)
      throws ContentNotFoundForPublishingException, UploadFailedException {
    LOGGER.debug(
        "Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"",
        site, target.getName(), filteredItems.size());
    URL requestUrl = null;
    try {
      requestUrl = new URL(target.getServerUrl());
    } catch (MalformedURLException e) {
      LOGGER.error("Invalid server URL for target {0}", target.getName());
      throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
    }

    ByteArrayPartSource baps = null;
    PartSource metadataPart = null;
    StringPart stringPart = null;
    FilePart filePart = null;

    int numberOfBuckets = filteredItems.size() / target.getBucketSize() + 1;
    Iterator<PublishingSyncItem> iter = filteredItems.iterator();
    LOGGER.debug(
        "Divide all deployment items into {0} bucket(s) for  target {1}",
        numberOfBuckets, target.getName());
    List<DeploymentEventItem> eventItems = new ArrayList<DeploymentEventItem>();
    for (int bucketIndex = 0; bucketIndex < numberOfBuckets; bucketIndex++) {
      int cntFiles = 0;
      StringBuilder sbDeletedFiles = new StringBuilder();
      List<Part> formParts = new ArrayList<Part>();

      formParts.add(new StringPart(PASSWORD_REQUEST_PARAMETER, target.getPassword()));
      formParts.add(new StringPart(TARGET_REQUEST_PARAMETER, target.getTarget()));
      String siteId = target.getSiteId();
      if (StringUtils.isEmpty(siteId)) {
        siteId = site;
      }
      formParts.add(new StringPart(SITE_REQUEST_PARAMETER, siteId));

      LOGGER.debug(
          "Preparing deployment items (bucket {0}) for target {1}",
          bucketIndex + 1, target.getName());

      int loopSize =
          (filteredItems.size() - (bucketIndex * target.getBucketSize()) > target.getBucketSize())
              ? target.getBucketSize()
              : filteredItems.size() - bucketIndex * target.getBucketSize();
      for (int j = 0; j < loopSize; j++) {
        if (iter.hasNext()) {

          PublishingSyncItem item = iter.next();
          LOGGER.debug(
              "Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"",
              item.getPath(), item.getSite(), target.getName());
          DeploymentEventItem eventItem = new DeploymentEventItem();
          eventItem.setSite(item.getSite());
          eventItem.setPath(item.getPath());
          eventItem.setUser(item.getUser());
          eventItem.setDateTime(new Date());

          if (item.getAction() == PublishingSyncItem.Action.DELETE) {
            eventItem.setState(DeploymentEventItem.STATE_DELETED);
            if (sbDeletedFiles.length() > 0) {
              sbDeletedFiles.append(FILES_SEPARATOR).append(item.getPath());
            } else {
              sbDeletedFiles.append(item.getPath());
            }
            if (item.getPath().endsWith("/" + _indexFile)) {
              sbDeletedFiles
                  .append(FILES_SEPARATOR)
                  .append(item.getPath().replace("/" + _indexFile, ""));
            }
          } else {

            if (item.getAction() == PublishingSyncItem.Action.NEW) {
              eventItem.setState(DeploymentEventItem.STATE_NEW);
            } else if (item.getAction() == PublishingSyncItem.Action.MOVE) {
              eventItem.setState(DeploymentEventItem.STATE_MOVED);
            } else {
              eventItem.setState(DeploymentEventItem.STATE_UPDATED);
            }

            LOGGER.debug("Get content for \"{0}\" , site \"{1}\"", item.getPath(), item.getSite());
            InputStream input =
                _contentRepository.getContent(site, null, item.getEnvironment(), item.getPath());
            try {
              if (input == null || input.available() < 0) {
                if (!_contentRepository.isFolder(site, item.getPath())
                    && _contentRepository.contentExists(site, item.getPath())) {
                  baps = null;
                  stringPart = null;
                  filePart = null;
                  formParts = null;
                  throw new ContentNotFoundForPublishingException(
                      site, target.getName(), item.getPath());
                } else {
                  // Content does not exist - skip deploying file
                  continue;
                }
              }
            } catch (IOException err) {
              LOGGER.error(
                  "Error reading input stream for content at path: "
                      + item.getPath()
                      + " site: "
                      + item.getSite());
              if (_contentRepository.contentExists(site, item.getPath())) {
                baps = null;
                stringPart = null;
                filePart = null;
                formParts = null;
                throw new ContentNotFoundForPublishingException(
                    site, target.getName(), item.getPath());
              } else {
                // Content does not exist - skip deploying file
                continue;
              }
            }
            String fileName = _contentRepository.getFilename(site, item.getPath());

            byte[] byteArray = null;

            try {
              byteArray = IOUtils.toByteArray(input);
            } catch (IOException e) {
              LOGGER.error("Error while converting input stream to byte array", e);
              baps = null;
              stringPart = null;
              filePart = null;
              formParts = null;
              if (_contentRepository.contentExists(site, item.getPath())) {
                throw new ContentNotFoundForPublishingException(
                    site, target.getName(), item.getPath());
              } else {
                // Content does not exist - skip deploying file
                continue;
              }
            } finally {
              IOUtils.closeQuietly(input);
              input = null;
            }
            baps = new ByteArrayPartSource(fileName, byteArray);

            LOGGER.debug(
                "Create http request parameters for \"{0}\" , site \"{1}\"; publishing on target \"{2}\"",
                item.getPath(), item.getSite(), target.getName());
            int idx = item.getPath().lastIndexOf("/");
            String relativePath = item.getPath().substring(0, idx + 1) + fileName;
            stringPart =
                new StringPart(CONTENT_LOCATION_REQUEST_PARAMETER + cntFiles, relativePath);
            formParts.add(stringPart);
            filePart = new FilePart(CONTENT_FILE_REQUEST_PARAMETER + cntFiles, baps);
            formParts.add(filePart);
            if (item.getAction() == PublishingSyncItem.Action.MOVE) {
              if (item.getOldPath() != null
                  && !item.getOldPath().equalsIgnoreCase(item.getPath())) {
                LOGGER.debug(
                    "Add old path to be deleted for MOVE action (\"{0}\")", item.getOldPath());
                eventItem.setOldPath(item.getOldPath());
                if (sbDeletedFiles.length() > 0) {
                  sbDeletedFiles.append(",").append(item.getOldPath());
                } else {
                  sbDeletedFiles.append(item.getOldPath());
                }
                if (item.getOldPath().endsWith("/" + _indexFile)) {
                  sbDeletedFiles
                      .append(FILES_SEPARATOR)
                      .append(item.getOldPath().replace("/" + _indexFile, ""));
                }
              }
            }

            if (target.isSendMetadata()) {
              LOGGER.debug(
                  "Adding meta data for content \"{0}\" site \"{0}\"",
                  item.getPath(), item.getSite());
              InputStream metadataStream = null;
              try {
                metadataStream = _contentRepository.getMetadataStream(site, item.getPath());
                metadataPart =
                    new ByteArrayPartSource(
                        fileName + ".meta", IOUtils.toByteArray(metadataStream));
                formParts.add(
                    new FilePart(METADATA_FILE_REQUEST_PARAMETER + cntFiles, metadataPart));
              } catch (IOException e) {
                LOGGER.error("Error while creating input stream with content metadata", e);
                baps = null;
                stringPart = null;
                filePart = null;
                formParts = null;
              } finally {
                IOUtils.closeQuietly(metadataStream);
                metadataPart = null;
              }
            }
          }
          cntFiles++;
          eventItems.add(eventItem);
        }
      }

      if (sbDeletedFiles.length() > 0) {
        formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
      }
      LOGGER.debug(
          "Create http request to deploy bucket {0} for target {1}",
          bucketIndex + 1, target.getName());

      PostMethod postMethod = null;
      HttpClient client = null;
      try {

        LOGGER.debug("Create HTTP Post Method");
        postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        Part[] parts = new Part[formParts.size()];
        for (int i = 0; i < formParts.size(); i++) parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        client = new HttpClient();

        LOGGER.debug("Execute HTTP POST request \"{0}\"", postMethod.getURI());
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
          LOGGER.info(
              "Successfully deployed bucket number {0} on target {1}",
              bucketIndex + 1, target.getName());
        } else {
          LOGGER.error(
              "Deployment failed for bucket number {0} on target {1}. Deployment agent returned status {2}",
              bucketIndex + 1, target.getName(), HttpStatus.getStatusText(status));
          throw new UploadFailedException(site, target.getName(), target.getServerUrl());
        }
      } catch (HttpException e) {
        LOGGER.error(
            "Publish failed for target {0} due to http protocol exception", target.getName());
        throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
      } catch (IOException e) {
        LOGGER.error(
            "Publish failed for target {0} due to I/O (transport) exception", target.getName());
        throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
      } finally {
        LOGGER.debug("Release http connection and release resources");
        if (client != null) {
          HttpConnectionManager mgr = client.getHttpConnectionManager();
          if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();
          }
        }
        if (postMethod != null) {
          postMethod.releaseConnection();
          postMethod = null;
          client = null;
        }
        baps = null;
        stringPart = null;
        filePart = null;
        formParts = null;
      }
    }

    LOGGER.debug(
        "Publishing deployment event for target \"{0}\" with \"{1}\" items.",
        target.getName(), eventItems.size());
    _contentRepository.publishDeployEvent(target.getName(), eventItems);

    LOGGER.info("Deployment successful on target {0}", target.getName());
    LOGGER.debug(
        "Finished deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"",
        site, target.getName(), filteredItems.size());
  }
 public void componentUnregistered(JID componentJID) {
   // Remove stored information about this component
   clearspaces.remove(componentJID.getDomain());
 }
 /**
  * Returns true if a given JID belongs to a known Clearspace component domain.
  *
  * @param address Address to check.
  * @return True if the specified address is a Clearspace component.
  */
 public boolean isFromClearspace(JID address) {
   return clearspaces.contains(address.getDomain());
 }
  @Override
  public BatchHttpResult getConfigureInformationBatch(
      List<String> dataIds, String group, int timeout) {
    if (dataIds == null) {
      log.error("dataId list cannot be null,group=" + group);
      return new BatchHttpResult(HttpStatus.SC_BAD_REQUEST);
    }
    if (group == null) {
      group = Constants.DEFAULT_GROUP;
    }

    StringBuilder dataIdBuilder = new StringBuilder();
    for (String dataId : dataIds) {
      dataIdBuilder.append(dataId).append(Constants.LINE_SEPARATOR);
    }
    String dataIdStr = dataIdBuilder.toString();

    PostMethod post = new PostMethod(Constants.HTTP_URI_FILE_BATCH);
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout);

    BatchHttpResult response = null;
    try {
      NameValuePair dataIdValue = new NameValuePair("dataIds", dataIdStr);
      NameValuePair groupValue = new NameValuePair("group", group);

      post.setRequestBody(new NameValuePair[] {dataIdValue, groupValue});

      httpClient
          .getHostConfiguration()
          .setHost(
              diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
              this.diamondConfigure.getPort());
      int status = httpClient.executeMethod(post);
      String responseMsg = post.getResponseBodyAsString();

      if (status == HttpStatus.SC_OK) {
        String json = null;
        try {
          json = responseMsg;

          List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
          Object resultObj =
              JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {});
          if (!(resultObj instanceof List<?>)) {
            throw new RuntimeException(
                "batch query deserialize type error, not list, json=" + json);
          }
          List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
          for (ConfigInfoEx configInfoEx : resultList) {
            configInfoExList.add(configInfoEx);
          }

          response = new BatchHttpResult(configInfoExList);
          log.info(
              "batch query success,dataIds=" + dataIdStr + ",group=" + group + ",json=" + json);
        } catch (Exception e) {
          response = new BatchHttpResult(Constants.BATCH_OP_ERROR);
          log.error(
              "batch query deserialize error,dataIdStr="
                  + dataIdStr
                  + ",group="
                  + group
                  + ",json="
                  + json,
              e);
        }

      } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
        response = new BatchHttpResult(HttpStatus.SC_REQUEST_TIMEOUT);
        log.error(
            "batch query timeout, socket timeout(ms):"
                + timeout
                + ",dataIds="
                + dataIdStr
                + ",group="
                + group);
      } else {
        response = new BatchHttpResult(status);
        log.error(
            "batch query fail, status:"
                + status
                + ", response:"
                + responseMsg
                + ",dataIds="
                + dataIdStr
                + ",group="
                + group);
      }
    } catch (HttpException e) {
      response = new BatchHttpResult(Constants.BATCH_HTTP_EXCEPTION);
      log.error("batch query http exception,dataIds=" + dataIdStr + ",group=" + group, e);
    } catch (IOException e) {
      response = new BatchHttpResult(Constants.BATCH_IO_EXCEPTION);
      log.error("batch query io exception, dataIds=" + dataIdStr + ",group=" + group, e);
    } finally {
      post.releaseConnection();
    }

    return response;
  }
Beispiel #13
0
 private void QueriesCmbItemStateChanged(
     java.awt.event.ItemEvent evt) { // GEN-FIRST:event_QueriesCmbItemStateChanged
   // TODO add your handling code here:
   int iQueryNumber = QueriesCmb.getSelectedIndex();
   SparqlTxtArea.setText(queryList.get(iQueryNumber).toString());
 } // GEN-LAST:event_QueriesCmbItemStateChanged
  protected Weather deserializeWeatherResult(InputStream inputStream, TemperatureUnit unit)
      throws JAXBException, ParseException {
    JAXBContext jaxbContext = JAXBContext.newInstance(WeatherData.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    WeatherData data = (WeatherData) unmarshaller.unmarshal(inputStream);

    Weather weather = new Weather();

    Current current = new Current();
    current.setCondition(data.getCondition().getDescription());
    current.setHumidity(data.getCondition().getHumidity());
    current.setPressure(data.getCondition().getPressure());
    current.setWindDirection(data.getCondition().getWindDir());

    if (data.getCondition().getWeatherIconUrl() != null
        && data.getCondition().getWeatherIconUrl().contains("night")) {
      current.setImgName(
          imageMapping.getProperty("image.night." + data.getCondition().getWeatherCode()));
    } else {
      current.setImgName(
          imageMapping.getProperty("image.day." + data.getCondition().getWeatherCode()));
    }

    switch (unit) {
      case C:
        current.setTemperature(data.getCondition().getTempC());
        current.setWindSpeed(data.getCondition().getSpeedKmph());
        weather.setTemperatureUnit("C");
        weather.setWindUnit("kmph");
        weather.setPressureUnit("mb");
        break;
      default:
        current.setTemperature(data.getCondition().getTempF());
        current.setWindSpeed(data.getCondition().getSpeedMiles());
        weather.setTemperatureUnit("F");
        weather.setWindUnit("mi");
        weather.setPressureUnit("mb");
    }
    weather.setCurrentWeather(current);

    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN);
    SimpleDateFormat dayFormat = new SimpleDateFormat(DAY_PATTERN);

    List<Forecast> forecasts = new ArrayList<Forecast>();
    for (WeatherForecast f : data.getForecasts()) {
      Forecast forecast = new Forecast();
      forecast.setCondition(f.getDescription());

      if (f.getIconUrl() != null && f.getIconUrl().contains("night")) {
        forecast.setImgName(imageMapping.getProperty("image.night." + f.getWeatherCode()));
      } else {
        forecast.setImgName(imageMapping.getProperty("image.day." + f.getWeatherCode()));
      }

      Date date = dateFormat.parse(f.getDate());
      forecast.setDay(dayFormat.format(date));

      switch (unit) {
        case C:
          forecast.setHighTemperature(f.getTempMaxC());
          forecast.setLowTemperature(f.getTempMinC());
          break;
        default:
          forecast.setHighTemperature(f.getTempMaxF());
          forecast.setLowTemperature(f.getTempMinF());
      }
      forecasts.add(forecast);
    }
    weather.setForecast(forecasts);

    return weather;
  }