public static void syncWorkspaceFormatFromMaster() {
    Hudson h = Hudson.getInstance();
    if (h != null)
      workspaceFormat =
          h.getDescriptorByType(SubversionSCM.DescriptorImpl.class).getWorkspaceFormat();
    else {
      Channel c = Channel.current();
      if (c != null) // just being defensive. cannot be null.
      try {
          workspaceFormat =
              c.call(
                  new Callable<Integer, RuntimeException>() {
                    private static final long serialVersionUID = 6494337549896104453L;

                    public Integer call() {
                      return Hudson.getInstance()
                          .getDescriptorByType(SubversionSCM.DescriptorImpl.class)
                          .getWorkspaceFormat();
                    }
                  });
        } catch (IOException e) {
          LOGGER.log(Level.WARNING, "Failed to retrieve Subversion workspace format", e);
        } catch (InterruptedException e) {
          LOGGER.log(Level.WARNING, "Failed to retrieve Subversion workspace format", e);
        }
    }
  }
 private void replaceContent(IFile f, String content) {
   try {
     f.delete(true, new NullProgressMonitor());
   } catch (CoreException ce) {
     LOGGER.log(Level.WARNING, ce.getMessage(), ce);
   }
   InputStream is = null;
   try {
     is = EAPFromWSDLTest.class.getResourceAsStream(content);
     f.create(is, true, new NullProgressMonitor());
   } catch (CoreException ce) {
     LOGGER.log(Level.WARNING, ce.getMessage(), ce);
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException ioe) {
         // ignore
       }
     }
   }
   try {
     ResourcesPlugin.getWorkspace()
         .getRoot()
         .refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, new NullProgressMonitor());
   } catch (CoreException e) {
     LOGGER.log(Level.WARNING, e.getMessage(), e);
   }
   util.waitForNonIgnoredJobs();
 }
 protected boolean verify(String hostname, SSLSession session, boolean interactive) {
   LOGGER.log(
       Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first");
   // if the default verifier accepts the hostname, we are done
   if (defaultVerifier.verify(hostname, session)) {
     LOGGER.log(Level.FINE, "default verifier accepted " + hostname);
     return true;
   }
   // otherwise, we check if the hostname is an alias for this cert in our keystore
   try {
     X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
     // Log.d(TAG, "cert: " + cert);
     if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) {
       LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting.");
       return true;
     } else {
       LOGGER.log(
           Level.FINE, "server " + hostname + " provided wrong certificate, asking user.");
       if (interactive) {
         return interactHostname(cert, hostname);
       } else {
         return false;
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     return false;
   }
 }
예제 #4
0
  /** {@inheritDoc } */
  @Override
  protected Map<String, String> toString(final Envelope env) {
    final Map<String, String> map = new HashMap<String, String>();
    final StringBuilder sb = new StringBuilder();
    final double minx = env.getMinimum(0);
    final double maxx = env.getMaximum(0);
    final double miny = env.getMinimum(1);
    final double maxy = env.getMaximum(1);
    sb.append(minx).append(',').append(miny).append(',').append(maxx).append(',').append(maxy);

    map.put("BBOX", sb.toString());

    try {
      String code = IdentifiedObjects.lookupIdentifier(env.getCoordinateReferenceSystem(), true);
      if (code == null) {
        code =
            IdentifiedObjects.lookupIdentifier(
                CRSUtilities.getCRS2D(env.getCoordinateReferenceSystem()), true);
      }
      map.put("CRS", code);
    } catch (FactoryException ex) {
      LOGGER.log(Level.WARNING, null, ex);
    } catch (TransformException ex) {
      LOGGER.log(Level.WARNING, null, ex);
    }

    encodeNDParameters(env, map);

    return map;
  }
예제 #5
0
    private boolean runPolling() {
      try {
        // to make sure that the log file contains up-to-date text,
        // don't do buffering.
        StreamTaskListener listener = new StreamTaskListener(getLogFile());

        try {
          PrintStream logger = listener.getLogger();
          long start = System.currentTimeMillis();
          logger.println("Started on " + DateFormat.getDateTimeInstance().format(new Date()));
          boolean result = job.poll(listener).hasChanges();
          logger.println(
              "Done. Took " + Util.getTimeSpanString(System.currentTimeMillis() - start));
          if (result) logger.println("Changes found");
          else logger.println("No changes");
          return result;
        } catch (Error e) {
          e.printStackTrace(listener.error("Failed to record SCM polling"));
          LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
          throw e;
        } catch (RuntimeException e) {
          e.printStackTrace(listener.error("Failed to record SCM polling"));
          LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
          throw e;
        } finally {
          listener.close();
        }
      } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failed to record SCM polling", e);
        return false;
      }
    }
예제 #6
0
		@EventHandler(priority = EventPriority.HIGHEST)
		public void onPlayerJoin(final PlayerJoinEvent event)
		{
			final User user = ess.getUser(event.getPlayer());
			if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
			{
				return;
			}

			try
			{
				sendToJail(user, user.getJail());
			}
			catch (Exception ex)
			{
				if (ess.getSettings().isDebug())
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
				}
				else
				{
					LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
				}
			}
			user.sendMessage(_("jailMessage"));
		}
