Transform an existing file into the target class.

@param <T>
@param securityContext
@param uuid
@param fileType
@return transformed file
@throws FrameworkException
@throws IOException
771633
public static <T extends File> T transformFile(final SecurityContext securityContext, final String uuid, final Class<T> fileType) throws FrameworkException, IOException {

		AbstractFile existingFile = getFileByUuid(securityContext, uuid);

		if (existingFile != null) {

			existingFile.unlockSystemPropertiesOnce();
			existingFile.setProperties(securityContext, new PropertyMap(AbstractNode.type, fileType == null ? File.class.getSimpleName() : fileType.getSimpleName()));

			existingFile = getFileByUuid(securityContext, uuid);

			return (T)(fileType != null ? fileType.cast(existingFile) : (File) existingFile);
		}

		return null;
	}
850872
private void writeUid(File uidFile, String uid) {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(uidFile));
			bw.write(uid);
		}
		catch (IOException ioe) {}
		finally { if (bw != null) { try { bw.close(); } catch (IOException ioe) {} } }
	}
659455
public static void updateMetadata(final File file, final PropertyMap map, final boolean calcChecksums) throws FrameworkException {

		final java.io.File fileOnDisk = file.getFileOnDisk(false);

		if (fileOnDisk != null && fileOnDisk.exists()) {

			try {

				final PropertyKey<Long> fileModificationDateKey = StructrApp.key(File.class, "fileModificationDate");
				final PropertyKey<String> contentTypeKey        = StructrApp.key(File.class, "contentType");
				final PropertyKey<Long> sizeKey                 = StructrApp.key(File.class, "size");

				String contentType = file.getContentType();

				// Don't overwrite existing MIME type
				if (StringUtils.isBlank(contentType)) {

					try {

						contentType = getContentMimeType(file);
						map.put(contentTypeKey, contentType);

					} catch (IOException ex) {
						logger.debug("Unable to detect content MIME type", ex);
					}
				}

				map.put(fileModificationDateKey, fileOnDisk.lastModified());

				if (calcChecksums) {
					map.putAll(getChecksums(file, fileOnDisk));
				}

				if (contentType != null) {

					// modify type when image type is detected AND the type is "File"
					if (contentType.startsWith("image/") && Boolean.FALSE.equals(Image.class.isAssignableFrom(file.getClass())) && File.class.getSimpleName().equals(file.getClass().getSimpleName())) {
						map.put(AbstractNode.type, Image.class.getSimpleName());
					}
				}

				long fileSize = FileHelper.getSize(fileOnDisk);
				if (fileSize > 0) {

					map.put(sizeKey, fileSize);
				}

				file.unlockSystemPropertiesOnce();
				file.setProperties(file.getSecurityContext(), map);

			} catch (IOException ioex) {
				logger.warn("Unable to access {} on disk: {}", fileOnDisk, ioex.getMessage());
			}
		}
	}
486714
@Override
    public Filter createFilter(FilterConfig filterConfig) {
        Binding binding = new Binding();
        SecurityComponents sc = this.createSecurityComponents();
        binding.setVariable("securityComponents", sc);
        binding.setVariable("securityRealm",this);
        BeanBuilder builder = new BeanBuilder();
        builder.parse(filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),binding);
        
        WebApplicationContext context = builder.createApplicationContext();
        
        return (Filter) context.getBean("legacy");
    }
208835
public static JMFType parse(String filename) {
    try {
      return parse(new FileReader(filename));
    } catch(IOException e) {
      // No FFDC needed
          IllegalArgumentException ee = new IllegalArgumentException(e.getMessage());
          ee.initCause(e);
          throw ee;
    }
  }
1237268
@SuppressWarnings("unchecked") // safe since the proxy implements type
  private <T> T createFakeResource(Class<T> type, final String name) {
    return (T) Proxy.newProxyInstance(
        FakeClientBundleProvider.class.getClassLoader(),
        new Class<?>[] {type},
        new InvocationHandler() {
          @Override
          public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            Class<?> returnType = method.getReturnType();
            if (returnType == String.class) {
              return name;
            } else if (returnType == SafeHtml.class) {
              return SafeHtmlUtils.fromTrustedString(name);
            } else if (returnType == SafeUri.class) {
              return UriUtils.fromTrustedString(name);
            } else if (returnType == boolean.class) {
              return false;
            } else if (returnType == int.class) {
              return 0;
            } else if (method.getParameterTypes()[0] == ResourceCallback.class) {
              // Read the underlying resource type out of the generic parameter
              // in the method's argument
              Class<?> resourceType = 
                  (Class<?>) 
                  ((ParameterizedType) args[0].getClass().getGenericInterfaces()[0])
                  .getActualTypeArguments()[0];
              ((ResourceCallback<ResourcePrototype>) args[0]).onSuccess(
                  (ResourcePrototype) createFakeResource(resourceType, name));
              return null;
            } else {
              throw new IllegalArgumentException(
                  "Unexpected return type for method " + method.getName());
            }
          }
        });
  }
