com.streamsets.pipeline.api.ext.json.delegate.ClassDelegate Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2021 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*
* limitations under the License.
*/
package com.streamsets.pipeline.api.ext.json.delegate;
import com.streamsets.pipeline.api.ext.json.JsonDelegate;
import com.streamsets.pipeline.api.ext.json.JsonException;
import com.streamsets.pipeline.api.ext.json.JsonRule;
import java.util.Map;
/**
* JSON Delegate used to produce Human-readable strings from Class objects.
*/
public class ClassDelegate implements JsonDelegate {
private final JsonRule annotation;
public ClassDelegate(JsonRule annotation) {
this.annotation = annotation;
}
@Override
public JsonRule annotation() {
return this.annotation;
}
@Override
public String serialize(Class clazz, Map options) {
return clazz == null ? null: clazz.getName();
}
@Override
public Class deserialize(String value, Map options) {
ClassLoader workingClassLoader = getClassLoader(options);
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();;
ClassLoader containerClassloader = workingClassLoader != null ? workingClassLoader : currentClassLoader;
try {
if (workingClassLoader != null) {
Thread.currentThread().setContextClassLoader(workingClassLoader);
}
try {
return value == null ? null : Class.forName(value, true, containerClassloader);
} catch (ClassNotFoundException exception) {
throw new JsonException(String.format("Class %s not found in your specified class loader", value), exception);
}
} finally {
if (workingClassLoader != null) {
Thread.currentThread().setContextClassLoader(currentClassLoader);
}
}
}
private final ClassLoader getClassLoader(Map options) {
Object classLoader = findOption(options, Parameters.CLASS_LOADER);
return classLoader == null ? null : (ClassLoader) classLoader;
}
public interface Parameters {
String CLASS_LOADER = "$classLoader";
}
}