예제 #7
0
    public void run() {
      try {
        while (selectable) {
          // The select() will be woke up if some new connection
          // have occurred, or if the selector has been explicitly
          // woke up
          if (selector.select() > 0) {
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();

            while (selectedKeys.hasNext()) {
              SelectionKey key = selectedKeys.next();
              selectedKeys.remove();

              if (key.isValid()) {
                EventHandler processor = ((EventHandler) key.attachment());
                processor.process(key);
              }
            }
          }
        }

      } catch (IOException ioe) {
        LOGGER.log(Level.WARNING, "Error while waiting for events", ioe);
      } finally {
        if (selectable) {
          LOGGER.log(
              Level.WARNING, "Unexpected death of thread {0}", Thread.currentThread().getName());
        } else {
          LOGGER.log(
              Level.FINE,
              "Thread {0} termination initiated by call to AgentServer.close()",
              Thread.currentThread().getName());
        }
      }
    }
예제 #8
0
  /** Called when a module build that corresponds to this module set build has completed. */
  /* package */ void notifyModuleBuild(IvyBuild newBuild) {
    try {
      // update module set build number
      getParent().updateNextBuildNumber();

      // update actions
      Map<IvyModule, List<IvyBuild>> moduleBuilds = getModuleBuilds();

      // actions need to be replaced atomically especially
      // given that two builds might complete simultaneously.
      synchronized (this) {
        boolean modified = false;

        List<Action> actions = getActions();
        Set<Class<? extends AggregatableAction>> individuals =
            new HashSet<Class<? extends AggregatableAction>>();
        for (Action a : actions) {
          if (a instanceof IvyAggregatedReport) {
            IvyAggregatedReport mar = (IvyAggregatedReport) a;
            mar.update(moduleBuilds, newBuild);
            individuals.add(mar.getIndividualActionType());
            modified = true;
          }
        }

        // see if the new build has any new aggregatable action that we
        // haven't seen.
        for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) {
          if (individuals.add(aa.getClass())) {
            // new AggregatableAction
            IvyAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds);
            mar.update(moduleBuilds, newBuild);
            actions.add(mar);
            modified = true;
          }
        }

        if (modified) {
          save();
          getProject().updateTransientActions();
        }
      }

      // symlink to this module build
      String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName();
      Util.createSymlink(
          getRootDir(),
          "../../modules/" + moduleFsName + "/builds/" + newBuild.getId() /*ugly!*/,
          moduleFsName,
          StreamTaskListener.NULL);
    } catch (IOException e) {
      LOGGER.log(Level.WARNING, "Failed to update " + this, e);
    } catch (InterruptedException e) {
      LOGGER.log(Level.WARNING, "Failed to update " + this, e);
    }
  }
  protected UserDetails retrieveUser(
      String username, UsernamePasswordAuthenticationToken authentication)
      throws AuthenticationException {
    try {
      // this is more seriously error, indicating a failure to search
      List<BadCredentialsException> errors = new ArrayList<BadCredentialsException>();

      // this is lesser error, in that we searched and the user was not found
      List<UsernameNotFoundException> notFound = new ArrayList<UsernameNotFoundException>();

      for (String domainName : domainNames) {
        try {
          return retrieveUser(username, authentication, domainName);
        } catch (UsernameNotFoundException e) {
          notFound.add(e);
        } catch (BadCredentialsException bce) {
          LOGGER.log(
              Level.WARNING,
              "Credential exception trying to authenticate against " + domainName + " domain",
              bce);
          errors.add(bce);
        }
      }

      switch (errors.size()) {
        case 0:
          break; // fall through
        case 1:
          throw errors.get(0); // preserve the original exception
        default:
          throw new MultiCauseBadCredentialsException(
              "Either no such user '" + username + "' or incorrect password", errors);
      }

      if (notFound.size() == 1) throw notFound.get(0); // preserve the original exception

      if (!Util.filter(notFound, UserMayOrMayNotExistException.class).isEmpty())
        // if one domain responds with UserMayOrMayNotExistException, then it might actually exist
        // there,
        // so our response will be "can't tell"
        throw new MultiCauseUserNotFoundException(
            "We can't tell if the user exists or not: " + username, notFound);

      if (!notFound.isEmpty())
        throw new MultiCauseUserNotFoundException("No such user: "******"no domain is configured");
    } catch (AuthenticationException e) {
      LOGGER.log(Level.FINE, "Failed toretrieve user " + username, e);
      throw e;
    }
  }