1177479
private void init(final SecurityContext securityContext, final Class type, final Field field, final String path) throws FrameworkException {

		final QueryConfig config = getConfig(path);

		config.handleTypeArguments(securityContext, type, field.getArguments());

		final SelectionSet selectionSet = field.getSelectionSet();
		if (selectionSet != null) {

			for (final Selection selection : selectionSet.getSelections()) {

				if (selection instanceof Field) {

					final Field childField      = (Field)selection;
					final SelectionSet childSet = childField.getSelectionSet();
					final PropertyKey key       = StructrApp.key(type, childField.getName());
					final Class relatedType     = key.relatedType() != null ? key.relatedType() : type;

					// add field to property set
					config.addPropertyKey(key);
					config.handleFieldArguments(securityContext, relatedType, field, childField);

					// recurse
					if (childSet != null) {

						init(securityContext, relatedType, childField, path + "/" + childField.getName());
					}
				}
			}
		}
	}
1096620
public Deferred<byte[]> getUIDAsync(final UniqueIdType type, final String name) {
    if (name == null || name.isEmpty()) {
      throw new IllegalArgumentException("Missing UID name");
    }
    switch (type) {
      case METRIC:
        return metrics.getIdAsync(name);
      case TAGK:
        return tag_names.getIdAsync(name);
      case TAGV:
        return tag_values.getIdAsync(name);
      default:
        throw new IllegalArgumentException("Unrecognized UID type");
    }
  }
687811
public WyalFile.Name convert(QualifiedName id, String suffix, SyntacticItem context) {
		return convert(id.getUnit(), id.getName().get().concat(suffix), context);
	}
228835
@SuppressWarnings({"unchecked"})
    public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException {
        acl.checkPermission(Item.CREATE);
        src.checkPermission(Item.EXTENDED_READ);
        XmlFile srcConfigFile = Items.getConfigFile(src);
        if (!src.hasPermission(Item.CONFIGURE)) {
            Matcher matcher = AbstractItem.SECRET_PATTERN.matcher(srcConfigFile.asString());
            while (matcher.find()) {
                if (Secret.decrypt(matcher.group(1)) != null) {
                    // AccessDeniedException2 does not permit a custom message, and anyway redirecting the user to the login screen is obviously pointless.
                    throw new AccessDeniedException(Messages.ItemGroupMixIn_may_not_copy_as_it_contains_secrets_and_(src.getFullName(), Jenkins.getAuthentication().getName(), Item.PERMISSIONS.title, Item.EXTENDED_READ.name, Item.CONFIGURE.name));
                }
            }
        }
        src.getDescriptor().checkApplicableIn(parent);
        acl.getACL().checkCreatePermission(parent, src.getDescriptor());
        ItemListener.checkBeforeCopy(src, parent);

        T result = (T)createProject(src.getDescriptor(),name,false);

        // copy config
        Files.copy(Util.fileToPath(srcConfigFile.getFile()), Util.fileToPath(Items.getConfigFile(result).getFile()),
                StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);

        // reload from the new config
        final File rootDir = result.getRootDir();
        result = Items.whileUpdatingByXml(new NotReallyRoleSensitiveCallable<T,IOException>() {
            @Override public T call() throws IOException {
                return (T) Items.load(parent, rootDir);
            }
        });
        result.onCopiedFrom(src);

        add(result);
        ItemListener.fireOnCopied(src,result);
        Jenkins.getInstance().rebuildDependencyGraphAsync();

        return result;
    }
767880
byte[] transformCandidate(byte[] classfileBuffer) {
        // reader --> serial version uid adder --> process candidate hook adapter --> tracing --> writer
        ClassReader reader = new ClassReader(classfileBuffer);
        ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);

        ClassVisitor visitor = writer;
        StringWriter stringWriter = null;
        if (tc.isDumpEnabled()) {
            stringWriter = new StringWriter();
            visitor = new CheckClassAdapter(visitor);
            visitor = new TraceClassVisitor(visitor, new PrintWriter(stringWriter));
        }
        visitor = new ClassAvailableHookClassAdapter(visitor);
        visitor = new SerialVersionUIDAdder(visitor);

        // Process the class
        reader.accept(visitor, 0);

        if (stringWriter != null && tc.isDumpEnabled()) {
            Tr.dump(tc, "Transformed class", stringWriter);
        }

        return writer.toByteArray();
    }
