public void log() { System.out.println("ResourceManager.log"); for (String path : resources.keySet()) { Resource resource = resources.get(path); System.out.format("%s->%d\n", path, resource.getRefs()); } }
private void copy(File workspaceDir, InputStream in, Pattern glob, boolean overwrite) throws Exception { Jar jar = new Jar("dot", in); try { for (Entry<String, Resource> e : jar.getResources().entrySet()) { String path = e.getKey(); bnd.trace("path %s", path); if (glob != null && !glob.matcher(path).matches()) continue; Resource r = e.getValue(); File dest = Processor.getFile(workspaceDir, path); if (overwrite || !dest.isFile() || dest.lastModified() < r.lastModified() || r.lastModified() <= 0) { bnd.trace("copy %s to %s", path, dest); File dp = dest.getParentFile(); if (!dp.exists() && !dp.mkdirs()) { throw new IOException("Could not create directory " + dp); } IO.copy(r.openInputStream(), dest); } } } finally { jar.close(); } }
/** * @native(docker) Scenario: Configure a job with over ssh publishing Given I have installed the * "publish-over-ssh" plugin And a docker fixture "sshd" And a job When I configure docker * fixture as SSH site And I configure the job to use a unsecure keyfile without passphrase * And I copy resource "scp_plugin/lorem-ipsum-scp.txt" into workspace And I publish * "lorem-ipsum-scp.txt" with SSH plugin And I save the job And I build the job Then the build * should succeed And SSH plugin should have published "lorem-ipsum-scp.txt" on docker fixture */ @Test public void ssh_key_path_and_no_password_publishing() throws IOException, InterruptedException { SshdContainer sshd = docker.start(SshdContainer.class); Resource cp_file = resource(resourceFilePath); File sshFile = sshd.getPrivateKey(); FreeStyleJob j = jenkins.jobs.create(); jenkins.configure(); this.commonConfigKeyFile(sshFile, false); InstanceSite is = this.instanceConfig(sshd); this.advancedConfigAllowExec(is, sshd); // delete button // is.delete.click(); // validate input // is.validate.click(); jenkins.save(); this.configureJobNoExec(j, cp_file); j.save(); j.startBuild().shouldSucceed(); sshd.cp(tempCopyFile, tempPath); assertThat( FileUtils.readFileToString(new File(tempCopyFile)), CoreMatchers.is(cp_file.asText())); }
/** * Method to check current status of the service and logged in user. * * <p>okay: true | false authenticated: true | false epersonEMAIL: [email protected] epersonNAME: * John Doe * * @param headers Request header which contains the header named "rest-dspace-token" containing * the token as value. * @return status the Status object with information about REST API * @throws UnsupportedEncodingException The Character Encoding is not supported. */ @GET @Path("/status") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Status status(@Context HttpHeaders headers) throws UnsupportedEncodingException { org.dspace.core.Context context = null; try { context = Resource.createContext(); EPerson ePerson = context.getCurrentUser(); if (ePerson != null) { // DB EPerson needed since token won't have full info, need context EPerson dbEPerson = epersonService.findByEmail(context, ePerson.getEmail()); Status status = new Status(dbEPerson.getEmail(), dbEPerson.getFullName()); return status; } } catch (ContextException e) { Resource.processException("Status context error: " + e.getMessage(), context); } catch (SQLException e) { Resource.processException("Status eperson db lookup error: " + e.getMessage(), context); } finally { context.abort(); } // fallback status, unauth return new Status(); }
private static void main2(String[] args) { Config.cmdline(args); try { javabughack(); } catch (InterruptedException e) { return; } setupres(); MainFrame f = new MainFrame(null); if (Utils.getprefb("fullscreen", false)) f.setfs(); f.mt.start(); try { f.mt.join(); } catch (InterruptedException e) { f.g.interrupt(); return; } dumplist(Resource.remote().loadwaited(), Config.loadwaited); dumplist(Resource.remote().cached(), Config.allused); if (ResCache.global != null) { try { Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8"); try { Resource.dumplist(Resource.remote().used(), w); } finally { w.close(); } } catch (IOException e) { } } System.exit(0); }
public static boolean generateHandler(Registry configSystemRegistry, String resourceFullPath) throws RegistryException, XMLStreamException { RegistryContext registryContext = configSystemRegistry.getRegistryContext(); if (registryContext == null) { return false; } Resource resource = configSystemRegistry.get(resourceFullPath); if (resource != null) { String content = null; if (resource.getContent() != null) { content = RegistryUtils.decodeBytes((byte[]) resource.getContent()); } if (content != null) { OMElement handler = AXIOMUtil.stringToOM(content); if (handler != null) { OMElement dummy = OMAbstractFactory.getOMFactory().createOMElement("dummy", null); dummy.addChild(handler); try { configSystemRegistry.beginTransaction(); boolean status = RegistryConfigurationProcessor.updateHandler( dummy, configSystemRegistry.getRegistryContext(), HandlerLifecycleManager.USER_DEFINED_HANDLER_PHASE); configSystemRegistry.commitTransaction(); return status; } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to add handler", e); } } } } return false; }
/** * Search for a resource in a local path, or the main repository path. * * @param path the resource name * @param loaders optional list of module loaders * @param localRoot a repository to look first * @return the resource * @throws IOException if an I/O error occurred */ public Resource findResource(String path, ModuleLoader[] loaders, Repository localRoot) throws IOException { // Note: as an extension to the CommonJS modules API // we allow absolute module paths for resources File file = new File(path); if (file.isAbsolute()) { Resource res; outer: if (loaders != null) { // loaders must contain at least one loader assert loaders.length > 0 && loaders[0] != null; for (ModuleLoader loader : loaders) { res = new FileResource(path + loader.getExtension()); if (res.exists()) { break outer; } } res = new FileResource(path + loaders[0].getExtension()); } else { res = new FileResource(file); } res.setAbsolute(true); return res; } else if (localRoot != null && (path.startsWith("./") || path.startsWith("../"))) { String newpath = localRoot.getRelativePath() + path; return findResource(newpath, loaders, null); } else { return config.getResource(normalizePath(path), loaders); } }
private static void read_file(EventLoader event_loader, String path, boolean need_cache) { Pair<Long, List<String>> b = null; try { b = read(path); } catch (FileNotFoundException e) { response_not_found(event_loader, path); return; } catch (IOException e) { event_loader.log.error( "request:" + event_loader.request_path() + " read failed for read file " + path, e); response_not_found(event_loader, path); return; } if (b == null || b.getValue().isEmpty()) { response_not_found(event_loader, path); return; } else { if (need_cache && b.getKey() < instance.file_max_size) { Resource r = new Resource(b.getValue()); r.file = new File(path); r.last_modify_time = last_modify_time(path); file_map.put(MyMath.encryptionWithMD5(path), r); } write(b.getValue(), event_loader); } }
public Template createTemplateForUri(String[] uri) { Template t; if (!isReloadEnabled()) { for (String anUri : uri) { t = createTemplateFromPrecompiled(anUri); if (t != null) { return t; } } } Resource resource = null; for (String anUri : uri) { Resource r = getResourceForUri(anUri); if (r.exists()) { resource = r; break; } } if (resource != null) { if (precompiledGspMap != null && precompiledGspMap.size() > 0) { if (LOG.isWarnEnabled()) { LOG.warn( "Precompiled GSP not found for uri: " + Arrays.asList(uri) + ". Using resource " + resource); } } return createTemplate(resource); } return null; }
@Override public void onBindViewHolder(ResourceViewHolder holder, final int position) { final Resource item = items.get(position); Context context = holder.itemView.getContext(); holder.iconView.setImageResource(item.getDrawableRes()); Resource.ResourceStyle style = item.getStyle(); holder.itemView.setBackgroundColor(ContextCompat.getColor(context, style.getResourceColor())); holder.titleView.setTextColor(ContextCompat.getColor(context, style.getTitleColorPrimary())); holder.titleView.setBackgroundColor( ContextCompat.getColor(context, style.getColorPrimaryDark())); holder.titleView.setText(item.getTextRes()); final Drawable itemIcon = ContextCompat.getDrawable(context, item.getDrawableRes()).mutate(); Drawable compatDrawable = DrawableCompat.wrap(itemIcon); DrawableCompat.setTint( compatDrawable, ContextCompat.getColor(context, style.getColorPrimary())); if (mOnItemClickListener != null) { holder.itemView.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { mOnItemClickListener.onItemClick(v, position); } }); } }
private static void addTypeToAll(Resource type, Set<Resource> candidates) { List<Resource> types = equivalentTypes(type); for (Resource element : candidates) { Resource resource = element; for (int i = 0; i < types.size(); i += 1) resource.addProperty(RDF.type, types.get(i)); } }
public List<String> getResourceList() { ArrayList<String> resources = new ArrayList<>(); for (Resource res : getCurrentConfig().getAllResources()) { resources.add(res.getName()); } return resources; }
public void newwidget(int id, String type, Coord c, int parent, Object... args) throws InterruptedException { WidgetFactory f; if (type.indexOf('/') >= 0) { int ver = -1, p; if ((p = type.indexOf(':')) > 0) { ver = Integer.parseInt(type.substring(p + 1)); type = type.substring(0, p); } Resource res = Resource.load(type, ver); res.loadwaitint(); f = res.layer(Resource.CodeEntry.class).get(WidgetFactory.class); } else { f = Widget.gettype(type); } synchronized (this) { Widget pwdg = widgets.get(parent); if (pwdg == null) throw (new UIException("Null parent widget " + parent + " for " + id, type, args)); Widget wdg = f.create(c, pwdg, args); bind(wdg, id); wdg.binded(); if (wdg instanceof MapView) mainview = (MapView) wdg; } }
private LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> buildRequestMap313() { LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>(); ResourceMapping resourceMapping = new ResourceMapping(getDataSource(), resourceQuery); for (Resource resource : (List<Resource>) resourceMapping.execute()) { String url = resource.getUrl(); String role = resource.getRole(); RequestMatcher key = resource.getMatchType().equalsIgnoreCase("ant") ? new AntPathRequestMatcher(url) : new RegexRequestMatcher(url, null); if (requestMap.containsKey(key)) { requestMap.get(key).add(new SecurityConfig(role.trim())); } else { requestMap.put(key, SecurityConfig.createList(role)); } } System.out.println("SecurityMetadataSource resourceQuery : " + resourceQuery); System.out.println("SecurityMetadataSource resourceMapping : " + resourceMapping); return requestMap; }
/** * Precomit the transaction. If it is an optimistic transaction lock all resources. If any * resource has been changed, since acquired, the precommit fails. */ public boolean precomit(int transactionId) { Validate.isTrue(transactionId != 0); Instance i = transactions.get(transactionId); Validate.isTrue(i.state == State.Optimistic || i.state == State.Precomit); if (i.state == State.Precomit) { return true; } for (String name : i.resources.keySet()) { // // Check that the resource hasn't been used and lock the // resource. // Resource localResource = i.resources.get(name); Resource masterResource = master.get(name); if (masterResource.hasChanged(localResource) || !masterResource.lock()) { rollback(transactionId); return false; } } i.state = State.Precomit; saveTransactionState(); return true; }
public void draw(GOut g) { try { Resource res = item.res.get(); Tex tex = res.layer(Resource.imgc).tex(); drawmain(g, tex); if (item.num >= 0) { g.atext(Integer.toString(item.num), tex.sz(), 1, 1); } else if (itemnum.get() != null) { g.aimage(itemnum.get(), tex.sz(), 1, 1); } if (item.meter > 0) { double a = ((double) item.meter) / 100.0; g.chcolor(255, 255, 255, 64); Coord half = Inventory.isqsz.div(2); g.prect(half, half.inv(), half, a * Math.PI * 2); g.chcolor(); } if (olcol.get() != null) { if (cmask != res) { mask = null; if (tex instanceof TexI) mask = ((TexI) tex).mkmask(); cmask = res; } if (mask != null) { g.chcolor(olcol.get()); g.image(mask, Coord.z); g.chcolor(); } } } catch (Loading e) { missing.loadwait(); g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz); } }
public static boolean addHandler(Registry configSystemRegistry, String payload) throws RegistryException, XMLStreamException { String name; OMElement element = AXIOMUtil.stringToOM(payload); if (element != null) { name = element.getAttributeValue(new QName("class")); } else return false; if (isHandlerNameInUse(name)) throw new RegistryException("The added handler name is already in use!"); String path = getContextRoot() + name; Resource resource; if (!handlerExists(configSystemRegistry, name)) { resource = new ResourceImpl(); } else { throw new RegistryException("The added handler name is already in use!"); } resource.setContent(payload); try { configSystemRegistry.beginTransaction(); configSystemRegistry.put(path, resource); generateHandler(configSystemRegistry, path); configSystemRegistry.commitTransaction(); } catch (Exception e) { configSystemRegistry.rollbackTransaction(); throw new RegistryException("Unable to generate handler", e); } return true; }
public void testBackwardCompatibility() throws RegistryException { Registry rootRegistry = embeddedRegistryService.getSystemRegistry(); Resource r1 = rootRegistry.newResource(); r1.setContent("r1 content"); rootRegistry.put("/test/comments/r1", r1); rootRegistry.addComment( "/test/comments/r1", new Comment("backward-compatibility1 on this resource :)")); rootRegistry.addComment( "/test/comments/r1", new Comment("backward-compatibility2 on this resource :)")); String sql = "SELECT REG_COMMENT_ID FROM REG_COMMENT C, REG_RESOURCE_COMMENT RC " + "WHERE C.REG_COMMENT_TEXT LIKE ? AND C.REG_ID=RC.REG_COMMENT_ID"; Resource queryR = rootRegistry.newResource(); queryR.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE); queryR.addProperty( RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE); rootRegistry.put("/beep/x", queryR); Map<String, String> params = new HashMap<String, String>(); params.put("query", sql); params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.COMMENTS_RESULT_TYPE); params.put("1", "backward-compatibility1%"); Collection qResults = rootRegistry.executeQuery("/beep/x", params); String[] qPaths = (String[]) qResults.getContent(); assertEquals("Query result count should be 1", qPaths.length, 1); }
/** * Invoke a script from the command line. * * @param scriptResource the script resource of path * @param scriptArgs an array of command line arguments * @return the return value * @throws IOException an I/O related error occurred * @throws JavaScriptException the script threw an error during compilation or execution */ public Object runScript(Object scriptResource, String... scriptArgs) throws IOException, JavaScriptException { Resource resource; if (scriptResource instanceof Resource) { resource = (Resource) scriptResource; } else if (scriptResource instanceof String) { resource = findResource((String) scriptResource, null, null); } else { throw new IOException("Unsupported script resource: " + scriptResource); } if (!resource.exists()) { throw new FileNotFoundException(scriptResource.toString()); } Context cx = contextFactory.enterContext(); try { Object retval; Map<Trackable, ReloadableScript> scripts = getScriptCache(cx); commandLineArgs = Arrays.asList(scriptArgs); ReloadableScript script = new ReloadableScript(resource, this); scripts.put(resource, script); mainScope = new ModuleScope(resource.getModuleName(), resource, globalScope, mainWorker); retval = mainWorker.evaluateScript(cx, script, mainScope); mainScope.updateExports(); return retval instanceof Wrapper ? ((Wrapper) retval).unwrap() : retval; } finally { Context.exit(); } }
@SuppressWarnings("SimplifiableIfStatement") public static boolean shouldShowGob(Gob gob) { Resource res = gob.getres(); if (res == null) return true; if (res.name.startsWith("gfx/terobjs/trees/")) return trees.isEnabled(); if (res.name.startsWith("gfx/terobjs/bushes/")) return bushes.isEnabled(); if (res.name.startsWith("gfx/terobjs/plants/") && !res.basename().equals("trellis")) return plants.isEnabled(); if (res.name.startsWith("gfx/terobjs/arch/palisade") || res.name.startsWith("gfx/terobjs/arch/pole") || res.name.startsWith("gfx/terobjs/arch/brickwall")) return fences.isEnabled(); if (res.name.startsWith("gfx/terobjs/arch/logcabin") || res.name.startsWith("gfx/terobjs/arch/stonemansion") || res.name.startsWith("gfx/terobjs/arch/timberhouse") || res.name.startsWith("gfx/terobjs/arch/logcabin") || res.name.startsWith("gfx/terobjs/arch/stonestead") || res.name.startsWith("gfx/terobjs/arch/greathall") || res.name.startsWith("gfx/terobjs/arch/stonetower")) return houses.isEnabled(); return true; }
/** Return a list of all tests of the given type, according to the current filters */ public List<Resource> findTestsOfType(Resource testType) { ArrayList<Resource> result = new ArrayList<>(); StmtIterator si = testDefinitions.listStatements(null, RDF.type, testType); while (si.hasNext()) { Resource test = si.nextStatement().getSubject(); boolean accept = true; // Check test status Literal status = (Literal) test.getProperty(RDFTest.status).getObject(); if (approvedOnly) { accept = status.getString().equals(STATUS_FLAGS[0]); } else { accept = false; for (String STATUS_FLAG : STATUS_FLAGS) { if (status.getString().equals(STATUS_FLAG)) { accept = true; break; } } } // Check for blocked tests for (String BLOCKED_TEST : BLOCKED_TESTS) { if (BLOCKED_TEST.equals(test.toString())) { accept = false; } } // End of filter tests if (accept) { result.add(test); } } return result; }
private static void extractList(List<String> output, Resource head) { if (head.hasProperty(RDF.first)) output.add(head.getProperty(RDF.first).getObject().asLiteral().getString()); if (head.hasProperty(RDF.rest)) extractList(output, head.getProperty(RDF.rest).getObject().asResource()); }
@Test public void testPresentTotalCount() throws URISyntaxException { Integer totalResults = new Integer(17); Resource thisMetaPage = createMetadata(true, totalResults); Literal tr = thisMetaPage.getModel().createTypedLiteral(totalResults); assertTrue(thisMetaPage.hasProperty(OpenSearch.totalResults, tr)); }
private void addWorkers() { ResourceType type; ArrayList<Resource> users = null; ArrayList<Project> projects = null; Random random = new Random(1l); try { type = resourceTypeDAO.getResourceTypeByResourceTypeName("human"); users = resourceDAO.getResourcesByResourceType(type); projects = projectDAO.getAllProjects(); } catch (Exception e) { e.printStackTrace(); } for (Project project : projects) { int workers = random.nextInt(11) + 5; Resource user = users.get(random.nextInt(users.size())); try { resourceDAO.insertUserTask(user.getResourceID(), project.getProjectID(), true); } catch (UserWorkOnThisProjectException e) { e.printStackTrace(); } for (int i = 0; i < workers; ++i) { user = users.get(random.nextInt(users.size())); try { resourceDAO.insertUserTask( user.getResourceID(), project.getProjectID(), (random.nextInt(5) == 0)); } catch (UserWorkOnThisProjectException e) { System.out.println( "User already assigned, but don't worry, there are plenty to choose from"); } } } }
public static String RenderTemplatePage(Bindings b, String templateName) throws IOException { MediaType mt = MediaType.TEXT_HTML; Resource config = model.createResource("eh:/root"); Mode prefixMode = Mode.PreferPrefixes; ShortnameService sns = new StandardShortnameService(); List<Resource> noResults = CollectionUtils.list(root.inModel(model)); Graph resultGraph = graphModel.getGraph(); resultGraph.getPrefixMapping().setNsPrefix("api", API.NS); resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode())); APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL); VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns); VelocityRendering vx = new VelocityRendering(b, rs, vr); VelocityEngine ve = vx.createVelocityEngine(); VelocityContext vc = vx.createVelocityContext(b); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(bos, "UTF-8"); Template t = ve.getTemplate(templateName); t.merge(vc, w); w.close(); return bos.toString(); }
private void addDescriptions() throws IOException { RandomAccessFile f = new RandomAccessFile("randomDescription.csv", "r"); String dataString = null; Random random = new Random(1l); ArrayList<String> descriptions = new ArrayList<String>(); while ((dataString = f.readLine()) != null) { descriptions.add(dataString); } f.close(); try { ArrayList<Resource> resources = resourceDAO.getAllResources(); for (Resource r : resources) { r.setDescription(descriptions.get(random.nextInt(descriptions.size()))); resourceDAO.updateResource(r); } } catch (DAOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ResourceNameExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ResourceHasActiveProjectException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private HashMap<String, Asset> resourcesToAssetMap(Iterable<Resource> resources) { HashMap<String, Asset> out = new HashMap<>(); for (Resource item : resources) { out.put(item.getId(), resourceToAsset(item)); } return out; }
/** * Acquire a resource in a transaction context. * * @param transactionId - The transaction instance context. * @param name - The base name of the resource. * @return - The alias name of the resource in the transaction context. * @throws StatusException */ public String acquire(int transactionId, String name) throws StatusException { Resource resource; if (transactionId == 0) { // // TransactionId 0 is always valid. // if (!master.containsKey(name)) { master.put(name, new Resource()); } resource = master.get(name); } else { // // Get the resource from the local list or retrieve // from the master list. // Instance i = transactions.get(transactionId); Validate.isTrue(i.state == State.Optimistic || i.state == State.Precomit); if (i.resources.containsKey(name)) { resource = i.resources.get(name); } else { boolean lock = (i.state == State.Precomit); resource = acquire(name, lock); i.resources.put(name, resource); } } saveTransactionState(); return resource.getName(name); }
/** * @native(docker) Scenario: Configure a job with over ssh publishing Given I have installed the * "publish-over-ssh" plugin And a docker fixture "sshd" And a job When I configure docker * fixture as SSH site And I configure the job to use a unsecure keyfile with passphrase And I * copy resource "scp_plugin/lorem-ipsum-scp.txt" into workspace And I publish * "lorem-ipsum-scp.txt" with SSH plugin And I save the job And I build the job Then the build * should succeed And SSH plugin should have published "lorem-ipsum-scp.txt" on docker fixture * And SSH plugin should have create with exec "testecho" on docker fixture */ @Test public void ssh_key_path_and_key_password_and_exec_publishing() throws IOException, InterruptedException { SshdContainer sshd = docker.start(SshdContainer.class); Resource cp_file = resource(resourceFilePath); File sshFile = sshd.getEncryptedPrivateKey(); FreeStyleJob j = jenkins.jobs.create(); jenkins.configure(); this.commonConfigKeyFileAndPassword(sshFile, false); InstanceSite is = this.instanceConfig(sshd); this.advancedConfigAllowExec(is, sshd); jenkins.save(); this.configureJobWithExec(j, cp_file); j.save(); j.startBuild().shouldSucceed(); sshd.cp(tempCopyFile, tempPath); sshd.cp(tempCopyFileEcho, tempPath); assertThat( FileUtils.readFileToString(new File(tempCopyFile)), CoreMatchers.is(cp_file.asText())); assertThat( FileUtils.readFileToString(new File(tempCopyFileEcho)), CoreMatchers.is("i was here\n")); }
/** * @param _sResource * @return */ public <T extends Resource> T getResourceRef(final Class<T> type, final String path) { T resource = null; Resource genericResource = resources.get(path); if (genericResource != null) { if (type.isInstance(genericResource)) { resource = type.cast(genericResource); } else { System.err.println( "Resource '" + path + ":" + genericResource.getClass().toString() + "' is not of type '" + type.getName()); } } else { resource = loadResource(type, path); if (resource != null) { resources.put(path, resource); } } if (resource != null) { addResourceRef(resource); } return resource; }