예제 #10
0
  void deleteTask(String taskArn) {
    final AmazonECSClient client = getAmazonECSClient();

    LOGGER.log(Level.INFO, "Delete ECS Slave task: {0}", taskArn);
    try {
      client.stopTask(new StopTaskRequest().withTask(taskArn));
    } catch (ClientException e) {
      LOGGER.log(
          Level.SEVERE,
          "Couldn't stop task arn " + taskArn + " caught exception: " + e.getMessage(),
          e);
    }
  }
예제 #11
0
  protected void handle(
      final String pathInContext,
      final String pathParams,
      final HttpRequest request,
      final HttpResponse response,
      final HttpFields trailer)
      throws IOException {

    NewObjectIdentifier identifier;
    try {
      identifier = getRequestIdentifier(request, response, trailer);
    } catch (IllegalArgumentException e) {
      // already sent error reply in superclass
      return;
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("deleting object with id " + identifier);
    }

    try {
      handleDelete(request, response, identifier);

    } catch (NoSuchObjectException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "delete failed on NoSuchObjectException.", e);
      }
      sendError(response, trailer, HttpResponse.__404_Not_Found, e.getMessage());
    } catch (ObjectLostException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "delete failed on ObjectLostException.", e);
      }
      sendError(response, trailer, HttpResponse.__410_Gone, e.getMessage());
    } catch (ArchiveException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "delete failed on ArchiveException.", e);
      }
      sendError(response, trailer, HttpResponse.__400_Bad_Request, e.getMessage());
    } catch (InternalException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "delete failed on InternalException.", e);
      }
      sendError(response, trailer, HttpResponse.__500_Internal_Server_Error, e.getMessage());
    } catch (IllegalArgumentException e) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "delete failed on IllegalArgumentException.", e);
      }
      sendError(response, trailer, HttpResponse.__400_Bad_Request, e.getMessage());
    }
  }