638500
public ServerBuilder setIcon(BufferedImage icon, String fileType) {
        delegate.setIcon(icon, fileType);
        return this;
    }
1298157
private static int toIntAccessType(String accessType) throws SecurityException {
	accessType = accessType.trim().toLowerCase();
	if (accessType.equals("setting")) return TYPE_SETTING;
	else if (accessType.equals("file")) return TYPE_FILE;
	else if (accessType.equals("direct_java_access")) return TYPE_DIRECT_JAVA_ACCESS;
	// else if(accessType.equals("search")) return TYPE_SEARCH;
	else if (accessType.equals("mail")) return TYPE_MAIL;
	// else if(accessType.equals("scheduled_task")) return TYPE_SCHEDULED_TASK;
	else if (accessType.equals("datasource")) return TYPE_DATASOURCE;
	else if (accessType.equals("mapping")) return TYPE_MAPPING;
	else if (accessType.equals("remote")) return TYPE_REMOTE;
	else if (accessType.equals("custom_tag")) return TYPE_CUSTOM_TAG;
	else if (accessType.equals("cfx_setting")) return TYPE_CFX_SETTING;
	else if (accessType.equals("cfx_usage")) return TYPE_CFX_USAGE;
	else if (accessType.equals("debugging")) return TYPE_DEBUGGING;
	else if (accessType.equals("tag_execute")) return TYPE_TAG_EXECUTE;
	else if (accessType.equals("tag_import")) return TYPE_TAG_IMPORT;
	else if (accessType.equals("tag_object")) return TYPE_TAG_OBJECT;
	else if (accessType.equals("tag_registry")) return TYPE_TAG_REGISTRY;
	else if (accessType.equals("search")) return TYPE_SEARCH;
	else if (accessType.equals("cache")) return TYPE_CACHE;
	else if (accessType.equals("gateway")) return TYPE_GATEWAY;
	else if (accessType.equals("orm")) return TYPE_ORM;
	else if (accessType.startsWith("scheduled_task")) return TYPE_SCHEDULED_TASK;
	else throw new SecurityException("invalid access type [" + accessType + "]",
		"valid access types are [setting,file,direct_java_access,mail,datasource,mapping,custom_tag,cfx_setting" + "cfx_usage,debugging]");

    }
729192
public static UUID uuid(ByteBuffer bb) {
        bb = bb.slice();
        return new UUID(bb.getLong(), bb.getLong());
    }
393320
public static String fileTypeAsString( int fileType ) {

		String result;
		switch( fileType ) {
		case AGGREGATOR:
			result = "aggregator";
			break;

		case GRAPH:
			result = "graph";
			break;

		case INSTANCE:
			result = "intsnace";
			break;

		case UNDETERMINED:
			result = "undetermined";
			break;

		default:
			result = "unknown";
			break;
		}

		return result;
	}
403929
public static void preRegisterFileManager(Context context) {
    context.put(
        JavaFileManager.class,
        new Context.Factory<JavaFileManager>() {
          @Override
          public JavaFileManager make(Context c) {
            return new MaskedFileManager(c);
          }
        });
  }
185870
public void encryptFile(File file, boolean replace) throws MissingParameterException, IOException {

		if(file == null || !file.exists()){
			throw new MissingParameterException("File not specified or file does not exist.");
		}
		
		FileInputStream fis = new FileInputStream(file);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
		
		encryptStream(fis, baos);
		
		File tmpEncrypted = File.createTempFile("commonsencryption", RandomStringUtils.randomAlphanumeric(10));
		
		if(!tmpEncrypted.exists()){
			throw new IOException("Failed to encrypt file.");
		}
		
		FileOutputStream fos = new FileOutputStream(tmpEncrypted);
		
		IOUtils.write(baos.toByteArray(),fos);
		
		fos.close();
		
		if(replace){
			File bkpFile = FileUtils.getFile(file.getAbsolutePath() + ".bkp");
			FileUtils.moveFile(file, bkpFile);
			
			try{
			
				FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath()));
			
			}catch(IOException e){
				throw new IOException("Failed to encrypt file. Existing file saved with \".bkp\": " + e.getMessage(),e);
			}
			
			bkpFile.delete();
			
		}else{
			
			FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath() + ".encrypted"));
			
		}
		
	}