예제 #12
0
  /**
   * Check for the count of EC2 slaves and determine if a new slave can be added. Takes into account
   * both what Amazon reports as well as an internal count of slaves currently being "provisioned".
   * Check for the count of EC2 slaves and determine if a new slave can be added. Takes into account
   * both what Amazon reports as well as an internal count of slaves currently being "provisioned".
   *
   * @param templateDesc
   */
  private boolean addProvisionedSlave(String ami, int amiCap, String templateDesc)
      throws AmazonClientException {
    int estimatedTotalSlaves = countCurrentEC2Slaves(null, null);
    int estimatedAmiSlaves = countCurrentEC2Slaves(ami, templateDesc);

    synchronized (provisioningAmis) {
      int currentProvisioning;

      for (int amiCount : provisioningAmis.values()) {
        estimatedTotalSlaves += amiCount;
      }
      try {
        currentProvisioning = provisioningAmis.get(ami);
      } catch (NullPointerException npe) {
        currentProvisioning = 0;
      }

      estimatedAmiSlaves += currentProvisioning;

      if (estimatedTotalSlaves >= instanceCap) {
        LOGGER.log(
            Level.INFO, "Total instance cap of " + instanceCap + " reached, not provisioning.");
        return false; // maxed out
      }

      if (estimatedAmiSlaves >= amiCap) {
        LOGGER.log(
            Level.INFO,
            "AMI Instance cap of " + amiCap + " reached for ami " + ami + ", not provisioning.");
        return false; // maxed out
      }

      LOGGER.log(
          Level.INFO,
          "Provisioning for AMI "
              + ami
              + "; "
              + "Estimated number of total slaves: "
              + String.valueOf(estimatedTotalSlaves)
              + "; "
              + "Estimated number of slaves for ami "
              + ami
              + ": "
              + String.valueOf(estimatedAmiSlaves));

      provisioningAmis.put(ami, currentProvisioning + 1);
      return true;
    }
  }
  /** Performs all monitoring concurrently. */
  @Override
  protected Map<Computer, T> monitor() throws InterruptedException {
    Map<Computer, Future<T>> futures = new HashMap<Computer, Future<T>>();

    for (Computer c : Jenkins.getInstance().getComputers()) {
      try {
        VirtualChannel ch = c.getChannel();
        futures.put(c, null); // sentinel value
        if (ch != null) {
          Callable<T, ?> cc = createCallable(c);
          if (cc != null) futures.put(c, ch.callAsync(cc));
        }
      } catch (RuntimeException e) {
        LOGGER.log(
            WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), e);
      } catch (IOException e) {
        LOGGER.log(
            WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), e);
      }
    }

    final long now = System.currentTimeMillis();
    final long end = now + getMonitoringTimeOut();

    final Map<Computer, T> data = new HashMap<Computer, T>();

    for (Entry<Computer, Future<T>> e : futures.entrySet()) {
      Computer c = e.getKey();
      Future<T> f = futures.get(c);
      data.put(c, null); // sentinel value

      if (f != null) {
        try {
          data.put(c, f.get(Math.max(0, end - System.currentTimeMillis()), MILLISECONDS));
        } catch (RuntimeException x) {
          LOGGER.log(
              WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
        } catch (ExecutionException x) {
          LOGGER.log(
              WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
        } catch (TimeoutException x) {
          LOGGER.log(
              WARNING, "Failed to monitor " + c.getDisplayName() + " for " + getDisplayName(), x);
        }
      }
    }

    return data;
  }
  @Override
  public void mouseMoved(final MouseEvent e) {
    if (coords.size() > 2) {
      if (justCreated) {
        coords.remove(coords.size() - 1);
        coords.remove(coords.size() - 1);
        coords.add(helper.toCoord(e.getX(), e.getY()));
        coords.add(helper.toCoord(e.getX(), e.getY()));
      } else {
        coords.remove(coords.size() - 1);
        coords.add(helper.toCoord(e.getX(), e.getY()));
      }

      erase = EditionHelper.createPolygon(coords);
      final Geometry line = EditionHelper.createLinearRing(coords);
      geometry =
          (multipolygon) ? EditionHelper.createMultiPolygon(subGeometries) : subGeometries.get(0);
      try {
        geometry = geometry.difference(erase);
      } catch (TopologyException ex) {
        LOGGER.log(Level.INFO, ex.getLocalizedMessage());
      }
      decoration.setGeometries(UnmodifiableArrayList.wrap(new Geometry[] {geometry, line}));
      return;
    }
    super.mouseMoved(e);
  }
예제 #15
0
 public void run() {
   String threadName = Thread.currentThread().getName();
   Thread.currentThread().setName("SCM polling for " + job);
   try {
     startTime = System.currentTimeMillis();
     if (runPolling()) {
       AbstractProject p = job.asProject();
       String name = " #" + p.getNextBuildNumber();
       SCMTriggerCause cause;
       try {
         cause = new SCMTriggerCause(getLogFile());
       } catch (IOException e) {
         LOGGER.log(WARNING, "Failed to parse the polling log", e);
         cause = new SCMTriggerCause();
       }
       if (p.scheduleBuild(p.getQuietPeriod(), cause, additionalActions)) {
         LOGGER.info("SCM changes detected in " + job.getName() + ". Triggering " + name);
       } else {
         LOGGER.info(
             "SCM changes detected in " + job.getName() + ". Job is already in the queue");
       }
     }
   } finally {
     Thread.currentThread().setName(threadName);
   }
 }
예제 #16
0
 /* (non-Javadoc)
  * @see java.lang.Thread#run()
  */
 public void run() {
   try {
     LOGGER.info("Start " + getName() + ", (running = " + running + ")");
     while (running) {
       try {
         work();
       } catch (Throwable t) {
         if (running)
           LOGGER.log(
               Level.WARNING,
               "Exception \"" + t + "\" in thread " + getName() + ": running=" + running,
               t);
         else
           LOGGER.info(
               "Exception \""
                   + t
                   + "\" in thread "
                   + getName()
                   + " has successfully stopped socket thread");
       }
     }
   } finally {
     LOGGER.info(getName() + " has terminated (running = " + running + ")");
   }
 }
    public <T> List<ExtensionComponent<T>> findComponents(Class<T> type, Hudson hudson) {

        List<ExtensionFinder> finders;
        if (type==ExtensionFinder.class) {
            // Avoid infinite recursion of using ExtensionFinders to find ExtensionFinders
            finders = Collections.<ExtensionFinder>singletonList(new ExtensionFinder.Sezpoz());
        } else {
            finders = hudson.getExtensionList(ExtensionFinder.class);
        }

        /**
         * See {@link ExtensionFinder#scout(Class, Hudson)} for the dead lock issue and what this does.
         */
        if (LOGGER.isLoggable(Level.FINER))
            LOGGER.log(Level.FINER,"Scout-loading ExtensionList: "+type, new Throwable());
        for (ExtensionFinder finder : finders) {
            finder.scout(type, hudson);
        }

        List<ExtensionComponent<T>> r = new ArrayList<ExtensionComponent<T>>();
        for (ExtensionFinder finder : finders) {
            try {
                r.addAll(finder._find(type, hudson));
            } catch (AbstractMethodError e) {
                // backward compatibility
                for (T t : finder.findExtensions(type, hudson))
                    r.add(new ExtensionComponent<T>(t));
            }
        }
        return r;
    }
예제 #18
0
  private void scanFile(File log) {
    LOGGER.fine("Scanning " + log);

    BufferedReader r = null;
    try {
      r = new BufferedReader(new FileReader(log));

      if (!findHeader(r)) return;

      // we should find a memory mapped file for secret.key
      String secretKey = getSecretKeyFile().getAbsolutePath();

      String line;
      while ((line = r.readLine()) != null) {
        if (line.contains(secretKey)) {
          files.add(new HsErrPidFile(this, log));
          return;
        }
      }
    } catch (IOException e) {
      // not a big enough deal.
      LOGGER.log(Level.FINE, "Failed to parse hs_err_pid file: " + log, e);
    } finally {
      IOUtils.closeQuietly(r);
    }
  }
예제 #19
0
  public HsErrPidList() {
    if (Functions.getIsUnitTest()) {
      return;
    }
    try {
      FileChannel ch = new FileInputStream(getSecretKeyFile()).getChannel();
      map = ch.map(MapMode.READ_ONLY, 0, 1);

      scan("./hs_err_pid%p.log");
      if (Functions.isWindows()) {
        File dir = Kernel32Utils.getTempDir();
        if (dir != null) {
          scan(dir.getPath() + "\\hs_err_pid%p.log");
        }
      } else {
        scan("/tmp/hs_err_pid%p.log");
      }
      // on different platforms, rules about the default locations are a lot more subtle.

      // check our arguments in the very end since this might fail on some platforms
      JavaVMArguments args = JavaVMArguments.current();
      for (String a : args) {
        // see http://www.oracle.com/technetwork/java/javase/felog-138657.html
        if (a.startsWith(ERROR_FILE_OPTION)) {
          scan(a.substring(ERROR_FILE_OPTION.length()));
        }
      }
    } catch (UnsupportedOperationException e) {
      // ignore
    } catch (Throwable e) {
      LOGGER.log(Level.WARNING, "Failed to list up hs_err_pid files", e);
    }
  }
 private void closeQuietly(DirContext context) {
   try {
     if (context != null) context.close();
   } catch (NamingException e) {
     LOGGER.log(Level.INFO, "Failed to close DirContext: " + context, e);
   }
 }
예제 #21
0
    protected FormValidation doTestConnection(
        URL ec2endpoint,
        boolean useInstanceProfileForCredentials,
        String accessId,
        String secretKey,
        String privateKey)
        throws IOException, ServletException {
      try {
        AWSCredentialsProvider credentialsProvider =
            createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
        AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
        ec2.describeInstances();

        if (privateKey == null)
          return FormValidation.error(
              "Private key is not specified. Click 'Generate Key' to generate one.");

        if (privateKey.trim().length() > 0) {
          // check if this key exists
          EC2PrivateKey pk = new EC2PrivateKey(privateKey);
          if (pk.find(ec2) == null)
            return FormValidation.error(
                "The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
                    + pk.getFingerprint()
                    + ")");
        }

        return FormValidation.ok(Messages.EC2Cloud_Success());
      } catch (AmazonClientException e) {
        LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
        return FormValidation.error(e.getMessage());
      }
    }
예제 #22
0
 public void run() {
   try {
     parser = parser().parse();
   } catch (Throwable t) {
     LOGGER.log(Level.WARNING, "LD test failed", t);
   }
 }
    @Override
    public void onComplete(NbGradleModel model, Throwable error) {
      loadedAtLeastOnceSignal.signal();

      boolean hasChanged = false;
      if (model != null) {
        NbGradleModelRef newModel = new NbGradleModelRef(model);
        NbGradleModelRef lastModel = currentModelRef.getAndSet(newModel);
        hasChanged = !lastModel.isSameModel(newModel);
      }

      if (error != null) {
        ProjectInfo.Entry entry =
            new ProjectInfo.Entry(ProjectInfo.Kind.ERROR, NbStrings.getErrorLoadingProject(error));
        getLoadErrorRef().setInfo(new ProjectInfo(Collections.singleton(entry)));
        LOGGER.log(Level.INFO, "Error while loading the project model.", error);
        displayError(NbStrings.getProjectLoadFailure(name), error, true);
      } else {
        getLoadErrorRef().setInfo(null);
      }

      if (hasChanged) {
        if (model == null) {
          notifyEmptyModelChange();
        } else {
          notifyModelChange(model);
        }
      }
    }
  public URL lookupBpmPlatformXmlFromCatalinaConfDirectory() {
    // read file from CATALINA_BASE if set, otherwise CATALINA_HOME directory.
    String catalinaHome = System.getProperty(CATALINA_BASE);
    if (catalinaHome == null) {
      catalinaHome = System.getProperty(CATALINA_HOME);
    }

    String bpmPlatformFileLocation =
        catalinaHome + File.separator + "conf" + File.separator + BPM_PLATFORM_XML_FILE;

    try {
      URL fileLocation = checkValidFileLocation(bpmPlatformFileLocation);

      if (fileLocation != null) {
        LOGGER.log(
            Level.INFO,
            "Found camunda bpm platform configuration in CATALINA_BASE/CATALINA_HOME conf directory ["
                + bpmPlatformFileLocation
                + "] at "
                + fileLocation.toString());
      }

      return fileLocation;
    } catch (MalformedURLException e) {
      throw new ProcessEngineException(
          "'"
              + bpmPlatformFileLocation
              + "' is not a valid camunda bpm platform configuration resource location.",
          e);
    }
  }
예제 #25
0
파일: User.java 프로젝트: nahi/jenkins
  /** Loads the other data from disk if it's available. */
  private synchronized void load() {
    properties.clear();

    XmlFile config = getConfigFile();
    try {
      if (config.exists()) config.unmarshal(this);
    } catch (IOException e) {
      LOGGER.log(Level.SEVERE, "Failed to load " + config, e);
    }

    // remove nulls that have failed to load
    for (Iterator<UserProperty> itr = properties.iterator(); itr.hasNext(); ) {
      if (itr.next() == null) itr.remove();
    }

    // allocate default instances if needed.
    // doing so after load makes sure that newly added user properties do get reflected
    for (UserPropertyDescriptor d : UserProperty.all()) {
      if (getProperty(d.clazz) == null) {
        UserProperty up = d.newInstance(this);
        if (up != null) properties.add(up);
      }
    }

    for (UserProperty p : properties) p.setUser(this);
  }
예제 #26
0
  /** Retrieves the currently active singleton instance of {@link ConfidentialStore}. */
  public static @Nonnull ConfidentialStore get() {
    if (TEST != null) return TEST.get();

    Jenkins j = Jenkins.getInstance();
    if (j == null) {
      throw new IllegalStateException(
          "cannot initialize confidential key store until Jenkins has started");
    }
    Lookup lookup = j.lookup;
    ConfidentialStore cs = lookup.get(ConfidentialStore.class);
    if (cs == null) {
      try {
        List<ConfidentialStore> r =
            (List)
                Service.loadInstances(
                    ConfidentialStore.class.getClassLoader(), ConfidentialStore.class);
        if (!r.isEmpty()) cs = r.get(0);
      } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to list up ConfidentialStore implementations", e);
        // fall through
      }

      if (cs == null)
        try {
          cs = new DefaultConfidentialStore();
        } catch (Exception e) {
          // if it's still null, bail out
          throw new Error(e);
        }

      cs = lookup.setIfNull(ConfidentialStore.class, cs);
    }
    return cs;
  }
예제 #27
0
    /** PENDING javadocs */
    public void run() {

      assert (monitors != null);
      boolean reloaded = false;
      for (Iterator<Monitor> i = monitors.iterator(); i.hasNext(); ) {
        Monitor m = i.next();
        try {
          if (m.hasBeenModified()) {
            if (!reloaded) {
              reloaded = true;
            }
          }
        } catch (IOException ioe) {
          if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.severe(
                "Unable to access url "
                    + m.uri.toString()
                    + ".  Monitoring for this resource will no longer occur.");
          }
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, ioe.toString(), ioe);
          }
          i.remove();
        }
      }
      if (reloaded) {
        reload(sc);
      }
    }
예제 #28
0
  public final boolean loadFrom(File source) {
    if (source == null) {
      throw new IllegalArgumentException(
          "The file must not be null in order to load the reflected!");
    }
    if (source.exists()) {
      I in = null;
      try {

        in = getCodec().newInput(source);
        this.loadFrom(in);
      } catch (IOException e) {
        throw new IllegalArgumentException("File to load from cannot be accessed!", e);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException e) {
            Reflector.LOGGER.log(WARNING, "Failed to close the input stream!", e);
          }
        }
      }
      this.onLoaded(source);
      return true;
    }
    LOGGER.log(Level.INFO, "Could not load reflected from file! Using default...");
    return false;
  }
예제 #29
0
  static List<SRS> buildCodeList() {
    long t = System.currentTimeMillis();
    Set<String> codes = CRS.getSupportedCodes("EPSG");

    try {
      codes.addAll(customFactory.getAuthorityCodes(CoordinateReferenceSystem.class));
    } catch (FactoryException e) {
      LOGGER.log(Level.WARNING, "Error occurred while trying to gather custom CRS codes", e);
    }

    // make a set with each code
    Set<SRS> idSet = new HashSet<SRS>();
    for (String code : codes) {
      // make sure we're using just the non prefix part
      String id = code.substring(code.indexOf(':') + 1);
      // avoid WGS84DD and eventual friends, as we're still not able to handle them,
      // if they are chosen exceptions arises everywhere
      if (NUMERIC.matcher(id).matches()) {
        idSet.add(new SRS(id));
      }
    }

    List<SRS> srsList = new ArrayList<SRS>(idSet);
    Collections.sort(srsList, new CodeComparator()); // sort to get them in order
    return srsList;
  }
예제 #30
0
  /** Creates a hudson.PluginStrategy, looking at the corresponding system property. */
  protected PluginStrategy createPluginStrategy() {
    String strategyName = System.getProperty(PluginStrategy.class.getName());
    if (strategyName != null) {
      try {
        Class<?> klazz = getClass().getClassLoader().loadClass(strategyName);
        Object strategy = klazz.getConstructor(PluginManager.class).newInstance(this);
        if (strategy instanceof PluginStrategy) {
          LOGGER.info("Plugin strategy: " + strategyName);
          return (PluginStrategy) strategy;
        } else {
          LOGGER.warning(
              "Plugin strategy (" + strategyName + ") is not an instance of hudson.PluginStrategy");
        }
      } catch (ClassNotFoundException e) {
        LOGGER.warning("Plugin strategy class not found: " + strategyName);
      } catch (Exception e) {
        LOGGER.log(
            WARNING,
            "Could not instantiate plugin strategy: "
                + strategyName
                + ". Falling back to ClassicPluginStrategy",
            e);
      }
      LOGGER.info("Falling back to ClassicPluginStrategy");
    }

    // default and fallback
    return new ClassicPluginStrategy(this);
  }